Files
wikideck/shared/duel/profile.ts

115 lines
5.9 KiB
TypeScript

/**
* Building the frozen CardProfile (data review §3) from data the host already has or fetches once
* through the polite Wikimedia client. Pure: this file never fetches. The host:
* 1. takes the cached PageEnrichment (description, wikidataId, categories),
* 2. fetches the item once with wikidataEntityParams([qid, …]) (≤ 50 ids per request),
* 3. fetches the labels of the P31/P279 classes it doesn't know with wikidataLabelParams(ids),
* 4. optionally adds outlinks (prop=links, ns0) as pageIds,
* 5. calls profileFromSources() and stores the result per tokenId forever.
* Owner: duel-cards.
*/
import type { PageEnrichment } from '../enrichment.ts';
import type { CardProfile, WikidataClass } from './classify.ts';
export const PROFILE_PROPERTIES = {
instanceOf: 'P31', subclassOf: 'P279', country: 'P17', citizenship: 'P27',
birth: 'P569', death: 'P570', inception: 'P571', start: 'P580', pointInTime: 'P585',
} as const;
/** Properties whose item values count as "cited" for the Linked tier (DUEL_DESIGN §6). */
export const CITE_PROPERTIES = ['P17', 'P27', 'P131', 'P361', 'P527', 'P463', 'P102', 'P108', 'P69', 'P19', 'P20', 'P710', 'P1344', 'P276'] as const;
/** Action API parameters for wbgetentities (claims only, so the payload stays small). */
export function wikidataEntityParams(qids: readonly string[]): Record<string, string> {
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' };
}
/** Action API parameters for class labels (English). */
export function wikidataLabelParams(qids: readonly string[]): Record<string, string> {
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' };
}
/** The slice of a wbgetentities entity this module reads. Unknown shapes are ignored, never thrown on. */
export interface WikidataEntity {
id?: string;
claims?: Record<string, readonly {
rank?: string;
mainsnak?: { snaktype?: string; datavalue?: { type?: string; value?: unknown } };
}[]>;
}
function claimValues(entity: WikidataEntity | null | undefined, property: string): unknown[] {
const statements = entity?.claims?.[property];
if (!Array.isArray(statements)) return [];
return statements
.filter(s => s?.rank !== 'deprecated' && s?.mainsnak?.snaktype === 'value')
.map(s => s.mainsnak?.datavalue?.value)
.filter(v => v !== undefined);
}
function itemIds(entity: WikidataEntity | null | undefined, property: string): string[] {
return claimValues(entity, property)
.map(v => (v && typeof v === 'object' && 'id' in v && typeof (v as { id: unknown }).id === 'string') ? (v as { id: string }).id : null)
.filter((id): id is string => id !== null && /^Q\d+$/.test(id));
}
/** Years from Wikidata time values ("+1909-04-29T00:00:00Z", "-0044-03-15T…"). */
function years(entity: WikidataEntity | null | undefined, property: string): number[] {
return claimValues(entity, property)
.map(v => (v && typeof v === 'object' && 'time' in v) ? String((v as { time: unknown }).time) : '')
.map(t => /^([+-])0*(\d{1,6})-/.exec(t))
.filter((m): m is RegExpExecArray => m !== null)
.map(m => (m[1] === '-' ? -1 : 1) * Number(m[2]))
.filter(y => y !== 0);
}
/** Q-ids whose labels the host must look up to classify this entity. */
export function classIdsOf(entity: WikidataEntity | null | undefined): string[] {
return [...new Set([...itemIds(entity, 'P31'), ...itemIds(entity, 'P279')])].sort();
}
export interface ProfileSources {
enrichment: Pick<PageEnrichment, 'description' | 'wikidataId' | 'categories' | 'revisionId'>;
/** The card's own wbgetentities entity, or null when it has no item or the fetch is pending. */
entity?: WikidataEntity | null;
/** English labels for class Q-ids; missing labels are kept as the bare Q-id. */
labels?: Readonly<Record<string, string>>;
/** Superclass chain for the P31 classes (P279, up to 4 hops), nearest first, if the host resolved it. */
superclasses?: readonly WikidataClass[];
/** ns0 outlinks resolved to pageIds. */
links?: readonly number[];
}
export function profileFromSources(src: ProfileSources): CardProfile {
const { enrichment, entity, labels = {} } = src;
const label = (id: string): WikidataClass => ({ id, label: labels[id] ?? id });
const countries = [...new Set([...itemIds(entity, 'P17'), ...itemIds(entity, 'P27')])].sort();
const yrs = [...new Set(['P569', 'P570', 'P571', 'P580', 'P585'].flatMap(p => years(entity, p)))].sort((a, b) => a - b);
const cites = [...new Set(CITE_PROPERTIES.flatMap(p => itemIds(entity, p)))].sort();
const subclassOf = [...itemIds(entity, 'P279').map(label), ...(src.superclasses ?? [])];
const profile: CardProfile = {
wikidataId: enrichment.wikidataId,
description: enrichment.description,
categories: [...enrichment.categories],
instanceOf: itemIds(entity, 'P31').map(label),
fetchedRevisionId: enrichment.revisionId,
};
if (subclassOf.length) profile.subclassOf = subclassOf;
if (countries.length) profile.countries = countries;
if (yrs.length) profile.years = yrs;
if (claimValues(entity, 'P570').length) profile.died = true;
if (cites.length) profile.cites = cites;
if (src.links?.length) profile.links = [...new Set(src.links)].sort((a, b) => a - b);
return profile;
}
/** A canonical JSON string of a profile, for storing, hashing and logging in the match record. */
export function canonicalProfile(profile: CardProfile): string {
const sortKeys = (v: unknown): unknown => Array.isArray(v) ? v.map(sortKeys)
: v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys((v as Record<string, unknown>)[k])]))
: v;
return JSON.stringify(sortKeys(profile));
}