@drfed/models 0.2.0-dev.712 → 0.2.0-dev.716

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.
Files changed (37) hide show
  1. package/dist/activity-delivery.d.mts +1 -1
  2. package/dist/{db-BBw4F4HU.d.mts → db-CcbUSnp2.d.mts} +84 -3
  3. package/dist/{db-BBw4F4HU.d.mts.map → db-CcbUSnp2.d.mts.map} +1 -1
  4. package/dist/db.d.mts +1 -1
  5. package/dist/document.d.mts +10 -0
  6. package/dist/document.d.mts.map +1 -1
  7. package/dist/document.mjs +6 -1
  8. package/dist/document.mjs.map +1 -1
  9. package/dist/index.d.mts +4 -4
  10. package/dist/index.mjs +3 -3
  11. package/dist/instance.d.mts +1 -1
  12. package/dist/key.d.mts +1 -1
  13. package/dist/login.d.mts +8 -2
  14. package/dist/login.d.mts.map +1 -1
  15. package/dist/login.mjs +8 -1
  16. package/dist/login.mjs.map +1 -1
  17. package/dist/migrations-manifest.json +8 -0
  18. package/dist/relations.d.mts +1 -1
  19. package/dist/relations.mjs +19 -2
  20. package/dist/relations.mjs.map +1 -1
  21. package/dist/{resource-revision-iQ8HZ699.mjs → resource-revision-bTQyJ7aw.mjs} +28 -3
  22. package/dist/resource-revision-bTQyJ7aw.mjs.map +1 -0
  23. package/dist/{resource-revision-BauDwFIn.d.mts → resource-revision-rDmHhNCj.d.mts} +19 -3
  24. package/dist/resource-revision-rDmHhNCj.d.mts.map +1 -0
  25. package/dist/resource-revision.d.mts +2 -2
  26. package/dist/resource-revision.mjs +1 -1
  27. package/dist/resource.d.mts +1 -1
  28. package/dist/schema.d.mts +2 -2
  29. package/dist/schema.mjs +27 -1
  30. package/dist/schema.mjs.map +1 -1
  31. package/drizzle/20261113080536_revision_embeddings/migration.sql +14 -0
  32. package/drizzle/20261113080536_revision_embeddings/snapshot.json +4634 -0
  33. package/drizzle/20261113080537_guard_revision_embeddings/migration.sql +42 -0
  34. package/drizzle/20261113080537_guard_revision_embeddings/snapshot.json +4634 -0
  35. package/package.json +6 -6
  36. package/dist/resource-revision-BauDwFIn.d.mts.map +0 -1
  37. package/dist/resource-revision-iQ8HZ699.mjs.map +0 -1
@@ -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 DIAGNOSTIC_REASONS = {\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 DIAGNOSTIC_REASONS;\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 ACTIVITY_STREAMS_CONTEXT = \"https://www.w3.org/ns/activitystreams\";\nconst MAXIMUM_DIAGNOSTICS = 100;\nconst MAXIMUM_PATH_DEPTH = 64;\nconst ACTOR_TYPES = [Application, Group, Organization, Person, Service];\n/** The ActivityStreams properties that address a document's recipients. */\nexport const ADDRESSING_PROPERTIES = [\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 OBJECT_ONLY_PROPERTIES: 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 IMPLEMENTED_TYPES: 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// Objects with these keywords are values or lists, not JSON-LD node objects.\nconst VALUE_OBJECT_KEYWORDS: ReadonlySet<string> = new Set([\n \"@value\",\n \"@list\",\n \"@set\",\n]);\n\nconst IDENTIFIER_PROPERTIES: 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 ...ADDRESSING_PROPERTIES,\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// A node object has one of each.\nconst FUNCTIONAL_REFERENCES = [\"id\", \"href\"] as const;\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 === MAXIMUM_DIAGNOSTICS) {\n complete = false;\n truncated = true;\n diagnostics[MAXIMUM_DIAGNOSTICS - 1] = {\n reason: \"diagnostic_limit_reached\",\n ...DIAGNOSTIC_REASONS.diagnostic_limit_reached,\n path: [],\n message: \"Further diagnostics were omitted.\",\n };\n return;\n }\n const classification = DIAGNOSTIC_REASONS[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 // A blank node identifier is no IRI, whatever term \"_\" names.\n if (colon < 0 || value.startsWith(\"_:\")) 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 [\n ACTIVITY_STREAMS_CONTEXT,\n \"https://w3id.org/security/v1\",\n ]) {\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(ACTIVITY_STREAMS_CONTEXT)!;\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 ? ACTIVITY_STREAMS_CONTEXT\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 || !IMPLEMENTED_TYPES.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 ACTOR_TYPES;\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 = ACTOR_TYPES.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 = ACTOR_TYPES.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// The keyword a key stands for: itself, or the keyword a term aliases. A\n// context the checker does not read aliases nothing it knows of.\nfunction keywordOf(\n key: string,\n context: DocumentContext | null | undefined,\n): string | undefined {\n if (key.startsWith(\"@\")) return key;\n const iri = context?.terms.get(key)?.iri;\n return iri?.startsWith(\"@\") === true ? iri : undefined;\n}\n\nfunction isNodeObject(\n values: Record<string, unknown>,\n context: DocumentContext | null,\n): boolean {\n return !Object.keys(values).some((key) =>\n VALUE_OBJECT_KEYWORDS.has(keywordOf(key, context) ?? \"\"),\n );\n}\n\n// The context an extension object is described with as a node object: none\n// for a value or a list, or null for one with properties as well, or for a\n// value that is an object but no JSON literal, which are no valid JSON-LD\n// and cannot be read.\nfunction nodeContext(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n if (context === undefined || isNodeObject(values, context)) return context;\n return Object.keys(values).some((key) => {\n const keyword = keywordOf(key, context);\n const value = values[key];\n // A value is a scalar unless it is a JSON literal.\n return (\n keyword == null ||\n (keyword === \"@value\" &&\n value !== null &&\n typeof value === \"object\" &&\n !isJsonLiteral(values, context))\n );\n })\n ? null\n : undefined;\n}\n\n// Whether a value object holds a JSON literal, however its keywords are\n// spelled.\nfunction isJsonLiteral(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): boolean {\n return Object.keys(values).some((key) => {\n if (keywordOf(key, context) !== \"@type\") return false;\n const type = values[key];\n // Read a list entry without evaluating an accessor.\n return (\n type === \"@json\" ||\n (Array.isArray(type) &&\n type.length === 1 &&\n Object.getOwnPropertyDescriptor(type, 0)?.value === \"@json\")\n );\n });\n}\n\n// The context a value of an extension object is described with: none for a\n// context definition, for the value of a value object, which is a scalar or\n// a JSON literal, or for a language map, none of which holds node objects.\n// A key with a @language container holds a language map only as an object.\nfunction extensionChildContext(\n key: string,\n value: unknown,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n return key === \"@context\" ||\n keywordOf(key, context) === \"@value\" ||\n (context?.terms.get(key)?.container === \"@language\" && isLanguageMap(value))\n ? undefined\n : context;\n}\n\nfunction isLanguageMap(value: unknown): boolean {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// Check the keywords of an extension object, and tell whether it holds a\n// JSON literal, however its keywords are spelled.\nfunction checkJsonLiteral(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n context: DocumentContext | null | undefined,\n): boolean {\n const literal = checkExtensionKeywords(values, path, report);\n return literal || isJsonLiteral(values, context);\n}\n\n// The context an extension object is read with: none when it is not\n// described, or null within a context of its own, which is not read.\nfunction extensionContext(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n return context !== undefined && Object.hasOwn(values, \"@context\")\n ? null\n : context;\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)\n ? OBJECT_ONLY_PROPERTIES\n : new Set<string>();\n}\n\nfunction checkPathDepth(path: FieldPath, report: Report): boolean {\n if (path.length <= MAXIMUM_PATH_DEPTH) return true;\n report(\n \"processing_limit_exceeded\",\n path,\n `Nesting exceeds the supported limit of ${MAXIMUM_PATH_DEPTH} 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 onExtensionNode?: (\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext | null,\n ) => void,\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 // Given the context it inherits, report each node object outside JSON\n // literals with that context, or with null within a context of its own.\n function checkExtension(\n value: unknown,\n path: FieldPath,\n keywords = true,\n context?: DocumentContext | null,\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(() =>\n checkExtension(entry, entryPath, keywords, context),\n );\n });\n } else {\n const values = readDocument(value, path, report);\n if (values != null) {\n const own = extensionContext(values, context);\n const jsonLiteral =\n keywords && checkJsonLiteral(values, path, report, own);\n const node = nodeContext(values, own);\n if (keywords && node !== undefined) {\n onExtensionNode?.(values, path, node);\n }\n for (const key of Object.keys(values)) {\n const childKeywords = keywords && !(jsonLiteral && key === \"@value\");\n children.push(() =>\n checkExtension(\n values[key],\n [...path, key],\n childKeywords,\n extensionChildContext(key, values[key], own),\n ),\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 ...ADDRESSING_PROPERTIES,\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(\n value,\n fieldPath,\n true,\n extensionChildContext(source, value, context),\n );\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 * The JSON-LD node objects inside this document's own opaque extension\n * values, at any depth, in traversal order.\n */\n readonly extensions: readonly ExtensionNode[];\n}\n\n/**\n * A JSON-LD node object inside an opaque extension value. The checker does\n * not read it as a vocabulary document, but a JSON-LD processor reads its\n * keys with the context it inherits, so its standard properties are named\n * as a described document's are, whatever their type coercion.\n */\nexport interface ExtensionNode {\n /** Source path of the node object. */\n readonly path: FieldPath;\n /**\n * The standard name of the property that holds the node object in another\n * one, whatever its source spelling; absent directly under an extension\n * property.\n */\n readonly property?: string;\n /** The path of the node object whose `property` holds this one. */\n readonly parent?: FieldPath;\n /**\n * Whether the checker cannot read all of the node object: it, or one\n * around it in the extension value, has a `@context` of its own, which the\n * checker does not read, or a reference property holds something other\n * than absolute IRIs, a blank node identifier as its `id`, and node\n * objects, such as a value object, a language map, a string the\n * property's alias does not coerce to an IRI, a relative reference or a\n * blank node identifier, or it has more than one `id` or `href`, or a node\n * object as one, or it nests properties with `@nest` or reverses them with\n * `@reverse`, or its `id` is used elsewhere in the document, as the `id` of\n * another node object or a reference outside its own properties, so that\n * it is not read apart; a `Link` whose `href` is its own `id` is read. An\n * uninterpreted node object has no properties, identifiers or types when\n * its context is unread.\n */\n readonly uninterpreted: boolean;\n /**\n * Standard property names mapped to the source keys that supply them,\n * matched by IRI whatever their type coercion or container.\n */\n readonly properties: ReadonlyMap<string, readonly string[]>;\n /**\n * String IRI references held by the node object's own standard\n * properties, through arrays and `@set` or `@list` objects, with compact\n * IRIs expanded through the context's prefixes.\n */\n readonly identifiers: readonly DocumentIdentifier[];\n /** The type IRIs, with terms and compact IRIs expanded. */\n readonly types: readonly string[];\n /**\n * The vocabulary category of its types the checker knows: `link` if one\n * is a link type, or else that of the first.\n */\n readonly kind?: DocumentNodeKind;\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\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 // A blank node identifier is no compact IRI, whatever prefix \"_\" names.\n if (\n colon <= 0 ||\n value.startsWith(\"//\", colon + 1) ||\n value.startsWith(\"_:\")\n ) {\n return value;\n }\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 (ACTOR_TYPES.some((Actor) => isTypeOrSubtype(Type, Actor))) return \"actor\";\n if (isTypeOrSubtype(Type, Collection)) return \"collection\";\n return \"object\";\n}\n\n// Name the standard properties of a document or node object, and the IRI\n// references they hold, as read with the context it is interpreted with.\nfunction describeProperties(\n values: Record<string, unknown>,\n path: FieldPath,\n fields: readonly SourceProperty[],\n context: DocumentContext,\n): Pick<DocumentNode, \"properties\" | \"identifiers\"> {\n const properties = new Map<string, string[]>();\n const identifiers: DocumentIdentifier[] = [];\n for (const { source, name } of fields) {\n if (name == null) continue;\n const sources = properties.get(name) ?? [];\n sources.push(source);\n properties.set(name, sources);\n if (!IDENTIFIER_PROPERTIES.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 { properties, identifiers };\n}\n\n// The standard name of an extension node object's key, matched by IRI\n// whatever its container, as a JSON-LD processor reads it, and whether its\n// strings are coerced as the standard property's are.\nfunction extensionProperty(\n source: string,\n context: DocumentContext,\n): { readonly name: string; readonly compatible: boolean } | undefined {\n const { name, iri, compatible } = resolveProperty(source, context);\n if (name != null) return { name, compatible };\n if (iri == null) return undefined;\n const type = context.terms.get(source)?.type;\n for (const [standard, term] of getContextTables().standardTerms) {\n if (term.iri === iri) {\n return { name: standard, compatible: term.type === type };\n }\n }\n return undefined;\n}\n\n// References must be absolute IRIs, or blank node identifiers, which name\n// no resource; relative ones need a base-IRI policy.\nconst isReadableReference = (value: string): boolean =>\n value.startsWith(\"_:\") ||\n (/^[a-z][a-z\\d+.-]*:/iu.test(value) && URL.canParse(value));\n\nfunction typeKind(iri: string): DocumentNodeKind | undefined {\n const Type =\n iri === Link.typeId.href\n ? Link\n : iri === Mention.typeId.href\n ? Mention\n : getEntityTypeById(iri);\n return Type == null ? undefined : nodeKind(Type);\n}\n\n// The entries of a value, through arrays and @set or @list objects. One\n// with a @context of its own is an entry itself, as its values are unread.\nfunction valueEntries(\n value: unknown,\n path: FieldPath,\n context: DocumentContext,\n): [unknown, FieldPath][] {\n if (Array.isArray(value)) {\n return value.flatMap((entry, index) =>\n valueEntries(entry, [...path, index], context),\n );\n }\n if (value !== null && typeof value === \"object\") {\n const values = value as Record<string, unknown>;\n if (Object.hasOwn(values, \"@context\")) return [[value, path]];\n const wrapper = Object.keys(values).find((key) => {\n const keyword = keywordOf(key, context);\n return keyword === \"@set\" || keyword === \"@list\";\n });\n if (wrapper != null) {\n return valueEntries(values[wrapper], [...path, wrapper], context);\n }\n }\n return [[value, path]];\n}\n\n// What a node object in an extension value holds, as read so far.\ninterface ExtensionReading {\n readonly identifiers: DocumentIdentifier[];\n readonly types: string[];\n readonly children: [FieldPath, string][];\n}\n\n// Read one entry of a standard property of a node object in an extension\n// value, and tell false when it is what the checker cannot read as a\n// reference.\nfunction readExtensionEntry(\n entry: unknown,\n path: FieldPath,\n property: { readonly name: string; readonly compatible: boolean },\n context: DocumentContext,\n reading: ExtensionReading,\n): boolean {\n const { name, compatible } = property;\n const reference = IDENTIFIER_PROPERTIES.has(name);\n if (typeof entry === \"string\") {\n if (name === \"type\") {\n reading.types.push(\n context.terms.get(entry)?.iri ?? expandIdentifier(entry, context),\n );\n return true;\n }\n if (!reference) return true;\n const iri = expandIdentifier(entry, context);\n // A literal or a relative reference names no resource the checker can\n // tell, nor does a blank node but as an id: elsewhere, it may name a\n // node object defined apart from the one that refers to it.\n if (!compatible || !isReadableReference(iri)) return false;\n // It is still listed, so that identity checks follow it.\n reading.identifiers.push({ property: name, path, value: entry, iri });\n return !iri.startsWith(\"_:\") || name === \"id\";\n }\n // Null stands for no value.\n if (entry === null) return true;\n if (typeof entry !== \"object\") return !reference;\n if (isNodeObject(entry as Record<string, unknown>, context)) {\n reading.children.push([path, name]);\n return true;\n }\n return !reference;\n}\n\n// Tell whether an id or href has more than one value, or a node object.\nfunction hasAmbiguousReference(reading: ExtensionReading): boolean {\n return FUNCTIONAL_REFERENCES.some(\n (name) =>\n reading.identifiers.filter(({ property }) => property === name).length >\n 1 || reading.children.some(([, property]) => property === name),\n );\n}\n\n// Describe a node object in an extension value, with the node objects its\n// standard properties hold and the names of those properties.\nfunction describeExtensionNode(\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext | null,\n): {\n readonly node: ExtensionNode;\n readonly children: readonly (readonly [FieldPath, string])[];\n} {\n if (context == null) {\n return {\n node: {\n path,\n uninterpreted: true,\n properties: new Map(),\n identifiers: [],\n types: [],\n },\n children: [],\n };\n }\n const properties = new Map<string, string[]>();\n const reading: ExtensionReading = {\n identifiers: [],\n types: [],\n children: [],\n };\n let readable = true;\n for (const source of Object.keys(values).sort()) {\n // Nested properties belong to the node object around them, and reverse\n // ones make other node objects the subjects; neither is read that way.\n const keyword = keywordOf(source, context);\n if (keyword === \"@nest\" || keyword === \"@reverse\") readable = false;\n const property = extensionProperty(source, context);\n if (property == null) continue;\n const { name } = property;\n properties.set(name, [...(properties.get(name) ?? []), source]);\n // A language map holds strings in languages, not references.\n if (\n context.terms.get(source)?.container === \"@language\" &&\n isLanguageMap(values[source])\n ) {\n if (IDENTIFIER_PROPERTIES.has(name) && values[source] != null) {\n readable = false;\n }\n continue;\n }\n for (const [entry, entryPath] of valueEntries(\n values[source],\n [...path, source],\n context,\n )) {\n if (!readExtensionEntry(entry, entryPath, property, context, reading)) {\n readable = false;\n }\n }\n }\n const { identifiers, types, children } = reading;\n const kinds = types.map(typeKind).filter((kind) => kind != null);\n const kind = kinds.includes(\"link\") ? \"link\" : kinds[0];\n return {\n node: {\n path,\n uninterpreted: !readable || hasAmbiguousReference(reading),\n properties,\n identifiers,\n types,\n ...(kind == null ? {} : { kind }),\n },\n children,\n };\n}\n\n// Find the objects in the language maps of a document's or a node object's\n// keys, which hold strings in languages: an object there is no valid\n// JSON-LD, and is not read.\nfunction languageMapObjects(\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext,\n): FieldPath[] {\n return Object.keys(values).flatMap((source) => {\n if (context.terms.get(source)?.container !== \"@language\") return [];\n const map = values[source];\n if (!isLanguageMap(map)) return [];\n return Object.entries(map as Record<string, unknown>).flatMap(\n ([language, entry]) => {\n const entries: [unknown, FieldPath][] = Array.isArray(entry)\n ? entry.map((item, index) => [\n item,\n [...path, source, language, index],\n ])\n : [[entry, [...path, source, language]]];\n return entries\n .filter(([item]) => item !== null && typeof item === \"object\")\n .map(([, itemPath]) => itemPath);\n },\n );\n });\n}\n\n// Name the property of its parent that embeds each value, which sits at\n// [...parent, key] or [...parent, key, index].\nfunction nameEmbeddingProperties<\n T extends Pick<DocumentNode, \"path\" | \"properties\" | \"property\">,\n>(nodes: readonly T[]): T[] {\n const byPath = new Map(\n nodes.map((node) => [JSON.stringify(node.path), node]),\n );\n return nodes.map((node) => {\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 if (\n length < node.path.length - 1 &&\n typeof node.path.at(-1) !== \"number\"\n ) {\n continue;\n }\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\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 read as vocabulary documents, but the JSON-LD\n * node objects in them are described as extensions of the document that\n * holds them.\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 const extensions: {\n readonly values: Record<string, unknown>;\n readonly path: FieldPath;\n readonly context: DocumentContext | null;\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 undefined,\n (values, path, context) => {\n extensions.push({ values, path, context });\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 documents = visited.map(({ values, path, context, Type, fields }) => ({\n path,\n type: Type.typeId.href,\n kind: nodeKind(Type),\n ...describeProperties(\n values,\n path,\n fields.filter(({ compatible }) => compatible),\n context,\n ),\n }));\n const described = [\n ...extensions.map(({ values, path, context }) =>\n describeExtensionNode(values, path, context),\n ),\n ...[...visited, ...extensions].flatMap(({ values, path, context }) =>\n context == null\n ? []\n : languageMapObjects(values, path, context).map((object) =>\n describeExtensionNode({}, object, null),\n ),\n ),\n ];\n const holders = new Map(\n described.flatMap(({ node, children }) =>\n children.map(([path, property]) => [\n JSON.stringify(path),\n { property, parent: node.path },\n ]),\n ),\n );\n // Node objects that share an id are one node, and one whose id another\n // value refers to says more of what that value names, so a node object\n // whose id is used elsewhere in the document is not read apart from it.\n // Its own properties, such as a Link's href naming its own id, name no\n // other node to join.\n const uses = Map.groupBy(\n [...documents, ...described.map(({ node }) => node)].flatMap(\n ({ identifiers }) => identifiers,\n ),\n ({ iri }) => iri,\n );\n const extensionNodes = described.map(({ node }): ExtensionNode => {\n const id = node.identifiers.find(({ property }) => property === \"id\");\n // Every use of its id in its own properties is among the uses; counting\n // keeps this linear in a long list of them.\n const joined =\n id != null &&\n (uses.get(id.iri)?.length ?? 0) >\n node.identifiers.filter(({ iri }) => iri === id.iri).length;\n return {\n ...node,\n ...holders.get(JSON.stringify(node.path)),\n ...(joined ? { uninterpreted: true } : {}),\n };\n });\n const owners = new Map(\n visited.map(({ path }): [string, ExtensionNode[]] => [\n JSON.stringify(path),\n [],\n ]),\n );\n for (const node of extensionNodes) {\n // A node object belongs to the closest document around it.\n for (let length = node.path.length - 1; length >= 0; length -= 1) {\n const owner = owners.get(JSON.stringify(node.path.slice(0, length)));\n if (owner == null) continue;\n owner.push(node);\n break;\n }\n }\n return nameEmbeddingProperties(\n documents.map(\n (node): DocumentNode => ({\n ...node,\n extensions: owners.get(JSON.stringify(node.path)) ?? [],\n }),\n ),\n );\n}\n"],"mappings":";;;;;AAgFA,MAAa,qBAAqB;CAChC,uBAAuB;EAAE,UAAU;EAAc,UAAU;CAAQ;CACnE,gBAAgB;EAAE,UAAU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AAWD,MAAM,oCAAiD,IAAI,IAAoB;CAC7E;CACAA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;AACF,CAAC;AAED,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,wBAAwB,CAAC,MAAM,MAAM;AAG3C,SAAS,iBAAiB;CACxB,MAAM,cAA4B,CAAC;CACnC,IAAI,WAAW;CACf,IAAI,YAAY;CAEhB,MAAM,UAAkB,QAAQ,MAAM,YAAY;EAChD,IAAI,WAAW;EACf,IAAI,YAAY,WAAW,qBAAqB;GAC9C,WAAW;GACX,YAAY;GACZ,YAAY,MAA2B;IACrC,QAAQ;IACR,GAAG,mBAAmB;IACtB,MAAM,CAAC;IACP,SAAS;GACX;GACA;EACF;EACA,MAAM,iBAAiB,mBAAmB;EAC1C,IAAI,eAAe,aAAa,WAAW,WAAW;EACtD,YAAY,KAAK;GAAE;GAAQ,GAAG;GAAgB;GAAM;EAAQ,CAAC;CAC/D;CAEA,OAAO;EACL;EACA,cAAc;EACd,eAAyC;GACvC;GACA;GACA,SAAS,CAAC;EACZ;CACF;AACF;AAEA,SAAS,aACP,UACA,MACA,QACqC;CACrC,IAAI,CAAC,iBAAiB,QAAQ,GAAG;EAC/B,OAAO,kBAAkB,MAAM,wBAAwB;EACvD;CACF;CACA,IACE,YAAY,QACZ,OAAO,aAAa,YACpB,MAAM,QAAQ,QAAQ,GACtB;EACA,OAAO,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,MAAM,QAAQ,gBAEjB,KAAK,IAAI,SAAS,KAAK,KAAK,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG;EAChE,MAAM,QAAQ,OAAO,IAAI,KAAK,UAAU,KAAK,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC;EACnE,IAAI,SAAS,MAAM;EACnB,MAAM,KAAK,IAAI;EACf;CACF;CAEF,OAAO,wBACL,UAAU,KACP,UAAwB;EACvB,GAAG;EACH,YAAY,OAAO,IAAI,KAAK,UAAU,KAAK,IAAI,CAAC,KAAK,CAAC;CACxD,EACF,CACF;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 DIAGNOSTIC_REASONS = {\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 source_unavailable: { 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 DIAGNOSTIC_REASONS;\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 ACTIVITY_STREAMS_CONTEXT = \"https://www.w3.org/ns/activitystreams\";\nconst MAXIMUM_DIAGNOSTICS = 100;\nconst MAXIMUM_PATH_DEPTH = 64;\nconst ACTOR_TYPES = [Application, Group, Organization, Person, Service];\n/** The ActivityStreams properties that address a document's recipients. */\nexport const ADDRESSING_PROPERTIES = [\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 OBJECT_ONLY_PROPERTIES: 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 IMPLEMENTED_TYPES: 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// Objects with these keywords are values or lists, not JSON-LD node objects.\nconst VALUE_OBJECT_KEYWORDS: ReadonlySet<string> = new Set([\n \"@value\",\n \"@list\",\n \"@set\",\n]);\n\nconst IDENTIFIER_PROPERTIES: 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 ...ADDRESSING_PROPERTIES,\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// A node object has one of each.\nconst FUNCTIONAL_REFERENCES = [\"id\", \"href\"] as const;\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 === MAXIMUM_DIAGNOSTICS) {\n complete = false;\n truncated = true;\n diagnostics[MAXIMUM_DIAGNOSTICS - 1] = {\n reason: \"diagnostic_limit_reached\",\n ...DIAGNOSTIC_REASONS.diagnostic_limit_reached,\n path: [],\n message: \"Further diagnostics were omitted.\",\n };\n return;\n }\n const classification = DIAGNOSTIC_REASONS[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 // A blank node identifier is no IRI, whatever term \"_\" names.\n if (colon < 0 || value.startsWith(\"_:\")) 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 [\n ACTIVITY_STREAMS_CONTEXT,\n \"https://w3id.org/security/v1\",\n ]) {\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(ACTIVITY_STREAMS_CONTEXT)!;\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 ? ACTIVITY_STREAMS_CONTEXT\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 || !IMPLEMENTED_TYPES.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 ACTOR_TYPES;\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 = ACTOR_TYPES.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 = ACTOR_TYPES.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// The keyword a key stands for: itself, or the keyword a term aliases. A\n// context the checker does not read aliases nothing it knows of.\nfunction keywordOf(\n key: string,\n context: DocumentContext | null | undefined,\n): string | undefined {\n if (key.startsWith(\"@\")) return key;\n const iri = context?.terms.get(key)?.iri;\n return iri?.startsWith(\"@\") === true ? iri : undefined;\n}\n\nfunction isNodeObject(\n values: Record<string, unknown>,\n context: DocumentContext | null,\n): boolean {\n return !Object.keys(values).some((key) =>\n VALUE_OBJECT_KEYWORDS.has(keywordOf(key, context) ?? \"\"),\n );\n}\n\n// The context an extension object is described with as a node object: none\n// for a value or a list, or null for one with properties as well, or for a\n// value that is an object but no JSON literal, which are no valid JSON-LD\n// and cannot be read.\nfunction nodeContext(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n if (context === undefined || isNodeObject(values, context)) return context;\n return Object.keys(values).some((key) => {\n const keyword = keywordOf(key, context);\n const value = values[key];\n // A value is a scalar unless it is a JSON literal.\n return (\n keyword == null ||\n (keyword === \"@value\" &&\n value !== null &&\n typeof value === \"object\" &&\n !isJsonLiteral(values, context))\n );\n })\n ? null\n : undefined;\n}\n\n// Whether a value object holds a JSON literal, however its keywords are\n// spelled.\nfunction isJsonLiteral(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): boolean {\n return Object.keys(values).some((key) => {\n if (keywordOf(key, context) !== \"@type\") return false;\n const type = values[key];\n // Read a list entry without evaluating an accessor.\n return (\n type === \"@json\" ||\n (Array.isArray(type) &&\n type.length === 1 &&\n Object.getOwnPropertyDescriptor(type, 0)?.value === \"@json\")\n );\n });\n}\n\n// The context a value of an extension object is described with: none for a\n// context definition, for the value of a value object, which is a scalar or\n// a JSON literal, or for a language map, none of which holds node objects.\n// A key with a @language container holds a language map only as an object.\nfunction extensionChildContext(\n key: string,\n value: unknown,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n return key === \"@context\" ||\n keywordOf(key, context) === \"@value\" ||\n (context?.terms.get(key)?.container === \"@language\" && isLanguageMap(value))\n ? undefined\n : context;\n}\n\nfunction isLanguageMap(value: unknown): boolean {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// Check the keywords of an extension object, and tell whether it holds a\n// JSON literal, however its keywords are spelled.\nfunction checkJsonLiteral(\n values: Record<string, unknown>,\n path: FieldPath,\n report: Report,\n context: DocumentContext | null | undefined,\n): boolean {\n const literal = checkExtensionKeywords(values, path, report);\n return literal || isJsonLiteral(values, context);\n}\n\n// The context an extension object is read with: none when it is not\n// described, or null within a context of its own, which is not read.\nfunction extensionContext(\n values: Record<string, unknown>,\n context: DocumentContext | null | undefined,\n): DocumentContext | null | undefined {\n return context !== undefined && Object.hasOwn(values, \"@context\")\n ? null\n : context;\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)\n ? OBJECT_ONLY_PROPERTIES\n : new Set<string>();\n}\n\nfunction checkPathDepth(path: FieldPath, report: Report): boolean {\n if (path.length <= MAXIMUM_PATH_DEPTH) return true;\n report(\n \"processing_limit_exceeded\",\n path,\n `Nesting exceeds the supported limit of ${MAXIMUM_PATH_DEPTH} 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 onExtensionNode?: (\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext | null,\n ) => void,\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 // Given the context it inherits, report each node object outside JSON\n // literals with that context, or with null within a context of its own.\n function checkExtension(\n value: unknown,\n path: FieldPath,\n keywords = true,\n context?: DocumentContext | null,\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(() =>\n checkExtension(entry, entryPath, keywords, context),\n );\n });\n } else {\n const values = readDocument(value, path, report);\n if (values != null) {\n const own = extensionContext(values, context);\n const jsonLiteral =\n keywords && checkJsonLiteral(values, path, report, own);\n const node = nodeContext(values, own);\n if (keywords && node !== undefined) {\n onExtensionNode?.(values, path, node);\n }\n for (const key of Object.keys(values)) {\n const childKeywords = keywords && !(jsonLiteral && key === \"@value\");\n children.push(() =>\n checkExtension(\n values[key],\n [...path, key],\n childKeywords,\n extensionChildContext(key, values[key], own),\n ),\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 ...ADDRESSING_PROPERTIES,\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(\n value,\n fieldPath,\n true,\n extensionChildContext(source, value, context),\n );\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 * The source keys of the document's own custom extension properties, whose\n * values are preserved as opaque JSON, sorted by key. Together with\n * the keys in `properties` and `@context`, they are all of its keys.\n */\n readonly extensionProperties: 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 * The JSON-LD node objects inside this document's own opaque extension\n * values, at any depth, in traversal order.\n */\n readonly extensions: readonly ExtensionNode[];\n}\n\n/**\n * A JSON-LD node object inside an opaque extension value. The checker does\n * not read it as a vocabulary document, but a JSON-LD processor reads its\n * keys with the context it inherits, so its standard properties are named\n * as a described document's are, whatever their type coercion.\n */\nexport interface ExtensionNode {\n /** Source path of the node object. */\n readonly path: FieldPath;\n /**\n * The standard name of the property that holds the node object in another\n * one, whatever its source spelling; absent directly under an extension\n * property.\n */\n readonly property?: string;\n /** The path of the node object whose `property` holds this one. */\n readonly parent?: FieldPath;\n /**\n * Whether the checker cannot read all of the node object: it, or one\n * around it in the extension value, has a `@context` of its own, which the\n * checker does not read, or a reference property holds something other\n * than absolute IRIs, a blank node identifier as its `id`, and node\n * objects, such as a value object, a language map, a string the\n * property's alias does not coerce to an IRI, a relative reference or a\n * blank node identifier, or it has more than one `id` or `href`, or a node\n * object as one, or it nests properties with `@nest` or reverses them with\n * `@reverse`, or its `id` is used elsewhere in the document, as the `id` of\n * another node object or a reference outside its own properties, so that\n * it is not read apart; a `Link` whose `href` is its own `id` is read. An\n * uninterpreted node object has no properties, identifiers or types when\n * its context is unread.\n */\n readonly uninterpreted: boolean;\n /**\n * Standard property names mapped to the source keys that supply them,\n * matched by IRI whatever their type coercion or container.\n */\n readonly properties: ReadonlyMap<string, readonly string[]>;\n /**\n * String IRI references held by the node object's own standard\n * properties, through arrays and `@set` or `@list` objects, with compact\n * IRIs expanded through the context's prefixes.\n */\n readonly identifiers: readonly DocumentIdentifier[];\n /** The type IRIs, with terms and compact IRIs expanded. */\n readonly types: readonly string[];\n /**\n * The vocabulary category of its types the checker knows: `link` if one\n * is a link type, or else that of the first.\n */\n readonly kind?: DocumentNodeKind;\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\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 // A blank node identifier is no compact IRI, whatever prefix \"_\" names.\n if (\n colon <= 0 ||\n value.startsWith(\"//\", colon + 1) ||\n value.startsWith(\"_:\")\n ) {\n return value;\n }\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 (ACTOR_TYPES.some((Actor) => isTypeOrSubtype(Type, Actor))) return \"actor\";\n if (isTypeOrSubtype(Type, Collection)) return \"collection\";\n return \"object\";\n}\n\n// Name the standard properties of a document or node object, and the IRI\n// references they hold, as read with the context it is interpreted with.\nfunction describeProperties(\n values: Record<string, unknown>,\n path: FieldPath,\n fields: readonly SourceProperty[],\n context: DocumentContext,\n): Pick<DocumentNode, \"properties\" | \"identifiers\"> {\n const properties = new Map<string, string[]>();\n const identifiers: DocumentIdentifier[] = [];\n for (const { source, name } of fields) {\n if (name == null) continue;\n const sources = properties.get(name) ?? [];\n sources.push(source);\n properties.set(name, sources);\n if (!IDENTIFIER_PROPERTIES.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 { properties, identifiers };\n}\n\n// The standard name of an extension node object's key, matched by IRI\n// whatever its container, as a JSON-LD processor reads it, and whether its\n// strings are coerced as the standard property's are.\nfunction extensionProperty(\n source: string,\n context: DocumentContext,\n): { readonly name: string; readonly compatible: boolean } | undefined {\n const { name, iri, compatible } = resolveProperty(source, context);\n if (name != null) return { name, compatible };\n if (iri == null) return undefined;\n const type = context.terms.get(source)?.type;\n for (const [standard, term] of getContextTables().standardTerms) {\n if (term.iri === iri) {\n return { name: standard, compatible: term.type === type };\n }\n }\n return undefined;\n}\n\n// References must be absolute IRIs, or blank node identifiers, which name\n// no resource; relative ones need a base-IRI policy.\nconst isReadableReference = (value: string): boolean =>\n value.startsWith(\"_:\") ||\n (/^[a-z][a-z\\d+.-]*:/iu.test(value) && URL.canParse(value));\n\nfunction typeKind(iri: string): DocumentNodeKind | undefined {\n const Type =\n iri === Link.typeId.href\n ? Link\n : iri === Mention.typeId.href\n ? Mention\n : getEntityTypeById(iri);\n return Type == null ? undefined : nodeKind(Type);\n}\n\n// The entries of a value, through arrays and @set or @list objects. One\n// with a @context of its own is an entry itself, as its values are unread.\nfunction valueEntries(\n value: unknown,\n path: FieldPath,\n context: DocumentContext,\n): [unknown, FieldPath][] {\n if (Array.isArray(value)) {\n return value.flatMap((entry, index) =>\n valueEntries(entry, [...path, index], context),\n );\n }\n if (value !== null && typeof value === \"object\") {\n const values = value as Record<string, unknown>;\n if (Object.hasOwn(values, \"@context\")) return [[value, path]];\n const wrapper = Object.keys(values).find((key) => {\n const keyword = keywordOf(key, context);\n return keyword === \"@set\" || keyword === \"@list\";\n });\n if (wrapper != null) {\n return valueEntries(values[wrapper], [...path, wrapper], context);\n }\n }\n return [[value, path]];\n}\n\n// What a node object in an extension value holds, as read so far.\ninterface ExtensionReading {\n readonly identifiers: DocumentIdentifier[];\n readonly types: string[];\n readonly children: [FieldPath, string][];\n}\n\n// Read one entry of a standard property of a node object in an extension\n// value, and tell false when it is what the checker cannot read as a\n// reference.\nfunction readExtensionEntry(\n entry: unknown,\n path: FieldPath,\n property: { readonly name: string; readonly compatible: boolean },\n context: DocumentContext,\n reading: ExtensionReading,\n): boolean {\n const { name, compatible } = property;\n const reference = IDENTIFIER_PROPERTIES.has(name);\n if (typeof entry === \"string\") {\n if (name === \"type\") {\n reading.types.push(\n context.terms.get(entry)?.iri ?? expandIdentifier(entry, context),\n );\n return true;\n }\n if (!reference) return true;\n const iri = expandIdentifier(entry, context);\n // A literal or a relative reference names no resource the checker can\n // tell, nor does a blank node but as an id: elsewhere, it may name a\n // node object defined apart from the one that refers to it.\n if (!compatible || !isReadableReference(iri)) return false;\n // It is still listed, so that identity checks follow it.\n reading.identifiers.push({ property: name, path, value: entry, iri });\n return !iri.startsWith(\"_:\") || name === \"id\";\n }\n // Null stands for no value.\n if (entry === null) return true;\n if (typeof entry !== \"object\") return !reference;\n if (isNodeObject(entry as Record<string, unknown>, context)) {\n reading.children.push([path, name]);\n return true;\n }\n return !reference;\n}\n\n// Tell whether an id or href has more than one value, or a node object.\nfunction hasAmbiguousReference(reading: ExtensionReading): boolean {\n return FUNCTIONAL_REFERENCES.some(\n (name) =>\n reading.identifiers.filter(({ property }) => property === name).length >\n 1 || reading.children.some(([, property]) => property === name),\n );\n}\n\n// Describe a node object in an extension value, with the node objects its\n// standard properties hold and the names of those properties.\nfunction describeExtensionNode(\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext | null,\n): {\n readonly node: ExtensionNode;\n readonly children: readonly (readonly [FieldPath, string])[];\n} {\n if (context == null) {\n return {\n node: {\n path,\n uninterpreted: true,\n properties: new Map(),\n identifiers: [],\n types: [],\n },\n children: [],\n };\n }\n const properties = new Map<string, string[]>();\n const reading: ExtensionReading = {\n identifiers: [],\n types: [],\n children: [],\n };\n let readable = true;\n for (const source of Object.keys(values).sort()) {\n // Nested properties belong to the node object around them, and reverse\n // ones make other node objects the subjects; neither is read that way.\n const keyword = keywordOf(source, context);\n if (keyword === \"@nest\" || keyword === \"@reverse\") readable = false;\n const property = extensionProperty(source, context);\n if (property == null) continue;\n const { name } = property;\n properties.set(name, [...(properties.get(name) ?? []), source]);\n // A language map holds strings in languages, not references.\n if (\n context.terms.get(source)?.container === \"@language\" &&\n isLanguageMap(values[source])\n ) {\n if (IDENTIFIER_PROPERTIES.has(name) && values[source] != null) {\n readable = false;\n }\n continue;\n }\n for (const [entry, entryPath] of valueEntries(\n values[source],\n [...path, source],\n context,\n )) {\n if (!readExtensionEntry(entry, entryPath, property, context, reading)) {\n readable = false;\n }\n }\n }\n const { identifiers, types, children } = reading;\n const kinds = types.map(typeKind).filter((kind) => kind != null);\n const kind = kinds.includes(\"link\") ? \"link\" : kinds[0];\n return {\n node: {\n path,\n uninterpreted: !readable || hasAmbiguousReference(reading),\n properties,\n identifiers,\n types,\n ...(kind == null ? {} : { kind }),\n },\n children,\n };\n}\n\n// Find the objects in the language maps of a document's or a node object's\n// keys, which hold strings in languages: an object there is no valid\n// JSON-LD, and is not read.\nfunction languageMapObjects(\n values: Record<string, unknown>,\n path: FieldPath,\n context: DocumentContext,\n): FieldPath[] {\n return Object.keys(values).flatMap((source) => {\n if (context.terms.get(source)?.container !== \"@language\") return [];\n const map = values[source];\n if (!isLanguageMap(map)) return [];\n return Object.entries(map as Record<string, unknown>).flatMap(\n ([language, entry]) => {\n const entries: [unknown, FieldPath][] = Array.isArray(entry)\n ? entry.map((item, index) => [\n item,\n [...path, source, language, index],\n ])\n : [[entry, [...path, source, language]]];\n return entries\n .filter(([item]) => item !== null && typeof item === \"object\")\n .map(([, itemPath]) => itemPath);\n },\n );\n });\n}\n\n// Name the property of its parent that embeds each value, which sits at\n// [...parent, key] or [...parent, key, index].\nfunction nameEmbeddingProperties<\n T extends Pick<DocumentNode, \"path\" | \"properties\" | \"property\">,\n>(nodes: readonly T[]): T[] {\n const byPath = new Map(\n nodes.map((node) => [JSON.stringify(node.path), node]),\n );\n return nodes.map((node) => {\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 if (\n length < node.path.length - 1 &&\n typeof node.path.at(-1) !== \"number\"\n ) {\n continue;\n }\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\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 read as vocabulary documents, but the JSON-LD\n * node objects in them are described as extensions of the document that\n * holds them.\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 const extensions: {\n readonly values: Record<string, unknown>;\n readonly path: FieldPath;\n readonly context: DocumentContext | null;\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 undefined,\n (values, path, context) => {\n extensions.push({ values, path, context });\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 documents = visited.map(({ values, path, context, Type, fields }) => ({\n path,\n type: Type.typeId.href,\n kind: nodeKind(Type),\n ...describeProperties(\n values,\n path,\n fields.filter(({ compatible }) => compatible),\n context,\n ),\n // Validation has reported any other unnamed key as an error.\n extensionProperties: fields\n .filter(({ name }) => name == null)\n .map(({ source }) => source),\n }));\n const described = [\n ...extensions.map(({ values, path, context }) =>\n describeExtensionNode(values, path, context),\n ),\n ...[...visited, ...extensions].flatMap(({ values, path, context }) =>\n context == null\n ? []\n : languageMapObjects(values, path, context).map((object) =>\n describeExtensionNode({}, object, null),\n ),\n ),\n ];\n const holders = new Map(\n described.flatMap(({ node, children }) =>\n children.map(([path, property]) => [\n JSON.stringify(path),\n { property, parent: node.path },\n ]),\n ),\n );\n // Node objects that share an id are one node, and one whose id another\n // value refers to says more of what that value names, so a node object\n // whose id is used elsewhere in the document is not read apart from it.\n // Its own properties, such as a Link's href naming its own id, name no\n // other node to join.\n const uses = Map.groupBy(\n [...documents, ...described.map(({ node }) => node)].flatMap(\n ({ identifiers }) => identifiers,\n ),\n ({ iri }) => iri,\n );\n const extensionNodes = described.map(({ node }): ExtensionNode => {\n const id = node.identifiers.find(({ property }) => property === \"id\");\n // Every use of its id in its own properties is among the uses; counting\n // keeps this linear in a long list of them.\n const joined =\n id != null &&\n (uses.get(id.iri)?.length ?? 0) >\n node.identifiers.filter(({ iri }) => iri === id.iri).length;\n return {\n ...node,\n ...holders.get(JSON.stringify(node.path)),\n ...(joined ? { uninterpreted: true } : {}),\n };\n });\n const owners = new Map(\n visited.map(({ path }): [string, ExtensionNode[]] => [\n JSON.stringify(path),\n [],\n ]),\n );\n for (const node of extensionNodes) {\n // A node object belongs to the closest document around it.\n for (let length = node.path.length - 1; length >= 0; length -= 1) {\n const owner = owners.get(JSON.stringify(node.path.slice(0, length)));\n if (owner == null) continue;\n owner.push(node);\n break;\n }\n }\n return nameEmbeddingProperties(\n documents.map(\n (node): DocumentNode => ({\n ...node,\n extensions: owners.get(JSON.stringify(node.path)) ?? [],\n }),\n ),\n );\n}\n"],"mappings":";;;;;AAgFA,MAAa,qBAAqB;CAChC,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,oBAAoB;EAAE,UAAU;EAAa,UAAU;CAAQ;CAC/D,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;EAAE,UAAU;EAAW,UAAU;CAAQ;CACpE,0BAA0B;EAAE,UAAU;EAAW,UAAU;CAAQ;CACnE,kCAAkC;EAChC,UAAU;EACV,UAAU;CACZ;CACA,8BAA8B;EAC5B,UAAU;EACV,UAAU;CACZ;CACA,qBAAqB;EAAE,UAAU;EAAiB,UAAU;CAAU;CACtE,mBAAmB;EAAE,UAAU;EAAiB,UAAU;CAAU;AACtE;AAgFA,MAAM,2BAA2B;AACjC,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,cAAc;CAAC;CAAa;CAAO;CAAc;CAAQ;AAAO;;AAEtE,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,yCAA8C,IAAI,IAAI;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAWD,MAAM,oCAAiD,IAAI,IAAoB;CAC7E;CACAA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;AACF,CAAC;AAED,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,wBAAwB,CAAC,MAAM,MAAM;AAG3C,SAAS,iBAAiB;CACxB,MAAM,cAA4B,CAAC;CACnC,IAAI,WAAW;CACf,IAAI,YAAY;CAEhB,MAAM,UAAkB,QAAQ,MAAM,YAAY;EAChD,IAAI,WAAW;EACf,IAAI,YAAY,WAAW,qBAAqB;GAC9C,WAAW;GACX,YAAY;GACZ,YAA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