// REFERENCES — docs/contributing/architecture.md#alias-aware-lookup-at-the-request-boundary: an id is adopted once and every declared // reference follows it. Adoption is an alias (`aliasOf` on the landed copy; the fold moves the // subject). A pack DECLARES which fields of which subject types hold another subject's id; the // kernel resolves those fields through the alias map — in the tree, whatever order the entries fold // in, and at the perform, so the vendor is asked about #7, never the local #3. // // One registry per process (a pack installed beside a world carries its own copy of the kernel). import type { SubjectFields } from './hash.ts'; export type ReferenceDeclaration = { /** the referencing subject type */ type: string; /** the referenced subject type */ to: string; /** the referenced subject's id, read from the referencing subject's fields (undefined: no reference) */ key: (fields: SubjectFields) => string | undefined; /** the fields to overlay once the referenced subject's id is `vendorId` */ adopt: (fields: SubjectFields, vendorId: string) => SubjectFields; }; /** The common case: one field holds the referenced subject's id as it is. */ export function referenceField(type: string, field: string, to: string): ReferenceDeclaration { return { type, to, key: (f) => (f[field] === undefined || f[field] === null ? undefined : String(f[field])), adopt: (_f, vendorId) => ({ [field]: vendorId }) }; } const REGISTRY = Symbol.for('volter.references'); const registry = (): Map => ((globalThis as Record)[REGISTRY] ??= new Map()) as Map; export function registerReferences(vendor: string, references: ReferenceDeclaration[]): void { registry().set(vendor, references); } export function packReferences(vendor: string): ReferenceDeclaration[] { return registry().get(vendor) ?? []; } /** `fields` of a `type` subject with every declared reference resolved through `aliases` * (`${type}:${oldId}` → newId, as `aliasesFrom` builds it). The same object when nothing applies. */ export function resolveReferences(vendor: string, type: string, fields: SubjectFields, aliases: Map): SubjectFields { if (aliases.size === 0) return fields; let out = fields; for (const ref of packReferences(vendor)) { if (ref.type !== type) continue; const key = ref.key(out); if (key === undefined) continue; const adopted = aliases.get(`${ref.to}:${key}`); if (adopted === undefined || adopted === key) continue; out = { ...out, ...ref.adopt(out, adopted) }; } return out; }