@drfed/models 0.2.0-dev.698 → 0.2.0-dev.703

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"document.mjs","names":["APObject"],"sources":["../src/document.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { MIMEType } from \"node:util\";\n\nimport {\n type $EntityType,\n Object as APObject,\n Accept,\n Activity,\n Add,\n Announce,\n Application,\n Arrive,\n Article,\n Block,\n Collection,\n CollectionPage,\n Create,\n Delete,\n Dislike,\n Flag,\n Follow,\n Group,\n Ignore,\n IntransitiveActivity,\n Invite,\n Join,\n Leave,\n Like,\n Link,\n Listen,\n Mention,\n Move,\n Note,\n Offer,\n OrderedCollection,\n OrderedCollectionPage,\n Organization,\n Person,\n Question,\n Read,\n Reject,\n Remove,\n Service,\n TentativeAccept,\n TentativeReject,\n Travel,\n Undo,\n Update,\n View,\n getEntityTypeById,\n} from \"@fedify/vocab\";\nimport { preloadedContexts } from \"@fedify/vocab-runtime\";\n\n/** The source property names and zero-based indexes leading to a finding. */\nexport type FieldPath = readonly (string | number)[];\n\nexport type DiagnosticCategory =\n | \"vocabulary\"\n | \"authority\"\n | \"support\"\n | \"compatibility\";\n\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\n/** Stable classifications; human-readable diagnostic messages may change. */\nexport const diagnosticReasons = {\n invalid_document_root: { category: \"vocabulary\", severity: \"error\" },\n non_json_value: { category: \"vocabulary\", severity: \"error\" },\n invalid_value_shape: { category: \"vocabulary\", severity: \"error\" },\n invalid_iri: { category: \"vocabulary\", severity: \"error\" },\n invalid_datetime: { category: \"vocabulary\", severity: \"error\" },\n invalid_multiplicity: { category: \"vocabulary\", severity: \"error\" },\n property_not_applicable: { category: \"vocabulary\", severity: \"error\" },\n invalid_context: { category: \"vocabulary\", severity: \"error\" },\n unauthorized_local_identity: { category: \"authority\", severity: \"error\" },\n server_owned_field_conflict: { category: \"authority\", severity: \"error\" },\n context_unavailable_offline: { category: \"support\", severity: \"error\" },\n unsupported_context_form: { category: \"support\", severity: \"error\" },\n unsupported_type: { category: \"support\", severity: \"error\" },\n unsupported_property: { category: \"support\", severity: \"error\" },\n unsupported_value_form: { category: \"support\", severity: \"error\" },\n processing_limit_exceeded: { category: \"support\", severity: \"error\" },\n diagnostic_limit_reached: { category: \"support\", severity: \"error\" },\n implicit_activitystreams_context: {\n category: \"compatibility\",\n severity: \"warning\",\n },\n extension_property_unchecked: {\n category: \"compatibility\",\n severity: \"warning\",\n },\n empty_property_list: { category: \"compatibility\", severity: \"warning\" },\n absent_identifier: { category: \"compatibility\", severity: \"warning\" },\n} as const satisfies Record<\n string,\n {\n readonly category: DiagnosticCategory;\n readonly severity: DiagnosticSeverity;\n }\n>;\n\nexport type DiagnosticReason = keyof typeof diagnosticReasons;\n\nexport interface Diagnostic {\n readonly reason: DiagnosticReason;\n readonly category: DiagnosticCategory;\n readonly severity: DiagnosticSeverity;\n readonly path: FieldPath;\n readonly message: string;\n}\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\n/** A proposed transformation; validation never applies it to the input. */\nexport type NormalizationChange =\n | {\n readonly operation: \"add\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly after: JsonValue;\n readonly message: string;\n }\n | {\n readonly operation: \"replace\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly before: JsonValue;\n readonly after: JsonValue;\n readonly message: string;\n }\n | {\n readonly operation: \"remove\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly before: JsonValue;\n readonly message: string;\n };\n\nexport interface DocumentValidationResult {\n /** Whether checks finished, including a definite invalid-input conclusion. */\n readonly complete: boolean;\n readonly diagnostics: readonly Diagnostic[];\n readonly normalizedDocument?: { readonly [key: string]: JsonValue };\n readonly changes: readonly NormalizationChange[];\n}\n\n/** A permission outcome established by server code, not by document content. */\nexport interface DocumentAuthority {\n readonly allowed: boolean;\n /** Original document location; use [] for an operation-level denial. */\n readonly path: FieldPath;\n}\n\n/** An authoritative creation value allocated by the caller, never the editor. */\nexport interface ServerOwnedField {\n /** Source path to id, actor, attributedTo, published, or updated. */\n readonly path: FieldPath;\n readonly value: string;\n}\n\n/** Trusted server inputs; these options must not be accepted from a client. */\nexport interface DocumentPreparationOptions {\n /** At least one explicit outcome is required; omission never means allowed. */\n readonly authority: readonly [DocumentAuthority, ...DocumentAuthority[]];\n readonly serverOwnedFields: readonly ServerOwnedField[];\n}\n\nconst activityStreamsContext = \"https://www.w3.org/ns/activitystreams\";\nconst maximumDiagnostics = 100;\nconst maximumPathDepth = 64;\nconst actorTypes = [Application, Group, Organization, Person, Service];\nconst addressingProperties = [\"to\", \"cc\", \"bto\", \"bcc\", \"audience\"];\n// AS2 vocabulary Object properties that do not also apply to Link.\nconst objectOnlyProperties: ReadonlySet<string> = new Set([\n \"attachment\",\n \"attributedTo\",\n \"audience\",\n \"content\",\n \"contentMap\",\n \"context\",\n \"endTime\",\n \"generator\",\n \"icon\",\n \"image\",\n \"inReplyTo\",\n \"location\",\n \"published\",\n \"replies\",\n \"startTime\",\n \"summary\",\n \"summaryMap\",\n \"tag\",\n \"updated\",\n \"url\",\n \"to\",\n \"bto\",\n \"cc\",\n \"bcc\",\n \"duration\",\n]);\n\ntype Report = (\n reason: DiagnosticReason,\n path: FieldPath,\n message: string,\n) => void;\n\ntype VocabularyType = $EntityType | typeof Link | typeof Mention;\n\n// Unsupported custom types by Fedify are not in this checker's coverage.\nconst implementedTypes: ReadonlySet<VocabularyType> = new Set<VocabularyType>([\n Note,\n APObject,\n Article,\n Application,\n Group,\n Organization,\n Person,\n Service,\n Collection,\n OrderedCollection,\n CollectionPage,\n OrderedCollectionPage,\n Link,\n Mention,\n Activity,\n Like,\n Create,\n Undo,\n Accept,\n Follow,\n IntransitiveActivity,\n Arrive,\n Travel,\n Add,\n Announce,\n Block,\n Delete,\n Dislike,\n Flag,\n Ignore,\n Invite,\n Join,\n Leave,\n Listen,\n Move,\n Offer,\n Question,\n Read,\n Reject,\n Remove,\n TentativeAccept,\n TentativeReject,\n Update,\n View,\n]);\n\n// Owns diagnostic collection and completion state for one validation call.\nfunction createReporter() {\n const diagnostics: Diagnostic[] = [];\n let complete = true;\n let truncated = false;\n\n const report: Report = (reason, path, message) => {\n if (truncated) return;\n if (diagnostics.length === maximumDiagnostics) {\n complete = false;\n truncated = true;\n diagnostics[maximumDiagnostics - 1] = {\n reason: \"diagnostic_limit_reached\",\n ...diagnosticReasons.diagnostic_limit_reached,\n path: [],\n message: \"Further diagnostics were omitted.\",\n };\n return;\n }\n const classification = diagnosticReasons[reason];\n if (classification.category === \"support\") complete = false;\n diagnostics.push({ reason, ...classification, path, message });\n };\n\n return {\n report,\n isFull: () => truncated,\n result: (): DocumentValidationResult => ({\n complete,\n diagnostics,\n changes: [],\n }),\n };\n}\n\nfunction readDocument(\n document: unknown,\n path: FieldPath,\n report: Report,\n): Record<string, unknown> | undefined {\n if (!isJsonValueShape(document)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n return undefined;\n }\n if (\n document == null ||\n typeof document !== \"object\" ||\n Array.isArray(document)\n ) {\n report(\"invalid_document_root\", path, \"Expected a document object.\");\n return undefined;\n }\n const prototype: unknown = Object.getPrototypeOf(document);\n if (prototype !== Object.prototype && prototype !== null) {\n report(\"non_json_value\", path, \"Expected a plain JSON data object.\");\n return undefined;\n }\n const keys = Reflect.ownKeys(document);\n if (keys.some((key) => typeof key !== \"string\")) {\n report(\n \"non_json_value\",\n path,\n \"JSON objects cannot have symbol properties.\",\n );\n return undefined;\n }\n const descriptors = Object.getOwnPropertyDescriptors(document);\n const values: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(descriptors).sort()) {\n const descriptor = descriptors[key]!;\n if (!(\"value\" in descriptor) || !descriptor.enumerable) {\n report(\n \"non_json_value\",\n [...path, key],\n \"Expected an enumerable data property.\",\n );\n return undefined;\n }\n const value: unknown = descriptor.value;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", [...path, key], \"Expected a JSON value.\");\n return undefined;\n }\n values[key] = value;\n }\n return values;\n}\n\n// This checks only the immediate JSON shape. Supported nested values are read\n// separately through readDocument() or visitList(), without invoking accessors.\nfunction isJsonValueShape(value: unknown): boolean {\n return (\n value === null ||\n typeof value === \"object\" ||\n typeof value === \"string\" ||\n typeof value === \"boolean\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n );\n}\n\n// Reports reference-rule failures without owning the diagnostic collection.\nfunction checkReference(value: unknown, path: FieldPath, report: Report): void {\n if (value === null) return;\n if (typeof value !== \"string\") {\n if (typeof value === \"object\") {\n report(\n \"unsupported_value_form\",\n path,\n \"Embedded values are not checked yet.\",\n );\n } else {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a resource reference, embedded object, or allowed list.\",\n );\n }\n return;\n }\n const hasControlOrSpace = Array.from(value).some((character) => {\n const point = character.codePointAt(0)!;\n return point <= 0x20 || point === 0x7f;\n });\n if (\n !value.isWellFormed() ||\n hasControlOrSpace ||\n /[<>\"{}|\\\\^`]/u.test(value) ||\n /%(?![\\da-f]{2})/iu.test(value)\n ) {\n report(\n \"invalid_iri\",\n path,\n \"Expected a syntactically valid IRI reference.\",\n );\n } else if (!/^[a-z][a-z\\d+.-]*:/iu.test(value)) {\n report(\n \"unsupported_value_form\",\n path,\n \"Relative references need a base-IRI policy.\",\n );\n } else if (!URL.canParse(value)) {\n report(\n \"unsupported_value_form\",\n path,\n \"This IRI cannot be represented by the current URL parser.\",\n );\n }\n}\n\n// Applies the current list-entry policy, independently of list traversal.\nfunction checkReferenceEntry(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n): void {\n if (value === null) return;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n } else if (Array.isArray(value)) {\n report(\"unsupported_value_form\", path, \"Nested lists are not checked yet.\");\n } else {\n check(value, path, report);\n }\n}\n\n// Visits data entries safely and constructs paths, without reference rules.\nfunction visitList(\n values: readonly unknown[],\n path: FieldPath,\n report: Report,\n visit: (value: unknown, path: FieldPath) => void,\n): void {\n if (Reflect.ownKeys(values).length > values.length + 1) {\n report(\n \"non_json_value\",\n path,\n \"Expected a JSON array without extra properties.\",\n );\n return;\n }\n for (let index = 0; index < values.length; index += 1) {\n const entryPath = [...path, index];\n const descriptor = Object.getOwnPropertyDescriptor(values, index);\n if (\n descriptor == null ||\n !(\"value\" in descriptor) ||\n !descriptor.enumerable\n ) {\n report(\n \"non_json_value\",\n entryPath,\n \"Expected an enumerable array entry.\",\n );\n continue;\n }\n const entry: unknown = descriptor.value;\n visit(entry, entryPath);\n }\n}\n\n// Coordinates reference rules with traversal and reporting.\nfunction checkReferenceValues(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference = checkReference,\n schedule: (work: () => void) => void = (work) => work(),\n): void {\n if (!Array.isArray(value)) {\n schedule(() => check(value, path, report));\n return;\n }\n if (value.length === 0) {\n report(\n \"unsupported_value_form\",\n path,\n \"Empty lists are not supported in this value position.\",\n );\n return;\n }\n visitList(\n value,\n path,\n (reason, entryPath, message) =>\n schedule(() => report(reason, entryPath, message)),\n (entry, entryPath) => {\n schedule(() => checkReferenceEntry(entry, entryPath, report, check));\n },\n );\n}\n\nfunction checkSingleReference(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n schedule: (work: () => void) => void,\n): void {\n checkSingleValue(\n value,\n path,\n (reason, entryPath, message) =>\n schedule(() => report(reason, entryPath, message)),\n (entry, entryPath) => schedule(() => check(entry, entryPath, report)),\n );\n}\n\ninterface ContextTerm {\n readonly iri: string;\n readonly type?: string | undefined;\n readonly container?: string | undefined;\n readonly prefix: boolean;\n}\n\ninterface DocumentContext {\n readonly terms: ReadonlyMap<string, ContextTerm>;\n}\n\nfunction sameContextTerm(\n actual: ContextTerm | undefined,\n expected: ContextTerm,\n): boolean {\n return (\n actual != null &&\n actual.iri === expected.iri &&\n actual.type === expected.type &&\n actual.container === expected.container &&\n actual.prefix === expected.prefix\n );\n}\n\nfunction isSupportedContextUri(value: string): boolean {\n // URL parsing alone accepts characters that JSON-LD IRI mappings forbid.\n return (\n /^[a-z][a-z\\d+.-]*:/iu.test(value) &&\n !Array.from(value).some((character) => {\n const point = character.codePointAt(0)!;\n return (\n point <= 0x20 ||\n (point >= 0x7f && point <= 0x9f) ||\n '<>\"{}|\\\\^`'.includes(character)\n );\n }) &&\n URL.canParse(value)\n );\n}\n\n// Resolve only explicit terms, defined prefixes, keywords, and absolute IRIs.\n// This profile deliberately does not implement general JSON-LD expansion.\nfunction resolveTerm(\n value: string,\n terms: ReadonlyMap<string, ContextTerm>,\n pending?: ReadonlySet<string>,\n): string | undefined {\n if (value === \"@id\" || value === \"@type\") return value;\n if (pending?.has(value)) return undefined;\n const term = terms.get(value);\n if (term != null) return term.iri;\n const colon = value.indexOf(\":\");\n if (colon < 0) return undefined;\n if (pending?.has(value.slice(0, colon))) return undefined;\n const prefix = terms.get(value.slice(0, colon));\n if (prefix?.prefix) {\n const expanded = prefix.iri + value.slice(colon + 1);\n return isSupportedContextUri(expanded) ? expanded : undefined;\n }\n return isSupportedContextUri(value) ? value : undefined;\n}\n\nfunction readContextTerm(\n definition: unknown,\n path: FieldPath,\n terms: ReadonlyMap<string, ContextTerm>,\n report: Report,\n pending: ReadonlySet<string>,\n): ContextTerm | undefined {\n let values: Record<string, unknown>;\n if (typeof definition === \"string\") values = { \"@id\": definition };\n else if (\n definition !== null &&\n typeof definition === \"object\" &&\n !Array.isArray(definition)\n ) {\n const record = readDocument(definition, path, report);\n if (record == null) return undefined;\n values = record;\n } else {\n report(\n definition === null ? \"unsupported_context_form\" : \"invalid_context\",\n path,\n \"Only string and simple term definitions are supported.\",\n );\n return undefined;\n }\n if (\n Object.keys(values).some(\n (key) => ![\"@id\", \"@type\", \"@container\", \"@prefix\"].includes(key),\n )\n ) {\n report(\n \"unsupported_context_form\",\n path,\n \"Scoped contexts, reverse properties, and complex term definitions are not supported.\",\n );\n return undefined;\n }\n const id = values[\"@id\"];\n if (id === undefined) {\n report(\n \"unsupported_context_form\",\n path,\n \"Inline term definitions require an explicit @id in this profile.\",\n );\n return undefined;\n }\n if (typeof id !== \"string\") {\n report(\"invalid_context\", path, \"Expected a string @id mapping.\");\n return undefined;\n }\n if (/^[#/.]/u.test(id) || id.startsWith(\"_:\")) {\n report(\n \"unsupported_context_form\",\n path,\n \"Relative and blank-node term mappings are outside the supported profile.\",\n );\n return undefined;\n }\n if (id.startsWith(\"@\") && ![\"@id\", \"@type\"].includes(id)) {\n report(\n \"unsupported_context_form\",\n path,\n \"This keyword alias is outside the supported profile.\",\n );\n return undefined;\n }\n return resolveContextTerm(\n id,\n values,\n typeof definition === \"string\",\n path,\n terms,\n report,\n pending,\n );\n}\n\nfunction resolveContextTerm(\n id: string,\n values: Record<string, unknown>,\n implicitPrefix: boolean,\n path: FieldPath,\n terms: ReadonlyMap<string, ContextTerm>,\n report: Report,\n pending: ReadonlySet<string>,\n): ContextTerm | undefined {\n const iri = resolveTerm(id, terms, pending);\n if (iri == null) return undefined;\n if (iri.startsWith(\"@\") && Object.keys(values).some((key) => key !== \"@id\")) {\n report(\n \"unsupported_context_form\",\n path,\n \"Keyword aliases with additional coercion or container options are not supported.\",\n );\n return undefined;\n }\n const type = values[\"@type\"];\n if (typeof type === \"string\" && type.startsWith(\"@\") && type !== \"@id\") {\n report(\n \"unsupported_context_form\",\n path,\n \"This type coercion is outside the supported profile.\",\n );\n return undefined;\n }\n const expandedType =\n typeof type === \"string\" ? resolveTerm(type, terms, pending) : undefined;\n if (type !== undefined && expandedType === undefined) return undefined;\n const container = values[\"@container\"];\n if (container === \"@language\" && type !== undefined) {\n report(\n \"unsupported_context_form\",\n path,\n \"Language containers with type coercion are not supported.\",\n );\n return undefined;\n }\n if (\n container !== undefined &&\n container !== \"@language\" &&\n container !== \"@list\"\n ) {\n report(\n \"unsupported_context_form\",\n path,\n \"This container form is not supported.\",\n );\n return undefined;\n }\n if (\n values[\"@prefix\"] !== undefined &&\n typeof values[\"@prefix\"] !== \"boolean\"\n ) {\n report(\"invalid_context\", path, \"Expected a boolean @prefix flag.\");\n return undefined;\n }\n return {\n iri,\n type: expandedType,\n container,\n prefix:\n values[\"@prefix\"] === true || (implicitPrefix && /[#/:]$/u.test(iri)),\n };\n}\n\nfunction applyContextTerms(\n values: Record<string, unknown>,\n path: FieldPath,\n terms: Map<string, ContextTerm>,\n report: Report,\n protectedTerms?: ReadonlyMap<string, ContextTerm>,\n): boolean {\n let valid = true;\n const localReport: Report = (...args) => {\n valid = false;\n report(...args);\n };\n const pending = new Set(Object.keys(values));\n for (const name of pending) terms.delete(name);\n while (pending.size > 0) {\n if (!valid) return false;\n let resolved = false;\n for (const name of pending) {\n const fieldPath = [...path, name];\n if (name.length === 0) {\n localReport(\n \"invalid_context\",\n fieldPath,\n \"A context term cannot be empty.\",\n );\n continue;\n }\n if (name.includes(\":\")) {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"IRI-shaped term definitions are outside the supported inline profile.\",\n );\n continue;\n }\n if (name.startsWith(\"@\")) {\n if (\n protectedTerms == null &&\n name === \"@vocab\" &&\n values[name] === \"_:\"\n ) {\n pending.delete(name);\n } else {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"This context directive is outside the supported profile.\",\n );\n }\n continue;\n }\n const term = readContextTerm(\n values[name],\n fieldPath,\n terms,\n localReport,\n pending,\n );\n if (term == null) continue;\n const original = protectedTerms?.get(name);\n if (original != null && !sameContextTerm(term, original)) {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"The standard ActivityStreams context cannot be overridden.\",\n );\n continue;\n }\n terms.set(name, term);\n pending.delete(name);\n resolved = true;\n }\n if (!resolved && pending.size > 0 && valid) {\n for (const name of pending) {\n localReport(\n \"invalid_context\",\n [...path, name],\n \"The term has an unresolved or cyclic IRI mapping.\",\n );\n }\n }\n }\n return valid;\n}\n\ninterface ContextTables {\n readonly bundledContexts: ReadonlyMap<\n string,\n ReadonlyMap<string, ContextTerm>\n >;\n readonly standardTerms: ReadonlyMap<string, ContextTerm>;\n readonly standardContext: DocumentContext;\n}\n\nlet contextTables: ContextTables | undefined;\n\n// Interpret dependency contexts lazily so a profile mismatch cannot break import.\nfunction getContextTables(): ContextTables {\n if (contextTables != null) return contextTables;\n // Bundled availability is not blanket admission to this bounded profile.\n const bundledContexts = new Map<string, ReadonlyMap<string, ContextTerm>>();\n for (const url of [activityStreamsContext, \"https://w3id.org/security/v1\"]) {\n const document = preloadedContexts[url] as {\n \"@context\": Record<string, unknown>;\n };\n const terms = new Map<string, ContextTerm>();\n applyContextTerms(\n document[\"@context\"],\n [],\n terms,\n (_reason, _path, message) => {\n throw new Error(message);\n },\n );\n bundledContexts.set(url, terms);\n }\n const standardTerms = bundledContexts.get(activityStreamsContext)!;\n // Publish the cache only after all definitions have been interpreted.\n contextTables = {\n bundledContexts,\n standardTerms,\n standardContext: { terms: standardTerms },\n };\n return contextTables;\n}\n\nfunction applyContextEntry(\n value: unknown,\n path: FieldPath,\n terms: Map<string, ContextTerm>,\n report: Report,\n): boolean {\n const { bundledContexts, standardTerms } = getContextTables();\n if (typeof value === \"string\") {\n const url =\n value === \"http://www.w3.org/ns/activitystreams\"\n ? activityStreamsContext\n : value;\n const bundled = bundledContexts.get(url);\n if (bundled == null) {\n report(\n \"context_unavailable_offline\",\n path,\n \"This context is outside the offline allowlist.\",\n );\n return false;\n }\n for (const [name, term] of bundled) terms.set(name, term);\n return true;\n }\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n report(\n value === null || Array.isArray(value)\n ? \"unsupported_context_form\"\n : \"invalid_context\",\n path,\n \"Expected an allowlisted context or a simple inline context.\",\n );\n return false;\n }\n const definitions = readDocument(value, path, report);\n return (\n definitions != null &&\n applyContextTerms(definitions, path, terms, report, standardTerms)\n );\n}\n\n// Each child gets its parent's understood context; overrides never affect siblings.\nfunction checkContext(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n inherited?: DocumentContext,\n): DocumentContext | undefined {\n const { standardContext, standardTerms } = getContextTables();\n if (!Object.hasOwn(values, \"@context\")) {\n if (inherited != null) return inherited;\n report(\n \"implicit_activitystreams_context\",\n [...path, \"@context\"],\n \"Assuming the ActivityStreams context for this document.\",\n );\n return standardContext;\n }\n const terms = new Map(inherited?.terms);\n let valid = true;\n const localReport: Report = (...args) => {\n valid = false;\n report(...args);\n };\n const context = values[\"@context\"];\n const contextPath = [...path, \"@context\"];\n if (Array.isArray(context)) {\n visitList(context, contextPath, localReport, (entry, entryPath) => {\n if (!applyContextEntry(entry, entryPath, terms, localReport)) {\n valid = false;\n }\n });\n } else if (!applyContextEntry(context, contextPath, terms, localReport)) {\n valid = false;\n }\n if (!valid) return undefined;\n // Require the standard vocabulary, rather than inferring AS from arbitrary terms.\n if (\n ![...standardTerms].every(([name, term]) =>\n sameContextTerm(terms.get(name), term),\n )\n ) {\n report(\n \"unsupported_context_form\",\n contextPath,\n \"The context must include the standard ActivityStreams vocabulary.\",\n );\n return undefined;\n }\n return { terms };\n}\n\ninterface SourceProperty {\n readonly source: string;\n readonly name?: string;\n readonly iri?: string;\n readonly compatible: boolean;\n}\n\n// Retain one entry per source field. Aliases are never merged or re-serialized.\nfunction resolveProperty(\n source: string,\n context: DocumentContext,\n): SourceProperty {\n const { standardTerms } = getContextTables();\n const term = context.terms.get(source);\n const iri = term?.iri ?? resolveTerm(source, context.terms);\n for (const [name, standard] of standardTerms) {\n if (iri !== standard.iri || term?.container !== standard.container) {\n continue;\n }\n return {\n source,\n name,\n iri: standard.iri,\n compatible: term?.type === standard.type,\n };\n }\n if (iri === \"@id\") {\n return { source, name: \"id\", iri: \"@id\", compatible: true };\n }\n if (iri === \"@type\") {\n return { source, name: \"type\", iri: \"@type\", compatible: true };\n }\n return { source, ...(iri == null ? {} : { iri }), compatible: false };\n}\n\nfunction isOpaqueExtension(field: SourceProperty): boolean {\n const { standardTerms } = getContextTables();\n return (\n !field.source.startsWith(\"@\") &&\n !field.iri?.startsWith(\"@\") &&\n !Array.from(standardTerms.values()).some((term) => term.iri === field.iri)\n );\n}\n\nfunction isTypeCombination(value: unknown): boolean {\n if (!Array.isArray(value) || value.length <= 1) return false;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (\n descriptor == null ||\n !(\"value\" in descriptor) ||\n typeof descriptor.value !== \"string\"\n ) {\n return false;\n }\n }\n return true;\n}\n\nfunction checkType(\n value: unknown,\n path: FieldPath,\n report: Report,\n context: DocumentContext,\n): VocabularyType | undefined {\n const typeIri =\n typeof value === \"string\" ? resolveTerm(value, context.terms) : undefined;\n let Type: VocabularyType | undefined;\n if (typeIri != null) {\n Type = getEntityTypeById(typeIri);\n // Link classes are exported separately from Fedify's entity registry.\n if (typeIri === Link.typeId.href) Type = Link;\n else if (typeIri === Mention.typeId.href) Type = Mention;\n }\n if (Type == null || !implementedTypes.has(Type)) {\n const reason = Array.isArray(value)\n ? \"unsupported_value_form\"\n : value == null || typeof value === \"string\"\n ? \"unsupported_type\"\n : \"invalid_value_shape\";\n report(\n reason,\n path,\n isTypeCombination(value)\n ? \"Type combinations are not supported. Provide a single supported type.\"\n : Array.isArray(value)\n ? \"Type arrays are not supported. Provide a single type string.\"\n : \"This type is not supported by the checker yet.\",\n );\n return undefined;\n }\n\n return Type;\n}\n\nfunction isTypeOrSubtype(Type: VocabularyType, Base: VocabularyType): boolean {\n return Type === Base || Type.prototype instanceof Base;\n}\n\nfunction checkEmbeddedFedifyRange(\n Type: VocabularyType,\n expected: readonly VocabularyType[] | undefined,\n path: FieldPath,\n report: Report,\n): void {\n if (expected?.every((Expected) => !isTypeOrSubtype(Type, Expected))) {\n report(\n \"unsupported_value_form\",\n path,\n `Fedify cannot preserve this embedded type for this property. Use ${expected.map((Expected) => Expected.name).join(\", \")} or an IRI reference.`,\n );\n }\n}\n\nfunction getEmbeddedFedifyRange(\n property: string,\n collectionRange: readonly VocabularyType[] | undefined,\n): readonly VocabularyType[] | undefined {\n if (property === \"actor\" || property === \"attributedTo\") return actorTypes;\n return collectionRange?.filter((Expected) => Expected !== Link);\n}\n\nfunction checkDocumentType(\n values: Record<string, unknown>,\n fields: readonly SourceProperty[],\n path: FieldPath,\n context: DocumentContext,\n report: Report,\n): VocabularyType | undefined {\n const types = fields.filter(({ name }) => name === \"type\");\n if (types.length > 1) {\n for (const field of types) {\n report(\n \"unsupported_value_form\",\n [...path, field.source],\n \"Multiple type declarations are not supported. Provide a single type field.\",\n );\n }\n return undefined;\n }\n const source = types[0]?.source ?? \"type\";\n return checkType(values[source], [...path, source], report, context);\n}\n\n// Collection navigation and actor collection links each identify one resource.\nfunction getCollectionRange(\n Type: VocabularyType,\n property: string,\n): readonly VocabularyType[] | undefined {\n if (isTypeOrSubtype(Type, Collection)) {\n if ([\"current\", \"first\", \"last\"].includes(property)) {\n return [CollectionPage, Link];\n }\n }\n if (isTypeOrSubtype(Type, CollectionPage)) {\n if (property === \"partOf\") return [Collection, Link];\n if ([\"next\", \"prev\"].includes(property)) return [CollectionPage, Link];\n }\n const actor = actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor));\n if (actor) {\n if ([\"inbox\", \"outbox\"].includes(property)) {\n return [OrderedCollection, OrderedCollectionPage];\n }\n if ([\"following\", \"followers\", \"liked\"].includes(property)) {\n return [Collection];\n }\n }\n return undefined;\n}\n\nfunction isFunctionalProperty(Type: VocabularyType, property: string): boolean {\n if ([\"id\", \"mediaType\"].includes(property)) return true;\n if (getCollectionRange(Type, property) != null) return true;\n if (isTypeOrSubtype(Type, Link)) {\n return [\"href\", \"height\", \"width\", \"hreflang\"].includes(property);\n }\n if ([\"published\", \"updated\", \"startTime\", \"endTime\"].includes(property)) {\n return true;\n }\n if (isTypeOrSubtype(Type, Collection) && property === \"totalItems\") {\n return true;\n }\n return (\n isTypeOrSubtype(Type, OrderedCollectionPage) && property === \"startIndex\"\n );\n}\n\n// Count original data slots without reading accessors; the value checks report\n// sparse/accessor entries separately. Null entries do not contribute a value.\nfunction countValues(value: unknown): number {\n if (!Array.isArray(value)) return value === null ? 0 : 1;\n let count = 0;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (\n descriptor != null &&\n \"value\" in descriptor &&\n descriptor.value !== null\n ) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction findMultipleAliases(\n Type: VocabularyType,\n fields: readonly SourceProperty[],\n values: Record<string, unknown>,\n): ReadonlySet<string> {\n const groups = new Map<string, string[]>();\n for (const field of fields) {\n if (\n field.name == null ||\n field.iri == null ||\n !isFunctionalProperty(Type, field.name)\n ) {\n continue;\n }\n if (countValues(values[field.source]) === 0) continue;\n const group = groups.get(field.iri) ?? [];\n group.push(field.source);\n groups.set(field.iri, group);\n }\n const multiple = new Set<string>();\n for (const group of groups.values()) {\n if (group.length < 2) continue;\n for (const source of group) {\n // The existing functional-array check reports its own multiplicity.\n if (countValues(values[source]) <= 1) multiple.add(source);\n }\n }\n return multiple;\n}\n\nfunction checkNonNegativeInteger(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (value === null) return;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n report(\"invalid_value_shape\", path, \"Expected a non-negative integer.\");\n }\n}\n\n// Functional properties count non-null values but retain source array indexes.\nfunction checkSingleValue(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n): void {\n if (!Array.isArray(value)) {\n check(value, path, report);\n return;\n }\n if (value.length === 0) {\n report(\n \"unsupported_value_form\",\n path,\n \"Empty lists are not supported in this value position.\",\n );\n return;\n }\n const entries: { value: unknown; path: FieldPath }[] = [];\n visitList(value, path, report, (entry, entryPath) => {\n if (entry !== null) entries.push({ value: entry, path: entryPath });\n });\n if (entries.length > 1) {\n report(\n \"invalid_multiplicity\",\n path,\n \"Expected at most one non-null value.\",\n );\n }\n for (const entry of entries) {\n checkReferenceEntry(entry.value, entry.path, report, check);\n }\n}\n\nfunction checkLanguageTag(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (\n typeof value !== \"string\" ||\n !/^[a-z]{1,8}(?:-[a-z\\d]{1,8})*$/iu.test(value)\n ) {\n report(\"invalid_value_shape\", path, \"Expected a language tag.\");\n return;\n }\n try {\n void new Intl.Locale(value);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"unsupported_value_form\",\n path,\n \"This language tag is outside the current locale parser's support.\",\n );\n }\n}\n\nfunction checkText(\n value: unknown,\n path: FieldPath,\n report: Report,\n plain: boolean,\n): void {\n if (value === null) return;\n if (typeof value === \"string\") {\n if (plain && /<(?:[a-z][^>]*>|\\/[a-z][^>]*>|!--)/iu.test(value)) {\n report(\n \"invalid_value_shape\",\n path,\n \"Names must be plain text without HTML markup.\",\n );\n }\n return;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n report(\"invalid_value_shape\", path, \"Expected text.\");\n return;\n }\n const values = readDocument(value, path, report);\n if (values == null) return;\n if (!Object.hasOwn(values, \"@value\")) {\n report(\n \"unsupported_value_form\",\n path,\n \"Use a language-map property or an explicit @value object for localized text.\",\n );\n return;\n }\n for (const key of Object.keys(values).sort()) {\n const fieldPath = [...path, key];\n if (key === \"@value\") {\n if (typeof values[key] === \"string\") {\n checkText(values[key], fieldPath, report, plain);\n } else {\n report(\"invalid_value_shape\", fieldPath, \"Expected a text value.\");\n }\n } else if (key === \"@language\") {\n checkLanguageTag(values[key], fieldPath, report);\n } else {\n report(\n \"unsupported_value_form\",\n fieldPath,\n \"This text-value attribute is not supported yet.\",\n );\n }\n }\n}\n\nfunction checkLanguageMap(\n value: unknown,\n path: FieldPath,\n report: Report,\n plain: boolean,\n): void {\n if (value === null) return;\n if (typeof value !== \"object\" || Array.isArray(value)) {\n report(\"invalid_value_shape\", path, \"Expected a language map.\");\n return;\n }\n const values = readDocument(value, path, report);\n if (values == null) return;\n for (const language of Object.keys(values).sort()) {\n const fieldPath = [...path, language];\n checkLanguageTag(language, fieldPath, report);\n if (values[language] === null) continue;\n if (typeof values[language] === \"string\") {\n checkText(values[language], fieldPath, report, plain);\n } else {\n report(\n \"invalid_value_shape\",\n fieldPath,\n \"Expected a language-map string.\",\n );\n }\n }\n}\n\nfunction checkDateTime(value: unknown, path: FieldPath, report: Report): void {\n if (value === null) return;\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected a date-time string.\");\n return;\n }\n // AS2 permits omitted seconds, but requires an offset and uppercase T/Z.\n const match =\n /^(?<minute>\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2})(?<second>:\\d{2})?(?<fraction>\\.\\d+)?(?<offset>Z|[+-]\\d{2}:\\d{2})$/u.exec(\n value,\n );\n if (match == null) {\n report(\n \"invalid_datetime\",\n path,\n \"Expected an ActivityStreams date-time with a timezone.\",\n );\n return;\n }\n const { minute, second, fraction, offset } = match.groups!;\n // Check calendar components separately from representation support.\n try {\n void Temporal.Instant.from(`${minute}${second ?? \":00\"}${offset}`);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"invalid_datetime\",\n path,\n \"Expected a valid calendar date, time, and offset.\",\n );\n return;\n }\n if (second === \":60\") {\n report(\n \"unsupported_value_form\",\n path,\n \"Leap-second timestamps are not checked by the current date-time parser.\",\n );\n return;\n }\n // Native Temporal can be more permissive than Fedify's parser. Require\n // explicit seconds and nanosecond precision before parsing the original.\n if (second == null) {\n report(\n \"unsupported_value_form\",\n path,\n fraction != null\n ? \"ActivityStreams permits fractions without seconds, but Fedify requires explicit seconds before a fractional component.\"\n : \"ActivityStreams permits omitted seconds, but Fedify requires explicit seconds, such as 12:34:00Z.\",\n );\n return;\n }\n if (fraction != null && fraction.length > 10) {\n report(\n \"unsupported_value_form\",\n path,\n \"Fractional seconds exceeding nine digits cannot be preserved through Fedify parsing; provide at most nine fractional digits.\",\n );\n return;\n }\n try {\n void Temporal.Instant.from(value);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"unsupported_value_form\",\n path,\n \"This date-time matches the ActivityStreams format, but cannot be parsed as an instant without rewriting; provide a timestamp such as 2024-01-01T12:34:00Z.\",\n );\n }\n}\n\n// Share coverage classification with empty-array omission admission.\nfunction getCommonPropertyKind(\n Type: VocabularyType,\n property: string,\n): \"text\" | \"languageMap\" | \"datetime\" | \"id\" | \"mediaType\" | undefined {\n const object = isTypeOrSubtype(Type, APObject);\n const actor = actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor));\n const textProperties = object ? [\"name\", \"summary\", \"content\"] : [\"name\"];\n if (actor) textProperties.push(\"preferredUsername\");\n if (textProperties.includes(property)) return \"text\";\n if (\n textProperties.some(\n (name) => property === `${name}Map` && name !== \"preferredUsername\",\n )\n ) {\n return \"languageMap\";\n }\n if (\n object &&\n [\"published\", \"updated\", \"startTime\", \"endTime\"].includes(property)\n ) {\n return \"datetime\";\n }\n if (property === \"id\" || property === \"mediaType\") return property;\n return undefined;\n}\n\n// Scalar/common properties share checks; embedded references use the work stack.\nfunction checkCommonProperty(\n kind: ReturnType<typeof getCommonPropertyKind>,\n property: string,\n value: unknown,\n path: FieldPath,\n report: Report,\n): boolean {\n if (kind === \"text\") {\n checkReferenceValues(value, path, report, (entry, entryPath) =>\n checkText(entry, entryPath, report, property === \"name\"),\n );\n } else if (kind === \"languageMap\") {\n checkLanguageMap(value, path, report, property === \"nameMap\");\n } else if (kind === \"datetime\") {\n checkSingleValue(value, path, report, checkDateTime);\n } else if (kind === \"id\") {\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected an IRI identifier string.\");\n } else {\n checkReference(value, path, report);\n }\n } else if (kind === \"mediaType\") {\n checkSingleValue(value, path, report, (entry, entryPath) =>\n checkLinkProperty(property, entry, entryPath, report),\n );\n } else {\n // Null is absent even when this vocabulary property has no value rules yet.\n return value === null;\n }\n return true;\n}\n\nfunction proposePropertyOmission(\n value: unknown,\n path: FieldPath,\n report: Report,\n changes: NormalizationChange[],\n identifier: boolean,\n): boolean {\n const emptyArray = Array.isArray(value) && value.length === 0;\n if (!emptyArray && !identifier) return false;\n if (value !== null && !Array.isArray(value)) return false;\n let safe = true;\n let absent = true;\n if (Array.isArray(value)) {\n visitList(\n value,\n path,\n (...args) => {\n safe = false;\n report(...args);\n },\n (entry) => {\n if (entry !== null) absent = false;\n },\n );\n }\n if (!safe) return true;\n if (!absent) return false;\n report(\n emptyArray ? \"empty_property_list\" : \"absent_identifier\",\n path,\n emptyArray\n ? \"ActivityStreams represents empty property arrays by omission or null; the preview omits this property.\"\n : \"This identifier is absent; the preview omits it so Fedify receives no non-string identifier.\",\n );\n changes.push({\n operation: \"remove\",\n reason: emptyArray ? \"omit_empty_property_list\" : \"omit_absent_identifier\",\n path,\n before: value as JsonValue,\n message: emptyArray\n ? \"Omit an empty property array from the wire representation.\"\n : \"Omit an absent identifier from the wire representation.\",\n });\n return true;\n}\n\nfunction checkLinkRelation(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (value === null) return;\n if (\n typeof value !== \"string\" ||\n value.length === 0 ||\n Array.from(value).some(\n (character) =>\n character.charCodeAt(0) <= 0x20 ||\n character.charCodeAt(0) === 0x7f ||\n character === \",\",\n )\n ) {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a relation token or absolute IRI without whitespace or commas.\",\n );\n } else if (/^[a-z][a-z\\d+.-]*:/iu.test(value)) {\n checkReference(value, path, report);\n } else if (!/^[a-z][a-z\\d.-]*$/iu.test(value)) {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a relation token or absolute IRI.\",\n );\n }\n}\n\n// Link metadata uses lexical checks without rewriting the original values.\nfunction checkLinkProperty(\n property: string,\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (property === \"rel\") {\n checkReferenceValues(value, path, report, checkLinkRelation);\n return;\n }\n if (value === null) return;\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected a string.\");\n return;\n }\n if (property === \"href\") {\n checkReference(value, path, report);\n } else if (property === \"mediaType\") {\n try {\n void new MIMEType(value);\n } catch (error) {\n if (!(error instanceof TypeError)) throw error;\n report(\"invalid_value_shape\", path, \"Expected a MIME media type.\");\n }\n } else {\n checkLanguageTag(value, path, report);\n }\n}\n\n// Check explicit keyword shapes, without expanding contexts or keyword aliases.\n// Return whether @value contains literal JSON rather than nested JSON-LD.\nfunction checkExtensionKeywords(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n): boolean {\n if (Object.hasOwn(values, \"@id\") && typeof values[\"@id\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@id\"],\n \"Expected a string JSON-LD identifier.\",\n );\n }\n let jsonLiteral = values[\"@type\"] === \"@json\";\n if (Object.hasOwn(values, \"@type\")) {\n const type = values[\"@type\"];\n if (Array.isArray(type)) {\n visitList(type, [...path, \"@type\"], report, (entry, entryPath) => {\n if (typeof entry !== \"string\") {\n report(\n \"invalid_value_shape\",\n entryPath,\n \"Expected a JSON-LD type string.\",\n );\n }\n if (type.length === 1 && entry === \"@json\") jsonLiteral = true;\n });\n } else if (typeof type !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@type\"],\n \"Expected a JSON-LD type string or array of strings.\",\n );\n }\n }\n if (Object.hasOwn(values, \"@value\") && values[\"@language\"] != null) {\n if (typeof values[\"@language\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@language\"],\n \"Expected a string language tag or null.\",\n );\n }\n if (values[\"@value\"] !== null && typeof values[\"@value\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@value\"],\n \"A JSON-LD language-tagged value must have a string @value or null absence.\",\n );\n }\n }\n return jsonLiteral;\n}\n\nfunction getInapplicableProperties(Type: VocabularyType): ReadonlySet<string> {\n return isTypeOrSubtype(Type, Link) ? objectOnlyProperties : new Set<string>();\n}\n\nfunction checkPathDepth(path: FieldPath, report: Report): boolean {\n if (path.length <= maximumPathDepth) return true;\n report(\n \"processing_limit_exceeded\",\n path,\n `Nesting exceeds the supported limit of ${maximumPathDepth} path segments.`,\n );\n return false;\n}\n\nfunction checkDocumentValue(\n rootDocument: unknown,\n rootPath: FieldPath,\n reporter: ReturnType<typeof createReporter>,\n changes: NormalizationChange[],\n onDocument?: (\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext,\n ) => void,\n onUnavailableDocument: (path: FieldPath) => void = () => undefined,\n): void {\n const { report, isFull } = reporter;\n const pending: (() => void)[] = [];\n const ancestors = new WeakSet<object>();\n\n // Check JSON safety and selected explicit keyword shapes. This is not full\n // JSON-LD validation; extension semantics and nested contexts remain unchecked.\n function checkExtension(\n value: unknown,\n path: FieldPath,\n keywords = true,\n ): void {\n if (!checkPathDepth(path, report)) return;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n return;\n }\n if (value === null || typeof value !== \"object\") return;\n if (ancestors.has(value)) {\n report(\"non_json_value\", path, \"JSON documents cannot contain cycles.\");\n return;\n }\n ancestors.add(value);\n pending.push(() => ancestors.delete(value));\n const children: (() => void)[] = [];\n if (Array.isArray(value)) {\n visitList(value, path, report, (entry, entryPath) => {\n children.push(() => checkExtension(entry, entryPath, keywords));\n });\n } else {\n const values = readDocument(value, path, report);\n if (values != null) {\n const jsonLiteral =\n keywords && checkExtensionKeywords(values, path, report);\n for (const key of Object.keys(values)) {\n const childKeywords = keywords && !(jsonLiteral && key === \"@value\");\n children.push(() =>\n checkExtension(values[key], [...path, key], childKeywords),\n );\n }\n }\n }\n for (const child of children.reverse()) pending.push(child);\n }\n\n function checkDocument(\n document: unknown,\n path: FieldPath,\n inherited?: DocumentContext,\n expectedTypes?: readonly VocabularyType[],\n fedifyTypes?: readonly VocabularyType[],\n ): void {\n if (!checkPathDepth(path, report)) {\n onUnavailableDocument(path);\n return;\n }\n if (\n document !== null &&\n typeof document === \"object\" &&\n ancestors.has(document)\n ) {\n report(\"non_json_value\", path, \"JSON documents cannot contain cycles.\");\n onUnavailableDocument(path);\n return;\n }\n const values = readDocument(document, path, report);\n if (values == null) {\n onUnavailableDocument(path);\n return;\n }\n const sourceDocument = document as object;\n const context = checkContext(values, path, report, inherited);\n if (context == null) {\n onUnavailableDocument(path);\n return;\n }\n const fields = Object.keys(values)\n .filter((source) => source !== \"@context\")\n .sort()\n .map((source) => resolveProperty(source, context));\n const Type = checkDocumentType(values, fields, path, context, report);\n if (Type == null) {\n onUnavailableDocument(path);\n return;\n }\n if (expectedTypes?.every((Expected) => !isTypeOrSubtype(Type, Expected))) {\n report(\n \"invalid_value_shape\",\n path,\n \"The embedded type is outside this property's collection range.\",\n );\n onUnavailableDocument(path);\n return;\n }\n checkEmbeddedFedifyRange(Type, fedifyTypes, path, report);\n onDocument?.(values, path, context);\n const isObject = isTypeOrSubtype(Type, APObject);\n const isLink = isTypeOrSubtype(Type, Link);\n const isActivity = isTypeOrSubtype(Type, Activity);\n const isIntransitive = isTypeOrSubtype(Type, IntransitiveActivity);\n const isCollection = isTypeOrSubtype(Type, Collection);\n const isOrderedPage = isTypeOrSubtype(Type, OrderedCollectionPage);\n const linkProperties = isLink\n ? [\"href\", \"mediaType\", \"hreflang\", \"rel\"]\n : [];\n const integerProperties = isLink\n ? [\"height\", \"width\"]\n : isOrderedPage\n ? [\"totalItems\", \"startIndex\"]\n : isCollection\n ? [\"totalItems\"]\n : [];\n const referenceProperties = [\"preview\"];\n if (isObject) {\n referenceProperties.push(\n \"attributedTo\",\n \"location\",\n ...addressingProperties,\n );\n }\n if (isActivity) {\n referenceProperties.push(\n \"actor\",\n \"object\",\n \"target\",\n \"origin\",\n \"result\",\n \"instrument\",\n );\n }\n if (isCollection) referenceProperties.push(\"items\", \"orderedItems\");\n const omittableProperties = new Set([\n ...integerProperties,\n ...linkProperties,\n ...referenceProperties,\n ]);\n const multipleAliases = findMultipleAliases(Type, fields, values);\n const inapplicableProperties = getInapplicableProperties(Type);\n\n ancestors.add(sourceDocument);\n pending.push(() => {\n ancestors.delete(sourceDocument);\n });\n // LIFO work preserves the same depth-first, sorted-property order.\n for (const field of fields\n .filter(({ name }) => name !== \"type\")\n .reverse()) {\n const { source, name: key } = field;\n const intransitiveObject = isIntransitive && key === \"object\";\n pending.push(() => {\n const value = values[source];\n const fieldPath = [...path, source];\n if (key == null) {\n if (isOpaqueExtension(field)) {\n report(\n \"extension_property_unchecked\",\n fieldPath,\n \"This custom property's data is preserved; its semantics were not checked.\",\n );\n checkExtension(value, fieldPath);\n return;\n }\n report(\n \"unsupported_property\",\n fieldPath,\n \"This property is outside the checker's Fedify vocabulary coverage.\",\n );\n return;\n }\n if (!field.compatible) {\n report(\n \"unsupported_value_form\",\n fieldPath,\n \"This spelling's type coercion differs from the supported vocabulary term.\",\n );\n return;\n }\n if (inapplicableProperties.has(key)) {\n if (value === null) return;\n report(\n \"property_not_applicable\",\n fieldPath,\n \"This property applies to Object documents, not Link documents.\",\n );\n return;\n }\n if (multipleAliases.has(source)) {\n report(\n \"invalid_multiplicity\",\n fieldPath,\n \"Multiple aliases supply values for one functional property.\",\n );\n }\n const collectionRange = getCollectionRange(Type, key);\n const commonKind = getCommonPropertyKind(Type, key);\n const supported =\n omittableProperties.has(key) ||\n collectionRange != null ||\n commonKind != null;\n // Preview omission of empty supported arrays and absent identifiers.\n if (\n supported &&\n proposePropertyOmission(\n value,\n fieldPath,\n report,\n changes,\n commonKind === \"id\",\n )\n ) {\n return;\n }\n if (integerProperties.includes(key)) {\n checkSingleValue(value, fieldPath, report, checkNonNegativeInteger);\n } else if (linkProperties.includes(key)) {\n if (key === \"rel\") {\n checkLinkProperty(key, value, fieldPath, report);\n } else {\n checkSingleValue(value, fieldPath, report, (entry, entryPath) =>\n checkLinkProperty(key, entry, entryPath, report),\n );\n }\n } else if (\n checkCommonProperty(commonKind, key, value, fieldPath, report)\n ) {\n // Common properties and null absence were checked above.\n } else if (intransitiveObject) {\n checkReferenceValues(value, fieldPath, report, (entry, entryPath) => {\n if (entry !== null) {\n report(\n \"property_not_applicable\",\n entryPath,\n \"The object property does not apply to intransitive activities.\",\n );\n }\n });\n } else if (\n referenceProperties.includes(key) ||\n collectionRange != null\n ) {\n const checks: (() => void)[] = [];\n const checkValues =\n collectionRange == null\n ? checkReferenceValues\n : checkSingleReference;\n checkValues(\n value,\n fieldPath,\n report,\n (entry, entryPath) => {\n if (\n entry !== null &&\n typeof entry === \"object\" &&\n !Array.isArray(entry)\n ) {\n // AS ranges can be wider than Fedify's typed decoders. Keep\n // vocabulary errors distinct from unsupported embedded forms.\n checkDocument(\n entry,\n entryPath,\n context,\n collectionRange,\n getEmbeddedFedifyRange(key, collectionRange),\n );\n } else {\n checkReference(entry, entryPath, report);\n }\n },\n (check) => checks.push(check),\n );\n for (const check of checks.reverse()) pending.push(check);\n } else {\n report(\n \"unsupported_property\",\n fieldPath,\n \"This property is not checked by the initial implementation.\",\n );\n }\n });\n }\n }\n\n checkDocument(rootDocument, rootPath);\n while (pending.length > 0 && !isFull()) {\n pending.pop()!();\n }\n}\n\n// Clone checked JSON iteratively so a deeply nested preview cannot overflow\n// the JavaScript call stack or share mutable containers with the input.\nfunction createPreview(\n document: { [key: string]: JsonValue },\n changes: readonly NormalizationChange[],\n): { [key: string]: JsonValue } {\n const root: { [key: string]: JsonValue } = {};\n const pending = [\n {\n source: document as object,\n target: root as { [key: string]: JsonValue },\n },\n ];\n while (pending.length > 0) {\n const { source, target } = pending.pop()!;\n for (const [key, value] of Object.entries(source)) {\n let copy = value as JsonValue;\n if (value !== null && typeof value === \"object\") {\n // Each JSON occurrence has its own path and proposed field values.\n copy = Array.isArray(value) ? [] : {};\n pending.push({\n source: value,\n target: copy as { [key: string]: JsonValue },\n });\n }\n Object.defineProperty(target, key, {\n value: copy,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n for (const change of changes) {\n let parent = root;\n for (const key of change.path.slice(0, -1)) {\n parent = parent[key] as { [key: string]: JsonValue };\n }\n const key = change.path.at(-1)!;\n if (change.operation === \"remove\") delete parent[key];\n else {\n Object.defineProperty(parent, key, {\n value: change.after,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n return root;\n}\n\n/**\n * Checks the implemented Activity Vocabulary types, including nested\n * activity objects, without network access or writes. Embedded objects inherit\n * the parent's context. Collections add member, count, and navigation checks.\n * Question uses shared intransitive rules; poll-specific\n * fields remain unsupported pending #155.\n *\n * Supports allowlisted bundled contexts and simple inline aliases/prefixes,\n * single types, id, string content,\n * attribution/location and activity actor, object, target, origin, result,\n * and instrument values. These can be IRI references or supported\n * embedded types, singly or in flat lists. Empty supported property arrays\n * receive omission previews. Intransitive activities\n * reject a non-null object property. Other forms produce\n * support diagnostics and `complete: false`. This is not a permission check,\n * a Fedify parsability check, or full ActivityStreams validation.\n * The input must be plain JSON data, not a Proxy.\n * Context interpretation is bounded and synchronous. Unknown\n * custom properties are preserved as opaque JSON with warnings. Complex\n * contexts remain unsupported; input is never expanded.\n * Null list entries mean absence. Functional properties accept at most one\n * non-null value, preserving array-index paths. Common text/language maps,\n * timestamps, actor preferredUsername, and addressing are checked.\n * @returns Findings at original-input paths, with an explicit omission preview\n * for empty supported property arrays and absent identifiers only when validation\n * completes without errors.\n */\nexport function validateDocument(document: unknown): DocumentValidationResult {\n const reporter = createReporter();\n const changes: NormalizationChange[] = [];\n checkDocumentValue(document, [], reporter, changes);\n const result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\") ||\n changes.length === 0\n ) {\n return result;\n }\n const preview = createPreview(\n document as { [key: string]: JsonValue },\n changes,\n );\n const checked = validateDocument(preview);\n reportPreviewDiagnostics(result, checked, reporter.report);\n const previewResult = reporter.result();\n if (\n !checked.complete ||\n !previewResult.complete ||\n previewResult.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return {\n ...previewResult,\n complete: checked.complete && previewResult.complete,\n };\n }\n return { ...previewResult, changes, normalizedDocument: preview };\n}\n\n// Preview checks retain source diagnostics without repeating unchanged findings.\nfunction reportPreviewDiagnostics(\n original: DocumentValidationResult,\n checked: DocumentValidationResult,\n report: Report,\n): void {\n for (const diagnostic of checked.diagnostics) {\n if (\n !original.diagnostics.some(\n (existing) =>\n existing.reason === diagnostic.reason &&\n JSON.stringify(existing.path) === JSON.stringify(diagnostic.path),\n )\n ) {\n report(diagnostic.reason, diagnostic.path, diagnostic.message);\n }\n }\n}\n\ninterface PreparationTarget {\n readonly values: Record<string, unknown>;\n readonly context: DocumentContext;\n}\n\n// #152 supplies these options after its own permission checks and allocation.\n// TypeErrors identify caller mistakes; document problems use diagnostics.\n// Validating option shapes does not authenticate their source.\nfunction checkPreparationOptions(options: DocumentPreparationOptions): void {\n const validPath = (path: FieldPath) =>\n Array.isArray(path) &&\n path.every(\n (part) =>\n typeof part === \"string\" ||\n (typeof part === \"number\" && Number.isSafeInteger(part) && part >= 0),\n );\n if (\n options == null ||\n !Array.isArray(options.authority) ||\n options.authority.length === 0 ||\n options.authority.some(\n (outcome) =>\n outcome == null ||\n typeof outcome.allowed !== \"boolean\" ||\n !validPath(outcome.path),\n ) ||\n !Array.isArray(options.serverOwnedFields) ||\n options.serverOwnedFields.some(\n (field) =>\n field == null ||\n !validPath(field.path) ||\n typeof field.path.at(-1) !== \"string\" ||\n typeof field.value !== \"string\",\n )\n ) {\n throw new TypeError(\n \"Expected explicit trusted authority outcomes and server-owned fields.\",\n );\n }\n}\n\n// Inspect source paths without executing accessors, even on invalid documents.\nfunction isMissingPreparationParent(\n document: unknown,\n path: FieldPath,\n): boolean {\n let value = document;\n for (const part of path) {\n if (value === null || typeof value !== \"object\") return true;\n const descriptor = Object.getOwnPropertyDescriptor(value, part);\n if (descriptor == null) return true;\n if (!(\"value\" in descriptor)) return false;\n ({ value } = descriptor);\n }\n return false;\n}\n\nfunction checkServerOwnedFields(\n document: unknown,\n fields: readonly ServerOwnedField[],\n targets: ReadonlyMap<string, PreparationTarget>,\n unavailable: readonly FieldPath[],\n truncated: boolean,\n): { field: ServerOwnedField; target: PreparationTarget; property: string }[] {\n const seen = new Set<string>();\n const checked = [];\n for (const field of fields) {\n const parent = field.path.slice(0, -1);\n if (isMissingPreparationParent(document, parent)) {\n throw new TypeError(\"Server-owned field parent path does not exist.\");\n }\n const target = targets.get(JSON.stringify(parent));\n if (target == null) {\n // A failed type/context check cannot establish semantic target identity.\n const blocked = unavailable.some((path) =>\n path.every((part, index) => parent[index] === part),\n );\n if (blocked || truncated) {\n const source = field.path.at(-1) as string;\n const { standardContext } = getContextTables();\n if (resolveProperty(source, standardContext).name != null) {\n checkServerOwnedField(field, standardContext, seen);\n }\n continue;\n }\n throw new TypeError(\n \"Server-owned field parents must be existing supported documents, not references or opaque data.\",\n );\n }\n const property = checkServerOwnedField(field, target.context, seen);\n checked.push({ field, target, property });\n }\n return checked;\n}\n\n// Validate caller configuration before document errors can stop preparation.\nfunction checkServerOwnedField(\n field: ServerOwnedField,\n context: DocumentContext,\n seen: Set<string>,\n): string {\n const parentPath = field.path.slice(0, -1);\n const source = field.path.at(-1) as string;\n const resolved = resolveProperty(source, context);\n const property = resolved.name;\n if (\n !resolved.compatible ||\n property == null ||\n ![\"id\", \"actor\", \"attributedTo\", \"published\", \"updated\"].includes(property)\n ) {\n throw new TypeError(\n \"Server-owned fields must identify a supported identity or timestamp property.\",\n );\n }\n const identity = JSON.stringify([...parentPath, property]);\n if (seen.has(identity)) {\n throw new TypeError(\n \"Specify each server-owned semantic field only once, including aliases.\",\n );\n }\n seen.add(identity);\n const invalidServerValue: Report = () => {\n throw new TypeError(`Invalid server-owned value for ${property}.`);\n };\n if (property === \"published\" || property === \"updated\") {\n checkDateTime(field.value, field.path, invalidServerValue);\n } else {\n checkReference(field.value, field.path, invalidServerValue);\n }\n return property;\n}\n\n// Compare a checked server-owned value without rewriting a submitted claim.\nfunction proposeServerField(\n field: ServerOwnedField,\n target: PreparationTarget,\n property: string,\n report: Report,\n changes: NormalizationChange[],\n): void {\n const parentPath = field.path.slice(0, -1);\n const source = field.path.at(-1) as string;\n const aliases = Object.keys(target.values).filter(\n (key) => resolveProperty(key, target.context).name === property,\n );\n const supplied = aliases.flatMap((key) => {\n const value = target.values[key];\n const path = [...parentPath, key];\n if (Array.isArray(value)) {\n return value.flatMap((entry, index) =>\n entry === null ? [] : [{ entry, path: [...path, index] }],\n );\n }\n return value === null ? [] : [{ entry: value, path }];\n });\n if (supplied.length > 0) {\n if (supplied.length !== 1 || supplied[0]!.entry !== field.value) {\n for (const suppliedValue of supplied) {\n report(\n \"server_owned_field_conflict\",\n suppliedValue.path,\n \"This field must match the server-owned value for this creation operation.\",\n );\n }\n }\n return;\n }\n // Prefer the requested source spelling even when another null alias exists.\n const key = Object.hasOwn(target.values, source)\n ? source\n : (aliases[0] ?? source);\n const path = [...parentPath, key];\n // Replace an omission at this source path with the authoritative proposal.\n const omission = changes.findIndex(\n (change) =>\n change.operation === \"remove\" &&\n (change.reason === \"omit_empty_property_list\" ||\n change.reason === \"omit_absent_identifier\") &&\n JSON.stringify(change.path) === JSON.stringify(path),\n );\n if (omission >= 0) changes.splice(omission, 1);\n const common = {\n reason: \"assign_server_owned_field\",\n path,\n after: field.value,\n message: `Use the server-proposed ${property} for this creation operation.`,\n };\n changes.push(\n Object.hasOwn(target.values, key)\n ? {\n ...common,\n operation: \"replace\",\n before: target.values[key] as JsonValue,\n }\n : { ...common, operation: \"add\" },\n );\n}\n\n/**\n * Prepares a creation preview against trusted server values and permission\n * outcomes. Does not determine authorization, allocate values, or persist.\n *\n * Integration boundary: https://github.com/fedify-dev/drfed/issues/152\n * The write operation constructs options from trusted server state, not client\n * JSON. It must check every local write, including nested creations, and recheck\n * permissions at commit. This preview is not an authorization token. The caller\n * also owns keeping committed IDs/timestamps consistent with the shown preview.\n * Merely referencing or embedding an actor/resource does not request a write.\n *\n * Paths identify original source locations; owned-field aliases are resolved\n * within the supported context profile. Matching singleton values are retained;\n * absent/null values receive explicit additions/replacements. Conflicts block\n * the preview. Throws TypeError for invalid trusted options/target paths.\n * @returns Original-input diagnostics and any explicit creation preview changes.\n */\nexport function prepareDocument(\n document: unknown,\n options: DocumentPreparationOptions,\n): DocumentValidationResult {\n checkPreparationOptions(options);\n const reporter = createReporter();\n const changes: NormalizationChange[] = [];\n const requested = new Set(\n options.serverOwnedFields.map(({ path }) =>\n JSON.stringify(path.slice(0, -1)),\n ),\n );\n const targets = new Map<string, PreparationTarget>();\n const unavailable: FieldPath[] = [];\n // Use only documents reached by vocabulary traversal: arbitrary extension\n // objects and unresolved IRI references must not become local write targets.\n checkDocumentValue(\n document,\n [],\n reporter,\n changes,\n (values, path, context) => {\n const key = JSON.stringify(path);\n if (requested.has(key)) targets.set(key, { values, context });\n },\n (path) => unavailable.push(path),\n );\n const structural = reporter.result();\n const checkedFields = checkServerOwnedFields(\n document,\n options.serverOwnedFields,\n targets,\n unavailable,\n structural.diagnostics.some(\n ({ reason }) => reason === \"diagnostic_limit_reached\",\n ),\n );\n for (const outcome of options.authority) {\n if (!outcome.allowed) {\n reporter.report(\n \"unauthorized_local_identity\",\n [...outcome.path],\n \"The server denied use of this local identity for the requested operation.\",\n );\n }\n }\n let result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return result;\n }\n for (const { field, target, property } of checkedFields) {\n proposeServerField(field, target, property, reporter.report, changes);\n }\n result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\") ||\n changes.length === 0\n ) {\n return result;\n }\n // Warnings describe the final server-owned replacement, not an omission.\n const replacedPaths = new Set(\n changes\n .filter((change) => change.operation === \"replace\")\n .map(({ path }) => JSON.stringify(path)),\n );\n const preview = createPreview(\n document as { [key: string]: JsonValue },\n changes,\n );\n const checked = validateDocument(preview);\n // Trusted values can still be inapplicable to the target's vocabulary type.\n // Retain original warnings (e.g. empty arrays) without duplicating them.\n reportPreviewDiagnostics(result, checked, reporter.report);\n result = reporter.result();\n if (\n !checked.complete ||\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return { ...result, complete: checked.complete && result.complete };\n }\n return {\n ...result,\n diagnostics: result.diagnostics.map((diagnostic) =>\n (diagnostic.reason === \"empty_property_list\" ||\n diagnostic.reason === \"absent_identifier\") &&\n replacedPaths.has(JSON.stringify(diagnostic.path))\n ? {\n ...diagnostic,\n message:\n \"This absent value is replaced by the trusted server-owned value in the preview.\",\n }\n : diagnostic,\n ),\n changes,\n normalizedDocument: preview,\n };\n}\n"],"mappings":";;;;;AAgFA,MAAa,oBAAoB;CAC/B,uBAAuB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACnE,gBAAgB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC5D,qBAAqB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACjE,aAAa;EAAE,UAAU;EAAc,UAAU;CAAQ;CACzD,kBAAkB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC9D,sBAAsB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAClE,yBAAyB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACrE,iBAAiB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC7D,6BAA6B;EAAE,UAAU;EAAa,UAAU;CAAQ;CACxE,6BAA6B;EAAE,UAAU;EAAa,UAAU;CAAQ;CACxE,6BAA6B;EAAE,UAAU;EAAW,UAAU;CAAQ;CACtE,0BAA0B;EAAE,UAAU;EAAW,UAAU;CAAQ;CACnE,kBAAkB;EAAE,UAAU;EAAW,UAAU;CAAQ;CAC3D,sBAAsB;EAAE,UAAU;EAAW,UAAU;C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AQ,UAAU,SAAS,QAAQ,OAAO;CAEtE,SAAS,SAAS,OAAO;CACzB,IACE,CAAC,OAAO,YACR,OAAO,YAAY,MAAM,EAAE,eAAe,aAAa,OAAO,KAC9D,QAAQ,WAAW,GAEnB,OAAO;CAGT,MAAM,gBAAgB,IAAI,IACxB,QACG,QAAQ,WAAW,OAAO,cAAc,SAAS,CAAC,CAClD,KAAK,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC,CAC3C;CACA,MAAM,UAAU,cACd,UACA,OACF;CACA,MAAM,UAAU,iBAAiB,OAAO;CAGxC,yBAAyB,QAAQ,SAAS,SAAS,MAAM;CACzD,SAAS,SAAS,OAAO;CACzB,IACE,CAAC,QAAQ,YACT,CAAC,OAAO,YACR,OAAO,YAAY,MAAM,EAAE,eAAe,aAAa,OAAO,GAE9D,OAAO;EAAE,GAAG;EAAQ,UAAU,QAAQ,YAAY,OAAO;CAAS;CAEpE,OAAO;EACL,GAAG;EACH,aAAa,OAAO,YAAY,KAAK,gBAClC,WAAW,WAAW,yBACrB,WAAW,WAAW,wBACxB,cAAc,IAAI,KAAK,UAAU,WAAW,IAAI,CAAC,IAC7C;GACE,GAAG;GACH,SACE;EACJ,IACA,UACN;EACA;EACA,oBAAoB;CACtB;AACF"}
1
+ {"version":3,"file":"document.mjs","names":["APObject"],"sources":["../src/document.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { MIMEType } from \"node:util\";\n\nimport {\n type $EntityType,\n Object as APObject,\n Accept,\n Activity,\n Add,\n Announce,\n Application,\n Arrive,\n Article,\n Block,\n Collection,\n CollectionPage,\n Create,\n Delete,\n Dislike,\n Flag,\n Follow,\n Group,\n Ignore,\n IntransitiveActivity,\n Invite,\n Join,\n Leave,\n Like,\n Link,\n Listen,\n Mention,\n Move,\n Note,\n Offer,\n OrderedCollection,\n OrderedCollectionPage,\n Organization,\n Person,\n Question,\n Read,\n Reject,\n Remove,\n Service,\n TentativeAccept,\n TentativeReject,\n Travel,\n Undo,\n Update,\n View,\n getEntityTypeById,\n} from \"@fedify/vocab\";\nimport { preloadedContexts } from \"@fedify/vocab-runtime\";\n\n/** The source property names and zero-based indexes leading to a finding. */\nexport type FieldPath = readonly (string | number)[];\n\nexport type DiagnosticCategory =\n | \"vocabulary\"\n | \"authority\"\n | \"support\"\n | \"compatibility\";\n\nexport type DiagnosticSeverity = \"error\" | \"warning\";\n\n/** Stable classifications; human-readable diagnostic messages may change. */\nexport const diagnosticReasons = {\n invalid_document_root: { category: \"vocabulary\", severity: \"error\" },\n non_json_value: { category: \"vocabulary\", severity: \"error\" },\n invalid_value_shape: { category: \"vocabulary\", severity: \"error\" },\n invalid_iri: { category: \"vocabulary\", severity: \"error\" },\n invalid_datetime: { category: \"vocabulary\", severity: \"error\" },\n invalid_multiplicity: { category: \"vocabulary\", severity: \"error\" },\n property_not_applicable: { category: \"vocabulary\", severity: \"error\" },\n invalid_context: { category: \"vocabulary\", severity: \"error\" },\n unauthorized_local_identity: { category: \"authority\", severity: \"error\" },\n server_owned_field_conflict: { category: \"authority\", severity: \"error\" },\n context_unavailable_offline: { category: \"support\", severity: \"error\" },\n unsupported_context_form: { category: \"support\", severity: \"error\" },\n unsupported_type: { category: \"support\", severity: \"error\" },\n unsupported_property: { category: \"support\", severity: \"error\" },\n unsupported_value_form: { category: \"support\", severity: \"error\" },\n processing_limit_exceeded: { category: \"support\", severity: \"error\" },\n diagnostic_limit_reached: { category: \"support\", severity: \"error\" },\n implicit_activitystreams_context: {\n category: \"compatibility\",\n severity: \"warning\",\n },\n extension_property_unchecked: {\n category: \"compatibility\",\n severity: \"warning\",\n },\n empty_property_list: { category: \"compatibility\", severity: \"warning\" },\n absent_identifier: { category: \"compatibility\", severity: \"warning\" },\n} as const satisfies Record<\n string,\n {\n readonly category: DiagnosticCategory;\n readonly severity: DiagnosticSeverity;\n }\n>;\n\nexport type DiagnosticReason = keyof typeof diagnosticReasons;\n\nexport interface Diagnostic {\n readonly reason: DiagnosticReason;\n readonly category: DiagnosticCategory;\n readonly severity: DiagnosticSeverity;\n readonly path: FieldPath;\n readonly message: string;\n}\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\n/** A proposed transformation; validation never applies it to the input. */\nexport type NormalizationChange =\n | {\n readonly operation: \"add\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly after: JsonValue;\n readonly message: string;\n }\n | {\n readonly operation: \"replace\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly before: JsonValue;\n readonly after: JsonValue;\n readonly message: string;\n }\n | {\n readonly operation: \"remove\";\n readonly reason: string;\n readonly path: FieldPath;\n readonly before: JsonValue;\n readonly message: string;\n };\n\nexport interface DocumentValidationResult {\n /** Whether checks finished, including a definite invalid-input conclusion. */\n readonly complete: boolean;\n readonly diagnostics: readonly Diagnostic[];\n readonly normalizedDocument?: { readonly [key: string]: JsonValue };\n readonly changes: readonly NormalizationChange[];\n}\n\n/** A permission outcome established by server code, not by document content. */\nexport interface DocumentAuthority {\n readonly allowed: boolean;\n /** Original document location; use [] for an operation-level denial. */\n readonly path: FieldPath;\n}\n\n/** An authoritative creation value allocated by the caller, never the editor. */\nexport interface ServerOwnedField {\n /** Source path to id, actor, attributedTo, published, or updated. */\n readonly path: FieldPath;\n readonly value: string;\n}\n\n/** Trusted server inputs; these options must not be accepted from a client. */\nexport interface DocumentPreparationOptions {\n /** At least one explicit outcome is required; omission never means allowed. */\n readonly authority: readonly [DocumentAuthority, ...DocumentAuthority[]];\n readonly serverOwnedFields: readonly ServerOwnedField[];\n}\n\nconst activityStreamsContext = \"https://www.w3.org/ns/activitystreams\";\nconst maximumDiagnostics = 100;\nconst maximumPathDepth = 64;\nconst actorTypes = [Application, Group, Organization, Person, Service];\n/** The ActivityStreams properties that address a document's recipients. */\nexport const addressingProperties = [\n \"to\",\n \"cc\",\n \"bto\",\n \"bcc\",\n \"audience\",\n] as const;\n// AS2 vocabulary Object properties that do not also apply to Link.\nconst objectOnlyProperties: ReadonlySet<string> = new Set([\n \"attachment\",\n \"attributedTo\",\n \"audience\",\n \"content\",\n \"contentMap\",\n \"context\",\n \"endTime\",\n \"generator\",\n \"icon\",\n \"image\",\n \"inReplyTo\",\n \"location\",\n \"published\",\n \"replies\",\n \"startTime\",\n \"summary\",\n \"summaryMap\",\n \"tag\",\n \"updated\",\n \"url\",\n \"to\",\n \"bto\",\n \"cc\",\n \"bcc\",\n \"duration\",\n]);\n\ntype Report = (\n reason: DiagnosticReason,\n path: FieldPath,\n message: string,\n) => void;\n\ntype VocabularyType = $EntityType | typeof Link | typeof Mention;\n\n// Unsupported custom types by Fedify are not in this checker's coverage.\nconst implementedTypes: ReadonlySet<VocabularyType> = new Set<VocabularyType>([\n Note,\n APObject,\n Article,\n Application,\n Group,\n Organization,\n Person,\n Service,\n Collection,\n OrderedCollection,\n CollectionPage,\n OrderedCollectionPage,\n Link,\n Mention,\n Activity,\n Like,\n Create,\n Undo,\n Accept,\n Follow,\n IntransitiveActivity,\n Arrive,\n Travel,\n Add,\n Announce,\n Block,\n Delete,\n Dislike,\n Flag,\n Ignore,\n Invite,\n Join,\n Leave,\n Listen,\n Move,\n Offer,\n Question,\n Read,\n Reject,\n Remove,\n TentativeAccept,\n TentativeReject,\n Update,\n View,\n]);\n\n// Owns diagnostic collection and completion state for one validation call.\nfunction createReporter() {\n const diagnostics: Diagnostic[] = [];\n let complete = true;\n let truncated = false;\n\n const report: Report = (reason, path, message) => {\n if (truncated) return;\n if (diagnostics.length === maximumDiagnostics) {\n complete = false;\n truncated = true;\n diagnostics[maximumDiagnostics - 1] = {\n reason: \"diagnostic_limit_reached\",\n ...diagnosticReasons.diagnostic_limit_reached,\n path: [],\n message: \"Further diagnostics were omitted.\",\n };\n return;\n }\n const classification = diagnosticReasons[reason];\n if (classification.category === \"support\") complete = false;\n diagnostics.push({ reason, ...classification, path, message });\n };\n\n return {\n report,\n isFull: () => truncated,\n result: (): DocumentValidationResult => ({\n complete,\n diagnostics,\n changes: [],\n }),\n };\n}\n\nfunction readDocument(\n document: unknown,\n path: FieldPath,\n report: Report,\n): Record<string, unknown> | undefined {\n if (!isJsonValueShape(document)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n return undefined;\n }\n if (\n document == null ||\n typeof document !== \"object\" ||\n Array.isArray(document)\n ) {\n report(\"invalid_document_root\", path, \"Expected a document object.\");\n return undefined;\n }\n const prototype: unknown = Object.getPrototypeOf(document);\n if (prototype !== Object.prototype && prototype !== null) {\n report(\"non_json_value\", path, \"Expected a plain JSON data object.\");\n return undefined;\n }\n const keys = Reflect.ownKeys(document);\n if (keys.some((key) => typeof key !== \"string\")) {\n report(\n \"non_json_value\",\n path,\n \"JSON objects cannot have symbol properties.\",\n );\n return undefined;\n }\n const descriptors = Object.getOwnPropertyDescriptors(document);\n const values: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(descriptors).sort()) {\n const descriptor = descriptors[key]!;\n if (!(\"value\" in descriptor) || !descriptor.enumerable) {\n report(\n \"non_json_value\",\n [...path, key],\n \"Expected an enumerable data property.\",\n );\n return undefined;\n }\n const value: unknown = descriptor.value;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", [...path, key], \"Expected a JSON value.\");\n return undefined;\n }\n values[key] = value;\n }\n return values;\n}\n\n// This checks only the immediate JSON shape. Supported nested values are read\n// separately through readDocument() or visitList(), without invoking accessors.\nfunction isJsonValueShape(value: unknown): boolean {\n return (\n value === null ||\n typeof value === \"object\" ||\n typeof value === \"string\" ||\n typeof value === \"boolean\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n );\n}\n\n// Reports reference-rule failures without owning the diagnostic collection.\nfunction checkReference(value: unknown, path: FieldPath, report: Report): void {\n if (value === null) return;\n if (typeof value !== \"string\") {\n if (typeof value === \"object\") {\n report(\n \"unsupported_value_form\",\n path,\n \"Embedded values are not checked yet.\",\n );\n } else {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a resource reference, embedded object, or allowed list.\",\n );\n }\n return;\n }\n const hasControlOrSpace = Array.from(value).some((character) => {\n const point = character.codePointAt(0)!;\n return point <= 0x20 || point === 0x7f;\n });\n if (\n !value.isWellFormed() ||\n hasControlOrSpace ||\n /[<>\"{}|\\\\^`]/u.test(value) ||\n /%(?![\\da-f]{2})/iu.test(value)\n ) {\n report(\n \"invalid_iri\",\n path,\n \"Expected a syntactically valid IRI reference.\",\n );\n } else if (!/^[a-z][a-z\\d+.-]*:/iu.test(value)) {\n report(\n \"unsupported_value_form\",\n path,\n \"Relative references need a base-IRI policy.\",\n );\n } else if (!URL.canParse(value)) {\n report(\n \"unsupported_value_form\",\n path,\n \"This IRI cannot be represented by the current URL parser.\",\n );\n }\n}\n\n// Applies the current list-entry policy, independently of list traversal.\nfunction checkReferenceEntry(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n): void {\n if (value === null) return;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n } else if (Array.isArray(value)) {\n report(\"unsupported_value_form\", path, \"Nested lists are not checked yet.\");\n } else {\n check(value, path, report);\n }\n}\n\n// Visits data entries safely and constructs paths, without reference rules.\nfunction visitList(\n values: readonly unknown[],\n path: FieldPath,\n report: Report,\n visit: (value: unknown, path: FieldPath) => void,\n): void {\n if (Reflect.ownKeys(values).length > values.length + 1) {\n report(\n \"non_json_value\",\n path,\n \"Expected a JSON array without extra properties.\",\n );\n return;\n }\n for (let index = 0; index < values.length; index += 1) {\n const entryPath = [...path, index];\n const descriptor = Object.getOwnPropertyDescriptor(values, index);\n if (\n descriptor == null ||\n !(\"value\" in descriptor) ||\n !descriptor.enumerable\n ) {\n report(\n \"non_json_value\",\n entryPath,\n \"Expected an enumerable array entry.\",\n );\n continue;\n }\n const entry: unknown = descriptor.value;\n visit(entry, entryPath);\n }\n}\n\n// Coordinates reference rules with traversal and reporting.\nfunction checkReferenceValues(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference = checkReference,\n schedule: (work: () => void) => void = (work) => work(),\n): void {\n if (!Array.isArray(value)) {\n schedule(() => check(value, path, report));\n return;\n }\n if (value.length === 0) {\n report(\n \"unsupported_value_form\",\n path,\n \"Empty lists are not supported in this value position.\",\n );\n return;\n }\n visitList(\n value,\n path,\n (reason, entryPath, message) =>\n schedule(() => report(reason, entryPath, message)),\n (entry, entryPath) => {\n schedule(() => checkReferenceEntry(entry, entryPath, report, check));\n },\n );\n}\n\nfunction checkSingleReference(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n schedule: (work: () => void) => void,\n): void {\n checkSingleValue(\n value,\n path,\n (reason, entryPath, message) =>\n schedule(() => report(reason, entryPath, message)),\n (entry, entryPath) => schedule(() => check(entry, entryPath, report)),\n );\n}\n\ninterface ContextTerm {\n readonly iri: string;\n readonly type?: string | undefined;\n readonly container?: string | undefined;\n readonly prefix: boolean;\n}\n\ninterface DocumentContext {\n readonly terms: ReadonlyMap<string, ContextTerm>;\n}\n\nfunction sameContextTerm(\n actual: ContextTerm | undefined,\n expected: ContextTerm,\n): boolean {\n return (\n actual != null &&\n actual.iri === expected.iri &&\n actual.type === expected.type &&\n actual.container === expected.container &&\n actual.prefix === expected.prefix\n );\n}\n\nfunction isSupportedContextUri(value: string): boolean {\n // URL parsing alone accepts characters that JSON-LD IRI mappings forbid.\n return (\n /^[a-z][a-z\\d+.-]*:/iu.test(value) &&\n !Array.from(value).some((character) => {\n const point = character.codePointAt(0)!;\n return (\n point <= 0x20 ||\n (point >= 0x7f && point <= 0x9f) ||\n '<>\"{}|\\\\^`'.includes(character)\n );\n }) &&\n URL.canParse(value)\n );\n}\n\n// Resolve only explicit terms, defined prefixes, keywords, and absolute IRIs.\n// This profile deliberately does not implement general JSON-LD expansion.\nfunction resolveTerm(\n value: string,\n terms: ReadonlyMap<string, ContextTerm>,\n pending?: ReadonlySet<string>,\n): string | undefined {\n if (value === \"@id\" || value === \"@type\") return value;\n if (pending?.has(value)) return undefined;\n const term = terms.get(value);\n if (term != null) return term.iri;\n const colon = value.indexOf(\":\");\n if (colon < 0) return undefined;\n if (pending?.has(value.slice(0, colon))) return undefined;\n const prefix = terms.get(value.slice(0, colon));\n if (prefix?.prefix) {\n const expanded = prefix.iri + value.slice(colon + 1);\n return isSupportedContextUri(expanded) ? expanded : undefined;\n }\n return isSupportedContextUri(value) ? value : undefined;\n}\n\nfunction readContextTerm(\n definition: unknown,\n path: FieldPath,\n terms: ReadonlyMap<string, ContextTerm>,\n report: Report,\n pending: ReadonlySet<string>,\n): ContextTerm | undefined {\n let values: Record<string, unknown>;\n if (typeof definition === \"string\") values = { \"@id\": definition };\n else if (\n definition !== null &&\n typeof definition === \"object\" &&\n !Array.isArray(definition)\n ) {\n const record = readDocument(definition, path, report);\n if (record == null) return undefined;\n values = record;\n } else {\n report(\n definition === null ? \"unsupported_context_form\" : \"invalid_context\",\n path,\n \"Only string and simple term definitions are supported.\",\n );\n return undefined;\n }\n if (\n Object.keys(values).some(\n (key) => ![\"@id\", \"@type\", \"@container\", \"@prefix\"].includes(key),\n )\n ) {\n report(\n \"unsupported_context_form\",\n path,\n \"Scoped contexts, reverse properties, and complex term definitions are not supported.\",\n );\n return undefined;\n }\n const id = values[\"@id\"];\n if (id === undefined) {\n report(\n \"unsupported_context_form\",\n path,\n \"Inline term definitions require an explicit @id in this profile.\",\n );\n return undefined;\n }\n if (typeof id !== \"string\") {\n report(\"invalid_context\", path, \"Expected a string @id mapping.\");\n return undefined;\n }\n if (/^[#/.]/u.test(id) || id.startsWith(\"_:\")) {\n report(\n \"unsupported_context_form\",\n path,\n \"Relative and blank-node term mappings are outside the supported profile.\",\n );\n return undefined;\n }\n if (id.startsWith(\"@\") && ![\"@id\", \"@type\"].includes(id)) {\n report(\n \"unsupported_context_form\",\n path,\n \"This keyword alias is outside the supported profile.\",\n );\n return undefined;\n }\n return resolveContextTerm(\n id,\n values,\n typeof definition === \"string\",\n path,\n terms,\n report,\n pending,\n );\n}\n\nfunction resolveContextTerm(\n id: string,\n values: Record<string, unknown>,\n implicitPrefix: boolean,\n path: FieldPath,\n terms: ReadonlyMap<string, ContextTerm>,\n report: Report,\n pending: ReadonlySet<string>,\n): ContextTerm | undefined {\n const iri = resolveTerm(id, terms, pending);\n if (iri == null) return undefined;\n if (iri.startsWith(\"@\") && Object.keys(values).some((key) => key !== \"@id\")) {\n report(\n \"unsupported_context_form\",\n path,\n \"Keyword aliases with additional coercion or container options are not supported.\",\n );\n return undefined;\n }\n const type = values[\"@type\"];\n if (typeof type === \"string\" && type.startsWith(\"@\") && type !== \"@id\") {\n report(\n \"unsupported_context_form\",\n path,\n \"This type coercion is outside the supported profile.\",\n );\n return undefined;\n }\n const expandedType =\n typeof type === \"string\" ? resolveTerm(type, terms, pending) : undefined;\n if (type !== undefined && expandedType === undefined) return undefined;\n const container = values[\"@container\"];\n if (container === \"@language\" && type !== undefined) {\n report(\n \"unsupported_context_form\",\n path,\n \"Language containers with type coercion are not supported.\",\n );\n return undefined;\n }\n if (\n container !== undefined &&\n container !== \"@language\" &&\n container !== \"@list\"\n ) {\n report(\n \"unsupported_context_form\",\n path,\n \"This container form is not supported.\",\n );\n return undefined;\n }\n if (\n values[\"@prefix\"] !== undefined &&\n typeof values[\"@prefix\"] !== \"boolean\"\n ) {\n report(\"invalid_context\", path, \"Expected a boolean @prefix flag.\");\n return undefined;\n }\n return {\n iri,\n type: expandedType,\n container,\n prefix:\n values[\"@prefix\"] === true || (implicitPrefix && /[#/:]$/u.test(iri)),\n };\n}\n\nfunction applyContextTerms(\n values: Record<string, unknown>,\n path: FieldPath,\n terms: Map<string, ContextTerm>,\n report: Report,\n protectedTerms?: ReadonlyMap<string, ContextTerm>,\n): boolean {\n let valid = true;\n const localReport: Report = (...args) => {\n valid = false;\n report(...args);\n };\n const pending = new Set(Object.keys(values));\n for (const name of pending) terms.delete(name);\n while (pending.size > 0) {\n if (!valid) return false;\n let resolved = false;\n for (const name of pending) {\n const fieldPath = [...path, name];\n if (name.length === 0) {\n localReport(\n \"invalid_context\",\n fieldPath,\n \"A context term cannot be empty.\",\n );\n continue;\n }\n if (name.includes(\":\")) {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"IRI-shaped term definitions are outside the supported inline profile.\",\n );\n continue;\n }\n if (name.startsWith(\"@\")) {\n if (\n protectedTerms == null &&\n name === \"@vocab\" &&\n values[name] === \"_:\"\n ) {\n pending.delete(name);\n } else {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"This context directive is outside the supported profile.\",\n );\n }\n continue;\n }\n const term = readContextTerm(\n values[name],\n fieldPath,\n terms,\n localReport,\n pending,\n );\n if (term == null) continue;\n const original = protectedTerms?.get(name);\n if (original != null && !sameContextTerm(term, original)) {\n localReport(\n \"unsupported_context_form\",\n fieldPath,\n \"The standard ActivityStreams context cannot be overridden.\",\n );\n continue;\n }\n terms.set(name, term);\n pending.delete(name);\n resolved = true;\n }\n if (!resolved && pending.size > 0 && valid) {\n for (const name of pending) {\n localReport(\n \"invalid_context\",\n [...path, name],\n \"The term has an unresolved or cyclic IRI mapping.\",\n );\n }\n }\n }\n return valid;\n}\n\ninterface ContextTables {\n readonly bundledContexts: ReadonlyMap<\n string,\n ReadonlyMap<string, ContextTerm>\n >;\n readonly standardTerms: ReadonlyMap<string, ContextTerm>;\n readonly standardContext: DocumentContext;\n}\n\nlet contextTables: ContextTables | undefined;\n\n// Interpret dependency contexts lazily so a profile mismatch cannot break import.\nfunction getContextTables(): ContextTables {\n if (contextTables != null) return contextTables;\n // Bundled availability is not blanket admission to this bounded profile.\n const bundledContexts = new Map<string, ReadonlyMap<string, ContextTerm>>();\n for (const url of [activityStreamsContext, \"https://w3id.org/security/v1\"]) {\n const document = preloadedContexts[url] as {\n \"@context\": Record<string, unknown>;\n };\n const terms = new Map<string, ContextTerm>();\n applyContextTerms(\n document[\"@context\"],\n [],\n terms,\n (_reason, _path, message) => {\n throw new Error(message);\n },\n );\n bundledContexts.set(url, terms);\n }\n const standardTerms = bundledContexts.get(activityStreamsContext)!;\n // Publish the cache only after all definitions have been interpreted.\n contextTables = {\n bundledContexts,\n standardTerms,\n standardContext: { terms: standardTerms },\n };\n return contextTables;\n}\n\nfunction applyContextEntry(\n value: unknown,\n path: FieldPath,\n terms: Map<string, ContextTerm>,\n report: Report,\n): boolean {\n const { bundledContexts, standardTerms } = getContextTables();\n if (typeof value === \"string\") {\n const url =\n value === \"http://www.w3.org/ns/activitystreams\"\n ? activityStreamsContext\n : value;\n const bundled = bundledContexts.get(url);\n if (bundled == null) {\n report(\n \"context_unavailable_offline\",\n path,\n \"This context is outside the offline allowlist.\",\n );\n return false;\n }\n for (const [name, term] of bundled) terms.set(name, term);\n return true;\n }\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n report(\n value === null || Array.isArray(value)\n ? \"unsupported_context_form\"\n : \"invalid_context\",\n path,\n \"Expected an allowlisted context or a simple inline context.\",\n );\n return false;\n }\n const definitions = readDocument(value, path, report);\n return (\n definitions != null &&\n applyContextTerms(definitions, path, terms, report, standardTerms)\n );\n}\n\n// Each child gets its parent's understood context; overrides never affect siblings.\nfunction checkContext(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n inherited?: DocumentContext,\n): DocumentContext | undefined {\n const { standardContext, standardTerms } = getContextTables();\n if (!Object.hasOwn(values, \"@context\")) {\n if (inherited != null) return inherited;\n report(\n \"implicit_activitystreams_context\",\n [...path, \"@context\"],\n \"Assuming the ActivityStreams context for this document.\",\n );\n return standardContext;\n }\n const terms = new Map(inherited?.terms);\n let valid = true;\n const localReport: Report = (...args) => {\n valid = false;\n report(...args);\n };\n const context = values[\"@context\"];\n const contextPath = [...path, \"@context\"];\n if (Array.isArray(context)) {\n visitList(context, contextPath, localReport, (entry, entryPath) => {\n if (!applyContextEntry(entry, entryPath, terms, localReport)) {\n valid = false;\n }\n });\n } else if (!applyContextEntry(context, contextPath, terms, localReport)) {\n valid = false;\n }\n if (!valid) return undefined;\n // Require the standard vocabulary, rather than inferring AS from arbitrary terms.\n if (\n ![...standardTerms].every(([name, term]) =>\n sameContextTerm(terms.get(name), term),\n )\n ) {\n report(\n \"unsupported_context_form\",\n contextPath,\n \"The context must include the standard ActivityStreams vocabulary.\",\n );\n return undefined;\n }\n return { terms };\n}\n\ninterface SourceProperty {\n readonly source: string;\n readonly name?: string;\n readonly iri?: string;\n readonly compatible: boolean;\n}\n\n// Retain one entry per source field. Aliases are never merged or re-serialized.\nfunction resolveProperty(\n source: string,\n context: DocumentContext,\n): SourceProperty {\n const { standardTerms } = getContextTables();\n const term = context.terms.get(source);\n const iri = term?.iri ?? resolveTerm(source, context.terms);\n for (const [name, standard] of standardTerms) {\n if (iri !== standard.iri || term?.container !== standard.container) {\n continue;\n }\n return {\n source,\n name,\n iri: standard.iri,\n compatible: term?.type === standard.type,\n };\n }\n if (iri === \"@id\") {\n return { source, name: \"id\", iri: \"@id\", compatible: true };\n }\n if (iri === \"@type\") {\n return { source, name: \"type\", iri: \"@type\", compatible: true };\n }\n return { source, ...(iri == null ? {} : { iri }), compatible: false };\n}\n\nfunction isOpaqueExtension(field: SourceProperty): boolean {\n const { standardTerms } = getContextTables();\n return (\n !field.source.startsWith(\"@\") &&\n !field.iri?.startsWith(\"@\") &&\n !Array.from(standardTerms.values()).some((term) => term.iri === field.iri)\n );\n}\n\nfunction isTypeCombination(value: unknown): boolean {\n if (!Array.isArray(value) || value.length <= 1) return false;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (\n descriptor == null ||\n !(\"value\" in descriptor) ||\n typeof descriptor.value !== \"string\"\n ) {\n return false;\n }\n }\n return true;\n}\n\nfunction checkType(\n value: unknown,\n path: FieldPath,\n report: Report,\n context: DocumentContext,\n): VocabularyType | undefined {\n const typeIri =\n typeof value === \"string\" ? resolveTerm(value, context.terms) : undefined;\n let Type: VocabularyType | undefined;\n if (typeIri != null) {\n Type = getEntityTypeById(typeIri);\n // Link classes are exported separately from Fedify's entity registry.\n if (typeIri === Link.typeId.href) Type = Link;\n else if (typeIri === Mention.typeId.href) Type = Mention;\n }\n if (Type == null || !implementedTypes.has(Type)) {\n const reason = Array.isArray(value)\n ? \"unsupported_value_form\"\n : value == null || typeof value === \"string\"\n ? \"unsupported_type\"\n : \"invalid_value_shape\";\n report(\n reason,\n path,\n isTypeCombination(value)\n ? \"Type combinations are not supported. Provide a single supported type.\"\n : Array.isArray(value)\n ? \"Type arrays are not supported. Provide a single type string.\"\n : \"This type is not supported by the checker yet.\",\n );\n return undefined;\n }\n\n return Type;\n}\n\nfunction isTypeOrSubtype(Type: VocabularyType, Base: VocabularyType): boolean {\n return Type === Base || Type.prototype instanceof Base;\n}\n\nfunction checkEmbeddedFedifyRange(\n Type: VocabularyType,\n expected: readonly VocabularyType[] | undefined,\n path: FieldPath,\n report: Report,\n): void {\n if (expected?.every((Expected) => !isTypeOrSubtype(Type, Expected))) {\n report(\n \"unsupported_value_form\",\n path,\n `Fedify cannot preserve this embedded type for this property. Use ${expected.map((Expected) => Expected.name).join(\", \")} or an IRI reference.`,\n );\n }\n}\n\nfunction getEmbeddedFedifyRange(\n property: string,\n collectionRange: readonly VocabularyType[] | undefined,\n): readonly VocabularyType[] | undefined {\n if (property === \"actor\" || property === \"attributedTo\") return actorTypes;\n return collectionRange?.filter((Expected) => Expected !== Link);\n}\n\nfunction checkDocumentType(\n values: Record<string, unknown>,\n fields: readonly SourceProperty[],\n path: FieldPath,\n context: DocumentContext,\n report: Report,\n): VocabularyType | undefined {\n const types = fields.filter(({ name }) => name === \"type\");\n if (types.length > 1) {\n for (const field of types) {\n report(\n \"unsupported_value_form\",\n [...path, field.source],\n \"Multiple type declarations are not supported. Provide a single type field.\",\n );\n }\n return undefined;\n }\n const source = types[0]?.source ?? \"type\";\n return checkType(values[source], [...path, source], report, context);\n}\n\n// Collection navigation and actor collection links each identify one resource.\nfunction getCollectionRange(\n Type: VocabularyType,\n property: string,\n): readonly VocabularyType[] | undefined {\n if (isTypeOrSubtype(Type, Collection)) {\n if ([\"current\", \"first\", \"last\"].includes(property)) {\n return [CollectionPage, Link];\n }\n }\n if (isTypeOrSubtype(Type, CollectionPage)) {\n if (property === \"partOf\") return [Collection, Link];\n if ([\"next\", \"prev\"].includes(property)) return [CollectionPage, Link];\n }\n const actor = actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor));\n if (actor) {\n if ([\"inbox\", \"outbox\"].includes(property)) {\n return [OrderedCollection, OrderedCollectionPage];\n }\n if ([\"following\", \"followers\", \"liked\"].includes(property)) {\n return [Collection];\n }\n }\n return undefined;\n}\n\nfunction isFunctionalProperty(Type: VocabularyType, property: string): boolean {\n if ([\"id\", \"mediaType\"].includes(property)) return true;\n if (getCollectionRange(Type, property) != null) return true;\n if (isTypeOrSubtype(Type, Link)) {\n return [\"href\", \"height\", \"width\", \"hreflang\"].includes(property);\n }\n if ([\"published\", \"updated\", \"startTime\", \"endTime\"].includes(property)) {\n return true;\n }\n if (isTypeOrSubtype(Type, Collection) && property === \"totalItems\") {\n return true;\n }\n return (\n isTypeOrSubtype(Type, OrderedCollectionPage) && property === \"startIndex\"\n );\n}\n\n// Count original data slots without reading accessors; the value checks report\n// sparse/accessor entries separately. Null entries do not contribute a value.\nfunction countValues(value: unknown): number {\n if (!Array.isArray(value)) return value === null ? 0 : 1;\n let count = 0;\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (\n descriptor != null &&\n \"value\" in descriptor &&\n descriptor.value !== null\n ) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction findMultipleAliases(\n Type: VocabularyType,\n fields: readonly SourceProperty[],\n values: Record<string, unknown>,\n): ReadonlySet<string> {\n const groups = new Map<string, string[]>();\n for (const field of fields) {\n if (\n field.name == null ||\n field.iri == null ||\n !isFunctionalProperty(Type, field.name)\n ) {\n continue;\n }\n if (countValues(values[field.source]) === 0) continue;\n const group = groups.get(field.iri) ?? [];\n group.push(field.source);\n groups.set(field.iri, group);\n }\n const multiple = new Set<string>();\n for (const group of groups.values()) {\n if (group.length < 2) continue;\n for (const source of group) {\n // The existing functional-array check reports its own multiplicity.\n if (countValues(values[source]) <= 1) multiple.add(source);\n }\n }\n return multiple;\n}\n\nfunction checkNonNegativeInteger(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (value === null) return;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n report(\"invalid_value_shape\", path, \"Expected a non-negative integer.\");\n }\n}\n\n// Functional properties count non-null values but retain source array indexes.\nfunction checkSingleValue(\n value: unknown,\n path: FieldPath,\n report: Report,\n check: typeof checkReference,\n): void {\n if (!Array.isArray(value)) {\n check(value, path, report);\n return;\n }\n if (value.length === 0) {\n report(\n \"unsupported_value_form\",\n path,\n \"Empty lists are not supported in this value position.\",\n );\n return;\n }\n const entries: { value: unknown; path: FieldPath }[] = [];\n visitList(value, path, report, (entry, entryPath) => {\n if (entry !== null) entries.push({ value: entry, path: entryPath });\n });\n if (entries.length > 1) {\n report(\n \"invalid_multiplicity\",\n path,\n \"Expected at most one non-null value.\",\n );\n }\n for (const entry of entries) {\n checkReferenceEntry(entry.value, entry.path, report, check);\n }\n}\n\nfunction checkLanguageTag(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (\n typeof value !== \"string\" ||\n !/^[a-z]{1,8}(?:-[a-z\\d]{1,8})*$/iu.test(value)\n ) {\n report(\"invalid_value_shape\", path, \"Expected a language tag.\");\n return;\n }\n try {\n void new Intl.Locale(value);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"unsupported_value_form\",\n path,\n \"This language tag is outside the current locale parser's support.\",\n );\n }\n}\n\nfunction checkText(\n value: unknown,\n path: FieldPath,\n report: Report,\n plain: boolean,\n): void {\n if (value === null) return;\n if (typeof value === \"string\") {\n if (plain && /<(?:[a-z][^>]*>|\\/[a-z][^>]*>|!--)/iu.test(value)) {\n report(\n \"invalid_value_shape\",\n path,\n \"Names must be plain text without HTML markup.\",\n );\n }\n return;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n report(\"invalid_value_shape\", path, \"Expected text.\");\n return;\n }\n const values = readDocument(value, path, report);\n if (values == null) return;\n if (!Object.hasOwn(values, \"@value\")) {\n report(\n \"unsupported_value_form\",\n path,\n \"Use a language-map property or an explicit @value object for localized text.\",\n );\n return;\n }\n for (const key of Object.keys(values).sort()) {\n const fieldPath = [...path, key];\n if (key === \"@value\") {\n if (typeof values[key] === \"string\") {\n checkText(values[key], fieldPath, report, plain);\n } else {\n report(\"invalid_value_shape\", fieldPath, \"Expected a text value.\");\n }\n } else if (key === \"@language\") {\n checkLanguageTag(values[key], fieldPath, report);\n } else {\n report(\n \"unsupported_value_form\",\n fieldPath,\n \"This text-value attribute is not supported yet.\",\n );\n }\n }\n}\n\nfunction checkLanguageMap(\n value: unknown,\n path: FieldPath,\n report: Report,\n plain: boolean,\n): void {\n if (value === null) return;\n if (typeof value !== \"object\" || Array.isArray(value)) {\n report(\"invalid_value_shape\", path, \"Expected a language map.\");\n return;\n }\n const values = readDocument(value, path, report);\n if (values == null) return;\n for (const language of Object.keys(values).sort()) {\n const fieldPath = [...path, language];\n checkLanguageTag(language, fieldPath, report);\n if (values[language] === null) continue;\n if (typeof values[language] === \"string\") {\n checkText(values[language], fieldPath, report, plain);\n } else {\n report(\n \"invalid_value_shape\",\n fieldPath,\n \"Expected a language-map string.\",\n );\n }\n }\n}\n\nfunction checkDateTime(value: unknown, path: FieldPath, report: Report): void {\n if (value === null) return;\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected a date-time string.\");\n return;\n }\n // AS2 permits omitted seconds, but requires an offset and uppercase T/Z.\n const match =\n /^(?<minute>\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2})(?<second>:\\d{2})?(?<fraction>\\.\\d+)?(?<offset>Z|[+-]\\d{2}:\\d{2})$/u.exec(\n value,\n );\n if (match == null) {\n report(\n \"invalid_datetime\",\n path,\n \"Expected an ActivityStreams date-time with a timezone.\",\n );\n return;\n }\n const { minute, second, fraction, offset } = match.groups!;\n // Check calendar components separately from representation support.\n try {\n void Temporal.Instant.from(`${minute}${second ?? \":00\"}${offset}`);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"invalid_datetime\",\n path,\n \"Expected a valid calendar date, time, and offset.\",\n );\n return;\n }\n if (second === \":60\") {\n report(\n \"unsupported_value_form\",\n path,\n \"Leap-second timestamps are not checked by the current date-time parser.\",\n );\n return;\n }\n // Native Temporal can be more permissive than Fedify's parser. Require\n // explicit seconds and nanosecond precision before parsing the original.\n if (second == null) {\n report(\n \"unsupported_value_form\",\n path,\n fraction != null\n ? \"ActivityStreams permits fractions without seconds, but Fedify requires explicit seconds before a fractional component.\"\n : \"ActivityStreams permits omitted seconds, but Fedify requires explicit seconds, such as 12:34:00Z.\",\n );\n return;\n }\n if (fraction != null && fraction.length > 10) {\n report(\n \"unsupported_value_form\",\n path,\n \"Fractional seconds exceeding nine digits cannot be preserved through Fedify parsing; provide at most nine fractional digits.\",\n );\n return;\n }\n try {\n void Temporal.Instant.from(value);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n report(\n \"unsupported_value_form\",\n path,\n \"This date-time matches the ActivityStreams format, but cannot be parsed as an instant without rewriting; provide a timestamp such as 2024-01-01T12:34:00Z.\",\n );\n }\n}\n\n// Share coverage classification with empty-array omission admission.\nfunction getCommonPropertyKind(\n Type: VocabularyType,\n property: string,\n): \"text\" | \"languageMap\" | \"datetime\" | \"id\" | \"mediaType\" | undefined {\n const object = isTypeOrSubtype(Type, APObject);\n const actor = actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor));\n const textProperties = object ? [\"name\", \"summary\", \"content\"] : [\"name\"];\n if (actor) textProperties.push(\"preferredUsername\");\n if (textProperties.includes(property)) return \"text\";\n if (\n textProperties.some(\n (name) => property === `${name}Map` && name !== \"preferredUsername\",\n )\n ) {\n return \"languageMap\";\n }\n if (\n object &&\n [\"published\", \"updated\", \"startTime\", \"endTime\"].includes(property)\n ) {\n return \"datetime\";\n }\n if (property === \"id\" || property === \"mediaType\") return property;\n return undefined;\n}\n\n// Scalar/common properties share checks; embedded references use the work stack.\nfunction checkCommonProperty(\n kind: ReturnType<typeof getCommonPropertyKind>,\n property: string,\n value: unknown,\n path: FieldPath,\n report: Report,\n): boolean {\n if (kind === \"text\") {\n checkReferenceValues(value, path, report, (entry, entryPath) =>\n checkText(entry, entryPath, report, property === \"name\"),\n );\n } else if (kind === \"languageMap\") {\n checkLanguageMap(value, path, report, property === \"nameMap\");\n } else if (kind === \"datetime\") {\n checkSingleValue(value, path, report, checkDateTime);\n } else if (kind === \"id\") {\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected an IRI identifier string.\");\n } else {\n checkReference(value, path, report);\n }\n } else if (kind === \"mediaType\") {\n checkSingleValue(value, path, report, (entry, entryPath) =>\n checkLinkProperty(property, entry, entryPath, report),\n );\n } else {\n // Null is absent even when this vocabulary property has no value rules yet.\n return value === null;\n }\n return true;\n}\n\nfunction proposePropertyOmission(\n value: unknown,\n path: FieldPath,\n report: Report,\n changes: NormalizationChange[],\n identifier: boolean,\n): boolean {\n const emptyArray = Array.isArray(value) && value.length === 0;\n if (!emptyArray && !identifier) return false;\n if (value !== null && !Array.isArray(value)) return false;\n let safe = true;\n let absent = true;\n if (Array.isArray(value)) {\n visitList(\n value,\n path,\n (...args) => {\n safe = false;\n report(...args);\n },\n (entry) => {\n if (entry !== null) absent = false;\n },\n );\n }\n if (!safe) return true;\n if (!absent) return false;\n report(\n emptyArray ? \"empty_property_list\" : \"absent_identifier\",\n path,\n emptyArray\n ? \"ActivityStreams represents empty property arrays by omission or null; the preview omits this property.\"\n : \"This identifier is absent; the preview omits it so Fedify receives no non-string identifier.\",\n );\n changes.push({\n operation: \"remove\",\n reason: emptyArray ? \"omit_empty_property_list\" : \"omit_absent_identifier\",\n path,\n before: value as JsonValue,\n message: emptyArray\n ? \"Omit an empty property array from the wire representation.\"\n : \"Omit an absent identifier from the wire representation.\",\n });\n return true;\n}\n\nfunction checkLinkRelation(\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (value === null) return;\n if (\n typeof value !== \"string\" ||\n value.length === 0 ||\n Array.from(value).some(\n (character) =>\n character.charCodeAt(0) <= 0x20 ||\n character.charCodeAt(0) === 0x7f ||\n character === \",\",\n )\n ) {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a relation token or absolute IRI without whitespace or commas.\",\n );\n } else if (/^[a-z][a-z\\d+.-]*:/iu.test(value)) {\n checkReference(value, path, report);\n } else if (!/^[a-z][a-z\\d.-]*$/iu.test(value)) {\n report(\n \"invalid_value_shape\",\n path,\n \"Expected a relation token or absolute IRI.\",\n );\n }\n}\n\n// Link metadata uses lexical checks without rewriting the original values.\nfunction checkLinkProperty(\n property: string,\n value: unknown,\n path: FieldPath,\n report: Report,\n): void {\n if (property === \"rel\") {\n checkReferenceValues(value, path, report, checkLinkRelation);\n return;\n }\n if (value === null) return;\n if (typeof value !== \"string\") {\n report(\"invalid_value_shape\", path, \"Expected a string.\");\n return;\n }\n if (property === \"href\") {\n checkReference(value, path, report);\n } else if (property === \"mediaType\") {\n try {\n void new MIMEType(value);\n } catch (error) {\n if (!(error instanceof TypeError)) throw error;\n report(\"invalid_value_shape\", path, \"Expected a MIME media type.\");\n }\n } else {\n checkLanguageTag(value, path, report);\n }\n}\n\n// Check explicit keyword shapes, without expanding contexts or keyword aliases.\n// Return whether @value contains literal JSON rather than nested JSON-LD.\nfunction checkExtensionKeywords(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n): boolean {\n if (Object.hasOwn(values, \"@id\") && typeof values[\"@id\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@id\"],\n \"Expected a string JSON-LD identifier.\",\n );\n }\n let jsonLiteral = values[\"@type\"] === \"@json\";\n if (Object.hasOwn(values, \"@type\")) {\n const type = values[\"@type\"];\n if (Array.isArray(type)) {\n visitList(type, [...path, \"@type\"], report, (entry, entryPath) => {\n if (typeof entry !== \"string\") {\n report(\n \"invalid_value_shape\",\n entryPath,\n \"Expected a JSON-LD type string.\",\n );\n }\n if (type.length === 1 && entry === \"@json\") jsonLiteral = true;\n });\n } else if (typeof type !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@type\"],\n \"Expected a JSON-LD type string or array of strings.\",\n );\n }\n }\n if (Object.hasOwn(values, \"@value\") && values[\"@language\"] != null) {\n if (typeof values[\"@language\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@language\"],\n \"Expected a string language tag or null.\",\n );\n }\n if (values[\"@value\"] !== null && typeof values[\"@value\"] !== \"string\") {\n report(\n \"invalid_value_shape\",\n [...path, \"@value\"],\n \"A JSON-LD language-tagged value must have a string @value or null absence.\",\n );\n }\n }\n return jsonLiteral;\n}\n\nfunction getInapplicableProperties(Type: VocabularyType): ReadonlySet<string> {\n return isTypeOrSubtype(Type, Link) ? objectOnlyProperties : new Set<string>();\n}\n\nfunction checkPathDepth(path: FieldPath, report: Report): boolean {\n if (path.length <= maximumPathDepth) return true;\n report(\n \"processing_limit_exceeded\",\n path,\n `Nesting exceeds the supported limit of ${maximumPathDepth} path segments.`,\n );\n return false;\n}\n\nfunction checkDocumentValue(\n rootDocument: unknown,\n rootPath: FieldPath,\n reporter: ReturnType<typeof createReporter>,\n changes: NormalizationChange[],\n onDocument?: (\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext,\n Type: VocabularyType,\n fields: readonly SourceProperty[],\n ) => void,\n onUnavailableDocument: (path: FieldPath) => void = () => undefined,\n): void {\n const { report, isFull } = reporter;\n const pending: (() => void)[] = [];\n const ancestors = new WeakSet<object>();\n\n // Check JSON safety and selected explicit keyword shapes. This is not full\n // JSON-LD validation; extension semantics and nested contexts remain unchecked.\n function checkExtension(\n value: unknown,\n path: FieldPath,\n keywords = true,\n ): void {\n if (!checkPathDepth(path, report)) return;\n if (!isJsonValueShape(value)) {\n report(\"non_json_value\", path, \"Expected a JSON value.\");\n return;\n }\n if (value === null || typeof value !== \"object\") return;\n if (ancestors.has(value)) {\n report(\"non_json_value\", path, \"JSON documents cannot contain cycles.\");\n return;\n }\n ancestors.add(value);\n pending.push(() => ancestors.delete(value));\n const children: (() => void)[] = [];\n if (Array.isArray(value)) {\n visitList(value, path, report, (entry, entryPath) => {\n children.push(() => checkExtension(entry, entryPath, keywords));\n });\n } else {\n const values = readDocument(value, path, report);\n if (values != null) {\n const jsonLiteral =\n keywords && checkExtensionKeywords(values, path, report);\n for (const key of Object.keys(values)) {\n const childKeywords = keywords && !(jsonLiteral && key === \"@value\");\n children.push(() =>\n checkExtension(values[key], [...path, key], childKeywords),\n );\n }\n }\n }\n for (const child of children.reverse()) pending.push(child);\n }\n\n function checkDocument(\n document: unknown,\n path: FieldPath,\n inherited?: DocumentContext,\n expectedTypes?: readonly VocabularyType[],\n fedifyTypes?: readonly VocabularyType[],\n ): void {\n if (!checkPathDepth(path, report)) {\n onUnavailableDocument(path);\n return;\n }\n if (\n document !== null &&\n typeof document === \"object\" &&\n ancestors.has(document)\n ) {\n report(\"non_json_value\", path, \"JSON documents cannot contain cycles.\");\n onUnavailableDocument(path);\n return;\n }\n const values = readDocument(document, path, report);\n if (values == null) {\n onUnavailableDocument(path);\n return;\n }\n const sourceDocument = document as object;\n const context = checkContext(values, path, report, inherited);\n if (context == null) {\n onUnavailableDocument(path);\n return;\n }\n const fields = Object.keys(values)\n .filter((source) => source !== \"@context\")\n .sort()\n .map((source) => resolveProperty(source, context));\n const Type = checkDocumentType(values, fields, path, context, report);\n if (Type == null) {\n onUnavailableDocument(path);\n return;\n }\n if (expectedTypes?.every((Expected) => !isTypeOrSubtype(Type, Expected))) {\n report(\n \"invalid_value_shape\",\n path,\n \"The embedded type is outside this property's collection range.\",\n );\n onUnavailableDocument(path);\n return;\n }\n checkEmbeddedFedifyRange(Type, fedifyTypes, path, report);\n onDocument?.(values, path, context, Type, fields);\n const isObject = isTypeOrSubtype(Type, APObject);\n const isLink = isTypeOrSubtype(Type, Link);\n const isActivity = isTypeOrSubtype(Type, Activity);\n const isIntransitive = isTypeOrSubtype(Type, IntransitiveActivity);\n const isCollection = isTypeOrSubtype(Type, Collection);\n const isOrderedPage = isTypeOrSubtype(Type, OrderedCollectionPage);\n const linkProperties = isLink\n ? [\"href\", \"mediaType\", \"hreflang\", \"rel\"]\n : [];\n const integerProperties = isLink\n ? [\"height\", \"width\"]\n : isOrderedPage\n ? [\"totalItems\", \"startIndex\"]\n : isCollection\n ? [\"totalItems\"]\n : [];\n const referenceProperties = [\"preview\"];\n if (isObject) {\n referenceProperties.push(\n \"attributedTo\",\n \"location\",\n ...addressingProperties,\n );\n }\n if (isActivity) {\n referenceProperties.push(\n \"actor\",\n \"object\",\n \"target\",\n \"origin\",\n \"result\",\n \"instrument\",\n );\n }\n if (isCollection) referenceProperties.push(\"items\", \"orderedItems\");\n const omittableProperties = new Set([\n ...integerProperties,\n ...linkProperties,\n ...referenceProperties,\n ]);\n const multipleAliases = findMultipleAliases(Type, fields, values);\n const inapplicableProperties = getInapplicableProperties(Type);\n\n ancestors.add(sourceDocument);\n pending.push(() => {\n ancestors.delete(sourceDocument);\n });\n // LIFO work preserves the same depth-first, sorted-property order.\n for (const field of fields\n .filter(({ name }) => name !== \"type\")\n .reverse()) {\n const { source, name: key } = field;\n const intransitiveObject = isIntransitive && key === \"object\";\n pending.push(() => {\n const value = values[source];\n const fieldPath = [...path, source];\n if (key == null) {\n if (isOpaqueExtension(field)) {\n report(\n \"extension_property_unchecked\",\n fieldPath,\n \"This custom property's data is preserved; its semantics were not checked.\",\n );\n checkExtension(value, fieldPath);\n return;\n }\n report(\n \"unsupported_property\",\n fieldPath,\n \"This property is outside the checker's Fedify vocabulary coverage.\",\n );\n return;\n }\n if (!field.compatible) {\n report(\n \"unsupported_value_form\",\n fieldPath,\n \"This spelling's type coercion differs from the supported vocabulary term.\",\n );\n return;\n }\n if (inapplicableProperties.has(key)) {\n if (value === null) return;\n report(\n \"property_not_applicable\",\n fieldPath,\n \"This property applies to Object documents, not Link documents.\",\n );\n return;\n }\n if (multipleAliases.has(source)) {\n report(\n \"invalid_multiplicity\",\n fieldPath,\n \"Multiple aliases supply values for one functional property.\",\n );\n }\n const collectionRange = getCollectionRange(Type, key);\n const commonKind = getCommonPropertyKind(Type, key);\n const supported =\n omittableProperties.has(key) ||\n collectionRange != null ||\n commonKind != null;\n // Preview omission of empty supported arrays and absent identifiers.\n if (\n supported &&\n proposePropertyOmission(\n value,\n fieldPath,\n report,\n changes,\n commonKind === \"id\",\n )\n ) {\n return;\n }\n if (integerProperties.includes(key)) {\n checkSingleValue(value, fieldPath, report, checkNonNegativeInteger);\n } else if (linkProperties.includes(key)) {\n if (key === \"rel\") {\n checkLinkProperty(key, value, fieldPath, report);\n } else {\n checkSingleValue(value, fieldPath, report, (entry, entryPath) =>\n checkLinkProperty(key, entry, entryPath, report),\n );\n }\n } else if (\n checkCommonProperty(commonKind, key, value, fieldPath, report)\n ) {\n // Common properties and null absence were checked above.\n } else if (intransitiveObject) {\n checkReferenceValues(value, fieldPath, report, (entry, entryPath) => {\n if (entry !== null) {\n report(\n \"property_not_applicable\",\n entryPath,\n \"The object property does not apply to intransitive activities.\",\n );\n }\n });\n } else if (\n referenceProperties.includes(key) ||\n collectionRange != null\n ) {\n const checks: (() => void)[] = [];\n const checkValues =\n collectionRange == null\n ? checkReferenceValues\n : checkSingleReference;\n checkValues(\n value,\n fieldPath,\n report,\n (entry, entryPath) => {\n if (\n entry !== null &&\n typeof entry === \"object\" &&\n !Array.isArray(entry)\n ) {\n // AS ranges can be wider than Fedify's typed decoders. Keep\n // vocabulary errors distinct from unsupported embedded forms.\n checkDocument(\n entry,\n entryPath,\n context,\n collectionRange,\n getEmbeddedFedifyRange(key, collectionRange),\n );\n } else {\n checkReference(entry, entryPath, report);\n }\n },\n (check) => checks.push(check),\n );\n for (const check of checks.reverse()) pending.push(check);\n } else {\n report(\n \"unsupported_property\",\n fieldPath,\n \"This property is not checked by the initial implementation.\",\n );\n }\n });\n }\n }\n\n checkDocument(rootDocument, rootPath);\n while (pending.length > 0 && !isFull()) {\n pending.pop()!();\n }\n}\n\n// Clone checked JSON iteratively so a deeply nested preview cannot overflow\n// the JavaScript call stack or share mutable containers with the input.\nfunction createPreview(\n document: { [key: string]: JsonValue },\n changes: readonly NormalizationChange[],\n): { [key: string]: JsonValue } {\n const root: { [key: string]: JsonValue } = {};\n const pending = [\n {\n source: document as object,\n target: root as { [key: string]: JsonValue },\n },\n ];\n while (pending.length > 0) {\n const { source, target } = pending.pop()!;\n for (const [key, value] of Object.entries(source)) {\n let copy = value as JsonValue;\n if (value !== null && typeof value === \"object\") {\n // Each JSON occurrence has its own path and proposed field values.\n copy = Array.isArray(value) ? [] : {};\n pending.push({\n source: value,\n target: copy as { [key: string]: JsonValue },\n });\n }\n Object.defineProperty(target, key, {\n value: copy,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n for (const change of changes) {\n let parent = root;\n for (const key of change.path.slice(0, -1)) {\n parent = parent[key] as { [key: string]: JsonValue };\n }\n const key = change.path.at(-1)!;\n if (change.operation === \"remove\") delete parent[key];\n else {\n Object.defineProperty(parent, key, {\n value: change.after,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n return root;\n}\n\n/**\n * Checks the implemented Activity Vocabulary types, including nested\n * activity objects, without network access or writes. Embedded objects inherit\n * the parent's context. Collections add member, count, and navigation checks.\n * Question uses shared intransitive rules; poll-specific\n * fields remain unsupported pending #155.\n *\n * Supports allowlisted bundled contexts and simple inline aliases/prefixes,\n * single types, id, string content,\n * attribution/location and activity actor, object, target, origin, result,\n * and instrument values. These can be IRI references or supported\n * embedded types, singly or in flat lists. Empty supported property arrays\n * receive omission previews. Intransitive activities\n * reject a non-null object property. Other forms produce\n * support diagnostics and `complete: false`. This is not a permission check,\n * a Fedify parsability check, or full ActivityStreams validation.\n * The input must be plain JSON data, not a Proxy.\n * Context interpretation is bounded and synchronous. Unknown\n * custom properties are preserved as opaque JSON with warnings. Complex\n * contexts remain unsupported; input is never expanded.\n * Null list entries mean absence. Functional properties accept at most one\n * non-null value, preserving array-index paths. Common text/language maps,\n * timestamps, actor preferredUsername, and addressing are checked.\n * @returns Findings at original-input paths, with an explicit omission preview\n * for empty supported property arrays and absent identifiers only when validation\n * completes without errors.\n */\nexport function validateDocument(document: unknown): DocumentValidationResult {\n const reporter = createReporter();\n const changes: NormalizationChange[] = [];\n checkDocumentValue(document, [], reporter, changes);\n const result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\") ||\n changes.length === 0\n ) {\n return result;\n }\n const preview = createPreview(\n document as { [key: string]: JsonValue },\n changes,\n );\n const checked = validateDocument(preview);\n reportPreviewDiagnostics(result, checked, reporter.report);\n const previewResult = reporter.result();\n if (\n !checked.complete ||\n !previewResult.complete ||\n previewResult.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return {\n ...previewResult,\n complete: checked.complete && previewResult.complete,\n };\n }\n return { ...previewResult, changes, normalizedDocument: preview };\n}\n\n// Preview checks retain source diagnostics without repeating unchanged findings.\nfunction reportPreviewDiagnostics(\n original: DocumentValidationResult,\n checked: DocumentValidationResult,\n report: Report,\n): void {\n for (const diagnostic of checked.diagnostics) {\n if (\n !original.diagnostics.some(\n (existing) =>\n existing.reason === diagnostic.reason &&\n JSON.stringify(existing.path) === JSON.stringify(diagnostic.path),\n )\n ) {\n report(diagnostic.reason, diagnostic.path, diagnostic.message);\n }\n }\n}\n\ninterface PreparationTarget {\n readonly values: Record<string, unknown>;\n readonly context: DocumentContext;\n}\n\n// #152 supplies these options after its own permission checks and allocation.\n// TypeErrors identify caller mistakes; document problems use diagnostics.\n// Validating option shapes does not authenticate their source.\nfunction checkPreparationOptions(options: DocumentPreparationOptions): void {\n const validPath = (path: FieldPath) =>\n Array.isArray(path) &&\n path.every(\n (part) =>\n typeof part === \"string\" ||\n (typeof part === \"number\" && Number.isSafeInteger(part) && part >= 0),\n );\n if (\n options == null ||\n !Array.isArray(options.authority) ||\n options.authority.length === 0 ||\n options.authority.some(\n (outcome) =>\n outcome == null ||\n typeof outcome.allowed !== \"boolean\" ||\n !validPath(outcome.path),\n ) ||\n !Array.isArray(options.serverOwnedFields) ||\n options.serverOwnedFields.some(\n (field) =>\n field == null ||\n !validPath(field.path) ||\n typeof field.path.at(-1) !== \"string\" ||\n typeof field.value !== \"string\",\n )\n ) {\n throw new TypeError(\n \"Expected explicit trusted authority outcomes and server-owned fields.\",\n );\n }\n}\n\n// Inspect source paths without executing accessors, even on invalid documents.\nfunction isMissingPreparationParent(\n document: unknown,\n path: FieldPath,\n): boolean {\n let value = document;\n for (const part of path) {\n if (value === null || typeof value !== \"object\") return true;\n const descriptor = Object.getOwnPropertyDescriptor(value, part);\n if (descriptor == null) return true;\n if (!(\"value\" in descriptor)) return false;\n ({ value } = descriptor);\n }\n return false;\n}\n\nfunction checkServerOwnedFields(\n document: unknown,\n fields: readonly ServerOwnedField[],\n targets: ReadonlyMap<string, PreparationTarget>,\n unavailable: readonly FieldPath[],\n truncated: boolean,\n): { field: ServerOwnedField; target: PreparationTarget; property: string }[] {\n const seen = new Set<string>();\n const checked = [];\n for (const field of fields) {\n const parent = field.path.slice(0, -1);\n if (isMissingPreparationParent(document, parent)) {\n throw new TypeError(\"Server-owned field parent path does not exist.\");\n }\n const target = targets.get(JSON.stringify(parent));\n if (target == null) {\n // A failed type/context check cannot establish semantic target identity.\n const blocked = unavailable.some((path) =>\n path.every((part, index) => parent[index] === part),\n );\n if (blocked || truncated) {\n const source = field.path.at(-1) as string;\n const { standardContext } = getContextTables();\n if (resolveProperty(source, standardContext).name != null) {\n checkServerOwnedField(field, standardContext, seen);\n }\n continue;\n }\n throw new TypeError(\n \"Server-owned field parents must be existing supported documents, not references or opaque data.\",\n );\n }\n const property = checkServerOwnedField(field, target.context, seen);\n checked.push({ field, target, property });\n }\n return checked;\n}\n\n// Validate caller configuration before document errors can stop preparation.\nfunction checkServerOwnedField(\n field: ServerOwnedField,\n context: DocumentContext,\n seen: Set<string>,\n): string {\n const parentPath = field.path.slice(0, -1);\n const source = field.path.at(-1) as string;\n const resolved = resolveProperty(source, context);\n const property = resolved.name;\n if (\n !resolved.compatible ||\n property == null ||\n ![\"id\", \"actor\", \"attributedTo\", \"published\", \"updated\"].includes(property)\n ) {\n throw new TypeError(\n \"Server-owned fields must identify a supported identity or timestamp property.\",\n );\n }\n const identity = JSON.stringify([...parentPath, property]);\n if (seen.has(identity)) {\n throw new TypeError(\n \"Specify each server-owned semantic field only once, including aliases.\",\n );\n }\n seen.add(identity);\n const invalidServerValue: Report = () => {\n throw new TypeError(`Invalid server-owned value for ${property}.`);\n };\n if (property === \"published\" || property === \"updated\") {\n checkDateTime(field.value, field.path, invalidServerValue);\n } else {\n checkReference(field.value, field.path, invalidServerValue);\n }\n return property;\n}\n\n// Compare a checked server-owned value without rewriting a submitted claim.\nfunction proposeServerField(\n field: ServerOwnedField,\n target: PreparationTarget,\n property: string,\n report: Report,\n changes: NormalizationChange[],\n): void {\n const parentPath = field.path.slice(0, -1);\n const source = field.path.at(-1) as string;\n const aliases = Object.keys(target.values).filter(\n (key) => resolveProperty(key, target.context).name === property,\n );\n const supplied = aliases.flatMap((key) => {\n const value = target.values[key];\n const path = [...parentPath, key];\n if (Array.isArray(value)) {\n return value.flatMap((entry, index) =>\n entry === null ? [] : [{ entry, path: [...path, index] }],\n );\n }\n return value === null ? [] : [{ entry: value, path }];\n });\n if (supplied.length > 0) {\n if (supplied.length !== 1 || supplied[0]!.entry !== field.value) {\n for (const suppliedValue of supplied) {\n report(\n \"server_owned_field_conflict\",\n suppliedValue.path,\n \"This field must match the server-owned value for this creation operation.\",\n );\n }\n }\n return;\n }\n // Prefer the requested source spelling even when another null alias exists.\n const key = Object.hasOwn(target.values, source)\n ? source\n : (aliases[0] ?? source);\n const path = [...parentPath, key];\n // Replace an omission at this source path with the authoritative proposal.\n const omission = changes.findIndex(\n (change) =>\n change.operation === \"remove\" &&\n (change.reason === \"omit_empty_property_list\" ||\n change.reason === \"omit_absent_identifier\") &&\n JSON.stringify(change.path) === JSON.stringify(path),\n );\n if (omission >= 0) changes.splice(omission, 1);\n const common = {\n reason: \"assign_server_owned_field\",\n path,\n after: field.value,\n message: `Use the server-proposed ${property} for this creation operation.`,\n };\n changes.push(\n Object.hasOwn(target.values, key)\n ? {\n ...common,\n operation: \"replace\",\n before: target.values[key] as JsonValue,\n }\n : { ...common, operation: \"add\" },\n );\n}\n\n/**\n * Prepares a creation preview against trusted server values and permission\n * outcomes. Does not determine authorization, allocate values, or persist.\n *\n * Integration boundary: https://github.com/fedify-dev/drfed/issues/152\n * The write operation constructs options from trusted server state, not client\n * JSON. It must check every local write, including nested creations, and recheck\n * permissions at commit. This preview is not an authorization token. The caller\n * also owns keeping committed IDs/timestamps consistent with the shown preview.\n * Merely referencing or embedding an actor/resource does not request a write.\n *\n * Paths identify original source locations; owned-field aliases are resolved\n * within the supported context profile. Matching singleton values are retained;\n * absent/null values receive explicit additions/replacements. Conflicts block\n * the preview. Throws TypeError for invalid trusted options/target paths.\n * @returns Original-input diagnostics and any explicit creation preview changes.\n */\nexport function prepareDocument(\n document: unknown,\n options: DocumentPreparationOptions,\n): DocumentValidationResult {\n checkPreparationOptions(options);\n const reporter = createReporter();\n const changes: NormalizationChange[] = [];\n const requested = new Set(\n options.serverOwnedFields.map(({ path }) =>\n JSON.stringify(path.slice(0, -1)),\n ),\n );\n const targets = new Map<string, PreparationTarget>();\n const unavailable: FieldPath[] = [];\n // Use only documents reached by vocabulary traversal: arbitrary extension\n // objects and unresolved IRI references must not become local write targets.\n checkDocumentValue(\n document,\n [],\n reporter,\n changes,\n (values, path, context) => {\n const key = JSON.stringify(path);\n if (requested.has(key)) targets.set(key, { values, context });\n },\n (path) => unavailable.push(path),\n );\n const structural = reporter.result();\n const checkedFields = checkServerOwnedFields(\n document,\n options.serverOwnedFields,\n targets,\n unavailable,\n structural.diagnostics.some(\n ({ reason }) => reason === \"diagnostic_limit_reached\",\n ),\n );\n for (const outcome of options.authority) {\n if (!outcome.allowed) {\n reporter.report(\n \"unauthorized_local_identity\",\n [...outcome.path],\n \"The server denied use of this local identity for the requested operation.\",\n );\n }\n }\n let result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return result;\n }\n for (const { field, target, property } of checkedFields) {\n proposeServerField(field, target, property, reporter.report, changes);\n }\n result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\") ||\n changes.length === 0\n ) {\n return result;\n }\n // Warnings describe the final server-owned replacement, not an omission.\n const replacedPaths = new Set(\n changes\n .filter((change) => change.operation === \"replace\")\n .map(({ path }) => JSON.stringify(path)),\n );\n const preview = createPreview(\n document as { [key: string]: JsonValue },\n changes,\n );\n const checked = validateDocument(preview);\n // Trusted values can still be inapplicable to the target's vocabulary type.\n // Retain original warnings (e.g. empty arrays) without duplicating them.\n reportPreviewDiagnostics(result, checked, reporter.report);\n result = reporter.result();\n if (\n !checked.complete ||\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return { ...result, complete: checked.complete && result.complete };\n }\n return {\n ...result,\n diagnostics: result.diagnostics.map((diagnostic) =>\n (diagnostic.reason === \"empty_property_list\" ||\n diagnostic.reason === \"absent_identifier\") &&\n replacedPaths.has(JSON.stringify(diagnostic.path))\n ? {\n ...diagnostic,\n message:\n \"This absent value is replaced by the trusted server-owned value in the preview.\",\n }\n : diagnostic,\n ),\n changes,\n normalizedDocument: preview,\n };\n}\n\n/** The vocabulary category of a described document. */\nexport type DocumentNodeKind =\n | \"activity\"\n | \"actor\"\n | \"collection\"\n | \"link\"\n | \"object\";\n\n/** One document reached by vocabulary traversal, as the checker read it. */\nexport interface DocumentNode {\n /** Source path of the document; `[]` is the root. */\n readonly path: FieldPath;\n /**\n * The standard name of the property that embeds the document, whatever\n * its source spelling; absent for the root.\n */\n readonly property?: string;\n /** The ActivityStreams type IRI, such as `…/activitystreams#Note`. */\n readonly type: string;\n readonly kind: DocumentNodeKind;\n /**\n * Standard property names, including `id` and `type`, mapped to the source\n * keys that supply them, in source key order. Custom extension keys are\n * not listed.\n */\n readonly properties: ReadonlyMap<string, readonly string[]>;\n /**\n * String IRI references held by this document's own reference properties\n * (`id`, `actor`, `object`, addressing, `href`, and so on), with compact\n * IRIs expanded through the context's prefixes. Values inside embedded\n * documents belong to those documents' nodes.\n */\n readonly identifiers: readonly DocumentIdentifier[];\n}\n\n/** One IRI reference as written and as the context resolves it. */\nexport interface DocumentIdentifier {\n /** The standard property name, such as `actor` or `to`. */\n readonly property: string;\n /** Source path of the value, including its list index if any. */\n readonly path: FieldPath;\n /** The value as written. */\n readonly value: string;\n /** The value with a compact IRI prefix expanded. */\n readonly iri: string;\n}\n\nconst identifierProperties: ReadonlySet<string> = new Set([\n \"id\",\n \"actor\",\n \"object\",\n \"target\",\n \"origin\",\n \"result\",\n \"instrument\",\n \"attributedTo\",\n \"location\",\n \"preview\",\n ...addressingProperties,\n \"items\",\n \"orderedItems\",\n \"current\",\n \"first\",\n \"last\",\n \"partOf\",\n \"next\",\n \"prev\",\n \"inbox\",\n \"outbox\",\n \"following\",\n \"followers\",\n \"liked\",\n \"href\",\n]);\n\n// IRI values expand compact IRIs through prefixes only; JSON-LD applies terms\n// to property names and types, not to node identifiers.\nfunction expandIdentifier(value: string, context: DocumentContext): string {\n const colon = value.indexOf(\":\");\n if (colon <= 0 || value.startsWith(\"//\", colon + 1)) return value;\n const prefix = context.terms.get(value.slice(0, colon));\n // Like resolveTerm(), only terms flagged as prefixes expand compact IRIs.\n if (prefix?.prefix !== true || prefix.iri.startsWith(\"@\")) return value;\n return prefix.iri + value.slice(colon + 1);\n}\n\nfunction nodeKind(Type: VocabularyType): DocumentNodeKind {\n if (isTypeOrSubtype(Type, Link)) return \"link\";\n if (isTypeOrSubtype(Type, Activity)) return \"activity\";\n if (actorTypes.some((Actor) => isTypeOrSubtype(Type, Actor))) return \"actor\";\n if (isTypeOrSubtype(Type, Collection)) return \"collection\";\n return \"object\";\n}\n\n/**\n * Describes the vocabulary documents the checker reads, so that write paths\n * interpret aliases, full-IRI keys, and keyword aliases exactly as\n * validation did, instead of matching literal key spellings. Opaque\n * extension values are not descended into.\n * @returns The root and every embedded document in traversal order, or\n * `null` unless validation completes without errors.\n */\nexport function describeDocument(\n document: unknown,\n): readonly DocumentNode[] | null {\n const reporter = createReporter();\n const visited: {\n readonly values: Record<string, unknown>;\n readonly path: FieldPath;\n readonly context: DocumentContext;\n readonly Type: VocabularyType;\n readonly fields: readonly SourceProperty[];\n }[] = [];\n checkDocumentValue(\n document,\n [],\n reporter,\n [],\n (values, path, context, Type, fields) => {\n visited.push({ values, path, context, Type, fields });\n },\n );\n const result = reporter.result();\n if (\n !result.complete ||\n result.diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return null;\n }\n // Read values only now: validation has rejected sparse arrays, accessors,\n // and other non-JSON shapes without evaluating them.\n const nodes = visited.map(\n ({ values, path, context, Type, fields }): DocumentNode => {\n const properties = new Map<string, string[]>();\n const identifiers: DocumentIdentifier[] = [];\n for (const { source, name, compatible } of fields) {\n if (name == null || !compatible) continue;\n const sources = properties.get(name) ?? [];\n sources.push(source);\n properties.set(name, sources);\n if (!identifierProperties.has(name)) continue;\n const value = values[source];\n const entries: [unknown, FieldPath][] = Array.isArray(value)\n ? value.map((entry, index) => [entry, [...path, source, index]])\n : [[value, [...path, source]]];\n for (const [entry, entryPath] of entries) {\n if (typeof entry !== \"string\") continue;\n identifiers.push({\n property: name,\n path: entryPath,\n value: entry,\n iri: expandIdentifier(entry, context),\n });\n }\n }\n return {\n path,\n type: Type.typeId.href,\n kind: nodeKind(Type),\n properties,\n identifiers,\n };\n },\n );\n const byPath = new Map(\n nodes.map((node) => [JSON.stringify(node.path), node]),\n );\n return nodes.map((node) => {\n if (node.path.length === 0) return node;\n // An embedded document sits at [...parent, key] or [...parent, key, index].\n for (const length of [node.path.length - 1, node.path.length - 2]) {\n const parent = byPath.get(JSON.stringify(node.path.slice(0, length)));\n const key = node.path[length];\n if (parent == null || typeof key !== \"string\") continue;\n for (const [name, sources] of parent.properties) {\n if (sources.includes(key)) return { ...node, property: name };\n }\n }\n return node;\n });\n}\n"],"mappings":";;;;;AAgFA,MAAa,oBAAoB;CAC/B,uBAAuB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACnE,gBAAgB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC5D,qBAAqB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACjE,aAAa;EAAE,UAAU;EAAc,UAAU;CAAQ;CACzD,kBAAkB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC9D,sBAAsB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAClE,yBAAyB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACrE,iBAAiB;EAAE,UAAU;EAAc,UAAU;CAAQ;CAC7D,6BAA6B;EAAE,UAAU;EAAa,UAAU;CAAQ;CACxE,6BAA6B;EAAE,UAAU;EAAa,UAAU;CAAQ;CACxE,6BAA6B;EAAE,UAAU;EAAW,UAAU;CAAQ;CACtE,0BAA0B;EAAE,UAAU;EAAW,UAAU;CAAQ;CACnE,kBAAkB;EAAE,UAAU;EAAW,UAAU;CAAQ;CAC3D,sBAAsB;EAAE,UAAU;EAAW,UAAU;CAAQ;CAC/D,wBAAwB;EAAE,UAAU;EAAW,UAAU;CAAQ;CACjE,2BAA2B;EA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,UAAU;IAC/B,YAAY,KAAK;KACf,UAAU;KACV,MAAM;KACN,OAAO;KACP,KAAK,iBAAiB,OAAO,OAAO;IACtC,CAAC;GACH;EACF;EACA,OAAO;GACL;GACA,MAAM,KAAK,OAAO;GAClB,MAAM,SAAS,IAAI;GACnB;GACA;EACF;CACF,CACF;CACA,MAAM,SAAS,IAAI,IACjB,MAAM,KAAK,SAAS,CAAC,KAAK,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC,CACvD;CACA,OAAO,MAAM,KAAK,SAAS;EACzB,IAAI,KAAK,KAAK,WAAW,GAAG,OAAO;EAEnC,KAAK,MAAM,UAAU,CAAC,KAAK,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,CAAC,GAAG;GACjE,MAAM,SAAS,OAAO,IAAI,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC;GACpE,MAAM,MAAM,KAAK,KAAK;GACtB,IAAI,UAAU,QAAQ,OAAO,QAAQ,UAAU;GAC/C,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,YACnC,IAAI,QAAQ,SAAS,GAAG,GAAG,OAAO;IAAE,GAAG;IAAM,UAAU;GAAK;EAEhE;EACA,OAAO;CACT,CAAC;AACH"}
package/dist/index.d.mts CHANGED
@@ -3,7 +3,7 @@ import { AddressedActor, InboundDeliveryEntry, OutboundDeliveryEntry, OutboundSe
3
3
  import { normalizeEmail } from "./email.mjs";
4
4
  import { MigrateCredentials, MigrateOptions, PGliteMigrateCredentials, PostgresMigrateCredentials, migrate } from "./migrate.mjs";
5
5
  import { LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, consumeLoginChallenge, findLoginChallenge } from "./login.mjs";
6
- import { AddressingInput, PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, ensureResource, lockActorCollection, lockResources, promoteResource, storeAddressing } from "./resource.mjs";
6
+ import { AddressingInput, AddressingOccurrence, PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, checkAddressingOccurrences, ensureResource, lockActorCollection, lockResources, promoteResource, replaceAddressing, storeAddressing, storeAddressingOccurrences } from "./resource.mjs";
7
7
  import { ensureRemoteInstance } from "./instance.mjs";
8
8
  import { storableText } from "./text.mjs";
9
9
  import { MigrationIdentity, MigrationManifest, MigrationManifestPaths, assertMigrationManifestPrefix, migrationTimestamp, parseMigrationManifest, verifyMigrationManifest } from "./migration-manifest.mjs";
@@ -11,5 +11,5 @@ import { InspectMigrationStateOptions, MigrationHistoryFormat, MigrationQueryCli
11
11
  import { a as preparePostgresDatabase, i as migrationLockKey, n as PostgresPreparationCredentials, o as MigrationPreparationCode, r as PreparePostgresOptions, s as MigrationPreparationError, t as MigrationClientFactory } from "./migration-session-B4xHeU_a.mjs";
12
12
  import { PersistentPgliteStore, PgliteStoreCode, PgliteStoreError, openPersistentPglite } from "./pglite-store.mjs";
13
13
  import { PreparePgliteOptions, preparePgliteDatabase } from "./pglite-preparation.mjs";
14
- import { a as StoredResourceRevision, c as loadCurrentResourceRevision, d as ResourceRevisionStateError, f as LegacyResourceRevisionError, i as RevisionRelationInput, l as loadResourceRevision, n as JsonObject, o as appendResourceRevision, p as RevisionConflictError, r as JsonValue, s as listResourceRevisions, t as AppendResourceRevisionInput, u as captureLegacyResourceRevision } from "./resource-revision-BuG5kUlA.mjs";
15
- export { AddressedActor, AddressingInput, AppendResourceRevisionInput, Database, InboundDeliveryEntry, InspectMigrationStateOptions, JsonObject, JsonValue, LegacyResourceRevisionError, LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, MigrateCredentials, MigrateOptions, MigrationClientFactory, MigrationHistoryFormat, MigrationIdentity, MigrationManifest, MigrationManifestPaths, type MigrationPreparationCode, MigrationPreparationError, MigrationQueryClient, MigrationState, MigrationStatus, OutboundDeliveryEntry, OutboundSettlement, PGliteMigrateCredentials, PUBLIC_IRI, PUBLIC_RESOURCE_ID, PersistentPgliteStore, PgliteStoreCode, PgliteStoreError, PostgresMigrateCredentials, PostgresPreparationCredentials, PreparePgliteOptions, PreparePostgresOptions, PublicJwk, RelationsFilter, ResourceKindConflictError, ResourceRevisionStateError, RevisionConflictError, RevisionRelationInput, StoredResourceRevision, Transaction, addActorCollectionItem, appendResourceRevision, assertMigrationManifestPrefix, captureLegacyResourceRevision, classifyMigrationHistory, consumeLoginChallenge, ensureRemoteInstance, ensureResource, findLoginChallenge, inboundActorRows, inspectMigrationState, jwkThumbprint, linkInboundActivity, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision, lockActorCollection, lockResources, migrate, migrationLockKey, migrationTimestamp, normalizeEmail, observeKeyVersion, openPersistentPglite, parseMigrationManifest, preparePgliteDatabase, preparePostgresDatabase, promoteResource, receiveInbound, recordFetchedObject, recordInbound, recordOutbound, relations, schema_d_exports as schema, settleOutbound, storableText, storeAddressing, thumbprintInput, toPublicJwk, verifyMigrationManifest };
14
+ import { a as StoredResourceRevision, c as appendResourceRevision, d as loadResourceRevision, f as writeTypedResourceRevision, g as RevisionConflictError, h as LegacyResourceRevisionError, i as RevisionRelationInput, l as listResourceRevisions, m as ResourceRevisionStateError, n as JsonObject, o as TypedObjectColumns, p as captureLegacyResourceRevision, r as JsonValue, s as TypedResourceRevisionInput, t as AppendResourceRevisionInput, u as loadCurrentResourceRevision } from "./resource-revision-BauDwFIn.mjs";
15
+ export { AddressedActor, AddressingInput, AddressingOccurrence, AppendResourceRevisionInput, Database, InboundDeliveryEntry, InspectMigrationStateOptions, JsonObject, JsonValue, LegacyResourceRevisionError, LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, MigrateCredentials, MigrateOptions, MigrationClientFactory, MigrationHistoryFormat, MigrationIdentity, MigrationManifest, MigrationManifestPaths, type MigrationPreparationCode, MigrationPreparationError, MigrationQueryClient, MigrationState, MigrationStatus, OutboundDeliveryEntry, OutboundSettlement, PGliteMigrateCredentials, PUBLIC_IRI, PUBLIC_RESOURCE_ID, PersistentPgliteStore, PgliteStoreCode, PgliteStoreError, PostgresMigrateCredentials, PostgresPreparationCredentials, PreparePgliteOptions, PreparePostgresOptions, PublicJwk, RelationsFilter, ResourceKindConflictError, ResourceRevisionStateError, RevisionConflictError, RevisionRelationInput, StoredResourceRevision, Transaction, TypedObjectColumns, TypedResourceRevisionInput, addActorCollectionItem, appendResourceRevision, assertMigrationManifestPrefix, captureLegacyResourceRevision, checkAddressingOccurrences, classifyMigrationHistory, consumeLoginChallenge, ensureRemoteInstance, ensureResource, findLoginChallenge, inboundActorRows, inspectMigrationState, jwkThumbprint, linkInboundActivity, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision, lockActorCollection, lockResources, migrate, migrationLockKey, migrationTimestamp, normalizeEmail, observeKeyVersion, openPersistentPglite, parseMigrationManifest, preparePgliteDatabase, preparePostgresDatabase, promoteResource, receiveInbound, recordFetchedObject, recordInbound, recordOutbound, relations, replaceAddressing, schema_d_exports as schema, settleOutbound, storableText, storeAddressing, storeAddressingOccurrences, thumbprintInput, toPublicJwk, verifyMigrationManifest, writeTypedResourceRevision };
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import relations from "./relations.mjs";
4
4
  import "./db.mjs";
5
5
  import { migrate } from "./migrate.mjs";
6
6
  import { LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, consumeLoginChallenge, findLoginChallenge } from "./login.mjs";
7
- import { PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, ensureResource, lockActorCollection, lockResources, promoteResource, storeAddressing } from "./resource.mjs";
7
+ import { PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, checkAddressingOccurrences, ensureResource, lockActorCollection, lockResources, promoteResource, replaceAddressing, storeAddressing, storeAddressingOccurrences } from "./resource.mjs";
8
8
  import { jwkThumbprint, observeKeyVersion, thumbprintInput, toPublicJwk } from "./key.mjs";
9
9
  import { storableText } from "./text.mjs";
10
10
  import { inboundActorRows, linkInboundActivity, receiveInbound, recordFetchedObject, recordInbound, recordOutbound, settleOutbound } from "./activity-delivery.mjs";
@@ -15,5 +15,5 @@ import { n as MigrationPreparationError } from "./migration-snapshot-OM5jQN1-.mj
15
15
  import { migrationLockKey, preparePostgresDatabase } from "./migration-session.mjs";
16
16
  import { PgliteStoreError, openPersistentPglite } from "./pglite-store.mjs";
17
17
  import { preparePgliteDatabase } from "./pglite-preparation.mjs";
18
- import { a as captureLegacyResourceRevision, c as LegacyResourceRevisionError, i as loadResourceRevision, n as listResourceRevisions, o as RevisionConflictError, r as loadCurrentResourceRevision, s as ResourceRevisionStateError, t as appendResourceRevision } from "./resource-revision-DWg6et77.mjs";
19
- export { LegacyResourceRevisionError, LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, MigrationPreparationError, PUBLIC_IRI, PUBLIC_RESOURCE_ID, PgliteStoreError, ResourceKindConflictError, ResourceRevisionStateError, RevisionConflictError, addActorCollectionItem, appendResourceRevision, assertMigrationManifestPrefix, captureLegacyResourceRevision, classifyMigrationHistory, consumeLoginChallenge, ensureRemoteInstance, ensureResource, findLoginChallenge, inboundActorRows, inspectMigrationState, jwkThumbprint, linkInboundActivity, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision, lockActorCollection, lockResources, migrate, migrationLockKey, migrationTimestamp, normalizeEmail, observeKeyVersion, openPersistentPglite, parseMigrationManifest, preparePgliteDatabase, preparePostgresDatabase, promoteResource, receiveInbound, recordFetchedObject, recordInbound, recordOutbound, relations, schema_exports as schema, settleOutbound, storableText, storeAddressing, thumbprintInput, toPublicJwk, verifyMigrationManifest };
18
+ import { a as writeTypedResourceRevision, c as ResourceRevisionStateError, i as loadResourceRevision, l as LegacyResourceRevisionError, n as listResourceRevisions, o as captureLegacyResourceRevision, r as loadCurrentResourceRevision, s as RevisionConflictError, t as appendResourceRevision } from "./resource-revision-iQ8HZ699.mjs";
19
+ export { LegacyResourceRevisionError, LoginChallengeConsumptionError, LoginChallengeError, LoginChallengeNotFoundError, MigrationPreparationError, PUBLIC_IRI, PUBLIC_RESOURCE_ID, PgliteStoreError, ResourceKindConflictError, ResourceRevisionStateError, RevisionConflictError, addActorCollectionItem, appendResourceRevision, assertMigrationManifestPrefix, captureLegacyResourceRevision, checkAddressingOccurrences, classifyMigrationHistory, consumeLoginChallenge, ensureRemoteInstance, ensureResource, findLoginChallenge, inboundActorRows, inspectMigrationState, jwkThumbprint, linkInboundActivity, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision, lockActorCollection, lockResources, migrate, migrationLockKey, migrationTimestamp, normalizeEmail, observeKeyVersion, openPersistentPglite, parseMigrationManifest, preparePgliteDatabase, preparePostgresDatabase, promoteResource, receiveInbound, recordFetchedObject, recordInbound, recordOutbound, relations, replaceAddressing, schema_exports as schema, settleOutbound, storableText, storeAddressing, storeAddressingOccurrences, thumbprintInput, toPublicJwk, verifyMigrationManifest, writeTypedResourceRevision };