document-model 6.2.3-dev.90 → 6.2.3-dev.91
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.
- package/dist/catalog-6zzASEUv.js +358 -0
- package/dist/catalog-6zzASEUv.js.map +1 -0
- package/dist/catalog-B3nJD57s.d.ts +85 -0
- package/dist/catalog-B3nJD57s.d.ts.map +1 -0
- package/dist/index.d.ts +565 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4429 -2
- package/dist/index.js.map +1 -1
- package/dist/scalars.d.ts +2 -82
- package/dist/scalars.d.ts.map +1 -1
- package/dist/scalars.js +1 -354
- package/dist/scalars.js.map +1 -1
- package/dist/tooling.d.mts +121 -0
- package/dist/tooling.d.mts.map +1 -0
- package/dist/tooling.mjs +2655 -0
- package/dist/tooling.mjs.map +1 -0
- package/package.json +8 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tooling.mjs","names":["schema","schema","schema","schema","schema","schema"],"sources":["../src/definition/kernel/hashes.ts","../src/definition/kernel/primitives.ts","../src/definition/kernel/diagnostics.ts","../src/scalars/types.ts","../src/scalars/define-catalog-scalar.ts","../src/scalars/scalar-literal.ts","../src/scalars/declarations/unknown.ts","../src/scalars/declarations/date-time.ts","../src/scalars/pattern.ts","../src/scalars/declarations/address.ts","../src/scalars/declarations/attachment-ref.ts","../src/scalars/coercion.ts","../src/scalars/declarations/amounts.ts","../src/scalars/declarations/amount-tokens.ts","../src/scalars/declarations/ethereum-address.ts","../src/scalars/declarations/email-address.ts","../src/scalars/declarations/amount-percentage.ts","../src/scalars/declarations/date.ts","../src/scalars/declarations/url.ts","../src/scalars/declarations/amount-money.ts","../src/scalars/declarations/olabel.ts","../src/scalars/declarations/currency.ts","../src/scalars/declarations/phid.ts","../src/scalars/declarations/oid.ts","../src/scalars/declarations/amount-fiat.ts","../src/scalars/declarations/amount-currency.ts","../src/scalars/declarations/amount-crypto.ts","../src/scalars/declarations/amount.ts","../src/scalars/declarations/upload.ts","../src/scalars/declarations/json-object.ts","../src/scalars/catalog.ts","../src/definition/kernel/diagnostic-collector.ts","../src/definition/kernel/data-properties.ts","../src/definition/kernel/diagnostic-codes.ts","../src/definition/kernel/graphql-ast.ts","../src/definition/dsl/diagnostic-codes.ts","../src/definition/compiler/diagnostic-codes.ts","../src/definition/compiler/wire-shape.ts","../src/definition/model/diagnostic-codes.ts","../src/definition/tooling/diagnostic-codes.ts","../src/definition/tooling/adapters/code-first-document-model-source-adapter.ts","../src/definition/tooling/definition-source-resolution.ts","../src/definition/tooling/structured-diagnostics.ts","../src/definition/tooling/definition-source-loader.ts"],"sourcesContent":["import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\n\n// Hand-written so Node and browser builds derive the same digests and IDs\n// synchronously, with no host crypto.\n\nfunction rotateRight(value: number, shift: number): number {\n return ((value >>> shift) | (value << (32 - shift))) >>> 0;\n}\n\nconst SHA256_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nexport function sha256(value: string): Sha256Digest {\n const bytes = new TextEncoder().encode(value);\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ]);\n const words = new Uint32Array(64);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 64; index += 1) {\n const previous15 = words[index - 15];\n const previous2 = words[index - 2];\n const sigma0 =\n rotateRight(previous15, 7) ^\n rotateRight(previous15, 18) ^\n (previous15 >>> 3);\n const sigma1 =\n rotateRight(previous2, 17) ^\n rotateRight(previous2, 19) ^\n (previous2 >>> 10);\n words[index] =\n (words[index - 16] + sigma0 + words[index - 7] + sigma1) >>> 0;\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n let f = state[5];\n let g = state[6];\n let h = state[7];\n\n for (let index = 0; index < 64; index += 1) {\n const sigma1 =\n rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n const choice = (e & f) ^ (~e & g);\n const temporary1 =\n (h + sigma1 + choice + SHA256_CONSTANTS[index] + words[index]) >>> 0;\n const sigma0 =\n rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const temporary2 = (sigma0 + majority) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d + temporary1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temporary1 + temporary2) >>> 0;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n state[5] = (state[5] + f) >>> 0;\n state[6] = (state[6] + g) >>> 0;\n state[7] = (state[7] + h) >>> 0;\n }\n\n const hex = [...state]\n .map((word) => word.toString(16).padStart(8, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction uuidBytes(uuid: string): Uint8Array {\n if (!UUID_PATTERN.test(uuid)) {\n throw new TypeError(\n `UUID namespace ${JSON.stringify(uuid)} is not canonical.`,\n );\n }\n const hex = uuid.replaceAll(\"-\", \"\");\n return Uint8Array.from({ length: 16 }, (_, index) =>\n Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16),\n );\n}\n\nfunction formatUuid(bytes: Uint8Array): string {\n const hex = [...bytes]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\nexport function uuidV5(namespace: string, name: string): string {\n const namespaceBytes = uuidBytes(namespace);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(namespaceBytes.length + nameBytes.length);\n input.set(namespaceBytes);\n input.set(nameBytes, namespaceBytes.length);\n const digest = sha1(input).slice(0, 16);\n digest[6] = (digest[6] & 0x0f) | 0x50;\n digest[8] = (digest[8] & 0x3f) | 0x80;\n return formatUuid(digest);\n}\n\nfunction rotateLeft(value: number, shift: number): number {\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nfunction sha1(bytes: Uint8Array): Uint8Array {\n const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n const input = new Uint8Array(paddedLength);\n input.set(bytes);\n input[bytes.length] = 0x80;\n const view = new DataView(input.buffer);\n const bitLength = BigInt(bytes.length) * 8n;\n view.setUint32(paddedLength - 8, Number(bitLength >> 32n), false);\n view.setUint32(paddedLength - 4, Number(bitLength & 0xffff_ffffn), false);\n\n const state = new Uint32Array([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n ]);\n const words = new Uint32Array(80);\n\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 80; index += 1) {\n words[index] = rotateLeft(\n words[index - 3] ^\n words[index - 8] ^\n words[index - 14] ^\n words[index - 16],\n 1,\n );\n }\n\n let a = state[0];\n let b = state[1];\n let c = state[2];\n let d = state[3];\n let e = state[4];\n\n for (let index = 0; index < 80; index += 1) {\n let f: number;\n let k: number;\n if (index < 20) {\n f = (b & c) | (~b & d);\n k = 0x5a827999;\n } else if (index < 40) {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n } else if (index < 60) {\n f = (b & c) | (b & d) | (c & d);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n const next = (rotateLeft(a, 5) + f + e + k + words[index]) >>> 0;\n e = d;\n d = c;\n c = rotateLeft(b, 30);\n b = a;\n a = next;\n }\n\n state[0] = (state[0] + a) >>> 0;\n state[1] = (state[1] + b) >>> 0;\n state[2] = (state[2] + c) >>> 0;\n state[3] = (state[3] + d) >>> 0;\n state[4] = (state[4] + e) >>> 0;\n }\n\n const digest = new Uint8Array(20);\n const digestView = new DataView(digest.buffer);\n state.forEach((word, index) => {\n digestView.setUint32(index * 4, word, false);\n });\n return digest;\n}\n","import type { Sha256Digest } from \"@powerhousedao/shared/document-model\";\nimport { sha256 } from \"./hashes.js\";\n\nfunction memberPath(parent: string, key: string | number): string {\n if (typeof key === \"number\") {\n return `${parent}[${key}]`;\n }\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)\n ? `${parent}.${key}`\n : `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction encodeProperty(\n descriptor: PropertyDescriptor,\n path: string,\n ancestors: Set<object>,\n): string {\n if (!(\"value\" in descriptor)) {\n throw new TypeError(`${path} must be a data property, not an accessor.`);\n }\n if (descriptor.enumerable !== true) {\n throw new TypeError(`${path} must be enumerable.`);\n }\n return encode(descriptor.value, path, ancestors);\n}\n\nfunction encodeArray(\n value: readonly unknown[],\n path: string,\n ancestors: Set<object>,\n): string {\n if (Object.getPrototypeOf(value) !== Array.prototype) {\n throw new TypeError(`${path} must be a plain array.`);\n }\n for (const key of Reflect.ownKeys(value)) {\n if (key === \"length\") {\n continue;\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n if (!/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length) {\n throw new TypeError(\n `${path} must not have a non-index property ${JSON.stringify(key)}.`,\n );\n }\n }\n const members: string[] = [];\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n if (descriptor === undefined) {\n throw new TypeError(\n `${memberPath(path, index)} must not be an array hole.`,\n );\n }\n members.push(\n encodeProperty(descriptor, memberPath(path, index), ancestors),\n );\n }\n return `[${members.join(\",\")}]`;\n}\n\nfunction encodeObject(\n value: object,\n path: string,\n ancestors: Set<object>,\n): string {\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${path} must be a plain object.`);\n }\n const keys: string[] = [];\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") {\n throw new TypeError(`${path} must not have symbol keys.`);\n }\n keys.push(key);\n }\n keys.sort(compareCodeUnits);\n const members: string[] = [];\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined) {\n throw new TypeError(`${memberPath(path, key)} must be an own property.`);\n }\n members.push(\n `${JSON.stringify(key)}:${encodeProperty(descriptor, memberPath(path, key), ancestors)}`,\n );\n }\n return `{${members.join(\",\")}}`;\n}\n\nfunction encode(value: unknown, path: string, ancestors: Set<object>): string {\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return JSON.stringify(value);\n case \"number\":\n if (Number.isFinite(value)) {\n return JSON.stringify(value);\n }\n throw new TypeError(`${path} must be a finite number.`);\n case \"object\": {\n if (value === null) {\n return \"null\";\n }\n if (ancestors.has(value)) {\n throw new TypeError(`${path} must not contain a cycle.`);\n }\n ancestors.add(value);\n const encoded = Array.isArray(value)\n ? encodeArray(value, path, ancestors)\n : encodeObject(value, path, ancestors);\n ancestors.delete(value);\n return encoded;\n }\n default:\n throw new TypeError(\n `${path} must be a JSON value, received ${typeof value}.`,\n );\n }\n}\n\nexport function canonicalJson(value: unknown): string {\n return encode(value, \"$\", new Set());\n}\n\nexport function canonicalDigest(value: unknown): Sha256Digest {\n return sha256(canonicalJson(value));\n}\n\nexport function compareCodeUnits(a: string, b: string): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nconst DIGIT_0 = 48;\nconst DIGIT_9 = 57;\n\nfunction isDigit(code: number): boolean {\n return DIGIT_0 <= code && code <= DIGIT_9;\n}\n\n/**\n * graphql-js's `naturalCompare`, which `lexicographicSortSchema` sorts a\n * generated schema with: runs of digits compare as numbers, so `item2`\n * precedes `item10`. Copied, not imported, so a model never loads `graphql`.\n */\nexport function compareGeneratedOrder(a: string, b: string): number {\n let aIndex = 0;\n let bIndex = 0;\n while (aIndex < a.length && bIndex < b.length) {\n let aChar = a.charCodeAt(aIndex);\n let bChar = b.charCodeAt(bIndex);\n if (isDigit(aChar) && isDigit(bChar)) {\n let aNumber = 0;\n do {\n ++aIndex;\n aNumber = aNumber * 10 + aChar - DIGIT_0;\n aChar = a.charCodeAt(aIndex);\n } while (isDigit(aChar) && aNumber > 0);\n let bNumber = 0;\n do {\n ++bIndex;\n bNumber = bNumber * 10 + bChar - DIGIT_0;\n bChar = b.charCodeAt(bIndex);\n } while (isDigit(bChar) && bNumber > 0);\n if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;\n } else {\n if (aChar !== bChar) return aChar < bChar ? -1 : 1;\n ++aIndex;\n ++bIndex;\n }\n }\n return a.length - b.length;\n}\n\nexport const EMPTY_INPUT_FIELD_NAME = \"_empty\";\n\nexport function isGraphQLName(value: unknown): value is string {\n return typeof value === \"string\" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);\n}\n\nexport function isAuthoredSchemaName(value: unknown): value is string {\n return isGraphQLName(value) && !value.startsWith(\"__\");\n}\n\nexport function isEnumValueName(value: unknown): value is string {\n return (\n isAuthoredSchemaName(value) &&\n value !== \"true\" &&\n value !== \"false\" &&\n value !== \"null\"\n );\n}\n\nexport function isNFC(value: string): boolean {\n return value.normalize(\"NFC\") === value;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionDiagnosticPhase,\n DefinitionDiagnosticSeverity,\n DefinitionPath,\n DefinitionRef,\n DefinitionRelatedLocation,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareCodeUnits } from \"./primitives.js\";\n\nexport type DiagnosticCode = `PH-${string}`;\n\ntype DiagnosticCodeEntry = {\n readonly severity: DefinitionDiagnosticSeverity;\n readonly phase: DefinitionDiagnosticPhase;\n readonly meaning: string;\n};\n\nconst MAX_SUMMARY_CODE_POINTS = 512;\n\nexport function capCodePoints(\n value: string,\n max: number = MAX_SUMMARY_CODE_POINTS,\n): string {\n const points = [...value];\n const limit = Math.max(0, max);\n return points.length <= limit ? value : points.slice(0, limit).join(\"\");\n}\n\nexport type DefinitionDiagnosticInput<TCode extends string = DiagnosticCode> = {\n readonly code: TCode;\n readonly path: DefinitionPath;\n readonly message: string;\n readonly repair: string;\n readonly source?: DefinitionSource;\n readonly definition?: DefinitionRef;\n readonly expected?: string;\n readonly received?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n};\n\nfunction copySource(source: DefinitionSource): DefinitionSource {\n return {\n specifier: source.specifier,\n ...(source.exportPath !== undefined && {\n exportPath: [...source.exportPath],\n }),\n };\n}\n\nfunction copyDefinitionRef(definition: DefinitionRef): DefinitionRef {\n return {\n kind: definition.kind,\n key: definition.key,\n ...(definition.version !== undefined && { version: definition.version }),\n };\n}\n\nfunction createDiagnostic(\n input: DefinitionDiagnosticInput,\n { severity, phase }: DiagnosticCodeEntry,\n): DefinitionDiagnostic {\n return {\n code: input.code,\n severity,\n phase,\n ...(input.source !== undefined && { source: copySource(input.source) }),\n ...(input.definition !== undefined && {\n definition: copyDefinitionRef(input.definition),\n }),\n path: [...input.path],\n message: input.message,\n ...(input.expected !== undefined && {\n expected: capCodePoints(input.expected),\n }),\n ...(input.received !== undefined && {\n received: capCodePoints(input.received),\n }),\n repair: input.repair,\n ...(input.related !== undefined && {\n related: input.related.map((location) => ({\n ...(location.source !== undefined && {\n source: copySource(location.source),\n }),\n path: [...location.path],\n message: location.message,\n })),\n }),\n };\n}\n\nexport function describeReceived(value: unknown): string {\n if (value === null) return \"null\";\n try {\n return Array.isArray(value) ? \"array\" : typeof value;\n } catch {\n return \"inspection-failed\";\n }\n}\n\n/** The codes one layer emits, and the builders that fill in each code's severity and phase. */\nexport type DiagnosticCatalog<TCode extends DiagnosticCode> = {\n readonly codes: { readonly [K in TCode]: DiagnosticCodeEntry };\n create(input: DefinitionDiagnosticInput<TCode>): DefinitionDiagnostic;\n fail(input: DefinitionDiagnosticInput<TCode>): never;\n};\n\n/**\n * A layer's catalog: its own codes plus the codes of the catalog below it,\n * which already holds every lower layer's codes. A code keeps the meaning its\n * owning layer gave it, so an own code the lower catalog declares is refused.\n */\nexport function defineDiagnosticCatalog<\n TOwn extends DiagnosticCode = never,\n TLower extends DiagnosticCode = never,\n>(\n own: { readonly [K in TOwn]: DiagnosticCodeEntry } & {\n readonly [K in NoInfer<TLower>]?: never;\n },\n lower?: DiagnosticCatalog<TLower>,\n): DiagnosticCatalog<TOwn | TLower> {\n const lowerCodes: Readonly<Record<string, DiagnosticCodeEntry>> =\n lower?.codes ?? {};\n const ownEntries = Object.entries<DiagnosticCodeEntry>(own).map(\n ([code, entry]) => [code, Object.freeze({ ...entry })] as const,\n );\n const redefined = ownEntries\n .map(([code]) => code)\n .filter((code) => Object.hasOwn(lowerCodes, code));\n if (redefined.length > 0) {\n throw new TypeError(\n `Diagnostic code ${redefined.join(\", \")} is already declared by a lower layer.`,\n );\n }\n const codes = Object.freeze({\n ...lowerCodes,\n ...Object.fromEntries(ownEntries),\n }) as { readonly [K in TOwn | TLower]: DiagnosticCodeEntry };\n const create = (input: DefinitionDiagnosticInput<TOwn | TLower>) =>\n createDiagnostic(input, codes[input.code]);\n return Object.freeze({\n codes,\n create,\n fail(input: DefinitionDiagnosticInput<TOwn | TLower>): never {\n throw new DefinitionError([create(input)]);\n },\n });\n}\n\ntype Ordering = -1 | 0 | 1;\n\nfunction compareNumbers(a: number, b: number): Ordering {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareOptional<T>(\n a: T | undefined,\n b: T | undefined,\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n if (a === undefined) return b === undefined ? 0 : -1;\n if (b === undefined) return 1;\n return compare(a, b);\n}\n\nfunction compareLists<T>(\n a: readonly T[],\n b: readonly T[],\n compare: (x: T, y: T) => Ordering,\n): Ordering {\n const shared = Math.min(a.length, b.length);\n for (let index = 0; index < shared; index += 1) {\n const result = compare(a[index], b[index]);\n if (result !== 0) return result;\n }\n return compareNumbers(a.length, b.length);\n}\n\nfunction comparePathSegments(a: string | number, b: string | number): Ordering {\n if (typeof a === \"number\") {\n return typeof b === \"number\" ? compareNumbers(a, b) : -1;\n }\n if (typeof b === \"number\") return 1;\n return compareCodeUnits(a, b);\n}\n\nexport function compareDefinitionPaths(\n a: DefinitionPath,\n b: DefinitionPath,\n): Ordering {\n return compareLists(a, b, comparePathSegments);\n}\n\nfunction compareSources(a: DefinitionSource, b: DefinitionSource): Ordering {\n const specifier = compareCodeUnits(a.specifier, b.specifier);\n if (specifier !== 0) return specifier;\n return compareOptional(a.exportPath, b.exportPath, (x, y) =>\n compareLists(x, y, compareCodeUnits),\n );\n}\n\nfunction compareDefinitionRefs(a: DefinitionRef, b: DefinitionRef): Ordering {\n const kind = compareCodeUnits(a.kind, b.kind);\n if (kind !== 0) return kind;\n const key = compareCodeUnits(a.key, b.key);\n if (key !== 0) return key;\n return compareOptional(a.version, b.version, compareNumbers);\n}\n\nexport function compareDefinitionDiagnostics(\n a: DefinitionDiagnostic,\n b: DefinitionDiagnostic,\n): Ordering {\n const source = compareOptional(a.source, b.source, compareSources);\n if (source !== 0) return source;\n const definition = compareOptional(\n a.definition,\n b.definition,\n compareDefinitionRefs,\n );\n if (definition !== 0) return definition;\n const path = compareDefinitionPaths(a.path, b.path);\n if (path !== 0) return path;\n return compareCodeUnits(a.code, b.code);\n}\n\nexport function sortDefinitionDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n return [...diagnostics].sort(compareDefinitionDiagnostics);\n}\n\nfunction formatPointer(path: DefinitionPath): string {\n if (path.length === 0) return \"(root)\";\n return path\n .map(\n (segment) =>\n `/${String(segment).replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`,\n )\n .join(\"\");\n}\n\nfunction formatSource(source: DefinitionSource | undefined): string {\n if (source === undefined) return \"(no source)\";\n const exportPath = source.exportPath ?? [];\n return exportPath.length === 0\n ? source.specifier\n : `${source.specifier}#${formatPointer(exportPath)}`;\n}\n\nfunction formatDefinitionRef(definition: DefinitionRef | undefined): string {\n if (definition === undefined) return \"\";\n const version =\n definition.version === undefined ? \"\" : `@${definition.version}`;\n return ` ${definition.kind} ${definition.key}${version}`;\n}\n\nfunction oneLine(value: string): string {\n return value.replace(/\\s+/g, \" \");\n}\n\n/** @experimental One line: code, severity and phase, location, message, expected, received, related and repair. */\nexport function formatDefinitionDiagnostic(\n diagnostic: DefinitionDiagnostic,\n): string {\n const where = `${formatSource(diagnostic.source)}${formatDefinitionRef(diagnostic.definition)} ${formatPointer(diagnostic.path)}`;\n const expected =\n diagnostic.expected === undefined\n ? \"\"\n : ` Expected: ${oneLine(diagnostic.expected)}`;\n const received =\n diagnostic.received === undefined\n ? \"\"\n : ` Received: ${oneLine(diagnostic.received)}`;\n const related = (diagnostic.related ?? [])\n .map(\n (location) =>\n ` Related: ${formatSource(location.source)} ${formatPointer(location.path)}: ${oneLine(location.message)}`,\n )\n .join(\"\");\n return `${diagnostic.code} [${diagnostic.severity}/${diagnostic.phase}] ${where}: ${oneLine(diagnostic.message)}${expected}${received}${related} Repair: ${oneLine(diagnostic.repair)}`;\n}\n\n/**\n * @experimental Thrown when a code-first declaration is refused. `diagnostics`\n * holds every problem found, sorted, each with its code, path and repair.\n */\nexport class DefinitionError extends Error {\n readonly diagnostics: readonly DefinitionDiagnostic[];\n\n constructor(\n diagnostics: readonly [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n ) {\n if (diagnostics.length === 0) {\n throw new TypeError(\"DefinitionError requires at least one diagnostic.\");\n }\n const sorted = sortDefinitionDiagnostics(diagnostics);\n const noun = sorted.length === 1 ? \"diagnostic\" : \"diagnostics\";\n super(\n [\n `Definition failed with ${sorted.length} ${noun}:`,\n ...sorted.map(formatDefinitionDiagnostic),\n ].join(\"\\n\"),\n );\n this.name = \"DefinitionError\";\n this.diagnostics = sorted;\n }\n}\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\n\nexport const SCALAR_DEFINITION = Symbol.for(\"powerhouse.scalar-definition\");\nexport const SCALAR_DEFINITION_VERSION = 1;\n\n/** The wire shape of a scalar's values. */\nexport type ScalarRepresentation =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"json-object\"\n | \"json\"\n | \"opaque\";\n\n/** The GraphQL coercion of a scalar: variables, inline literals, and output. */\nexport type ScalarCoercion<TValue> = {\n readonly parseValue: (input: unknown) => TValue;\n readonly parseLiteral: (node: ScalarLiteralNode) => TValue;\n readonly serialize: (value: unknown) => unknown;\n};\n\nexport type ScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = {\n readonly [SCALAR_DEFINITION]: typeof SCALAR_DEFINITION_VERSION;\n readonly name: TName;\n readonly description?: string;\n readonly schema: z.ZodType<TValue>;\n readonly typescriptType: string | null;\n readonly zodSource: string | null;\n readonly example?: TValue;\n /**\n * The wire shape of a value. It picks the literal kinds a derived coercion\n * accepts. A definition from a release before this field lacks it.\n */\n readonly representation?: ScalarRepresentation;\n /** Absent means derived: `schema` runs on every path and only the literal kinds of `representation` parse. */\n readonly coercion?: ScalarCoercion<TValue>;\n};\n\n/** A definition this release made, with its representation filled. */\nexport type DescribedScalarDefinition<\n TName extends string = string,\n TValue = unknown,\n> = ScalarDefinition<TName, TValue> & {\n readonly representation: ScalarRepresentation;\n};\n\nexport type ScalarValue<T> =\n T extends ScalarDefinition<string, infer V> ? V : never;\n\n/** The definition format version `value` is branded with, if it has a brand. */\nexport function scalarDefinitionVersion(value: unknown): unknown {\n return typeof value === \"object\" &&\n value !== null &&\n SCALAR_DEFINITION in value\n ? value[SCALAR_DEFINITION]\n : undefined;\n}\n\nexport function isScalarDefinition(value: unknown): value is ScalarDefinition {\n return scalarDefinitionVersion(value) === SCALAR_DEFINITION_VERSION;\n}\n","import {\n type DescribedScalarDefinition,\n SCALAR_DEFINITION,\n SCALAR_DEFINITION_VERSION,\n} from \"./types.js\";\n\nexport function defineCatalogScalar<TName extends string, TValue>(\n input: Omit<\n DescribedScalarDefinition<TName, TValue>,\n typeof SCALAR_DEFINITION\n >,\n): DescribedScalarDefinition<TName, TValue> {\n return Object.freeze({\n ...input,\n [SCALAR_DEFINITION]: SCALAR_DEFINITION_VERSION,\n } satisfies DescribedScalarDefinition<TName, TValue>);\n}\n","/**\n * Closed literal grammar handed to `parseLiteral`. It mirrors the GraphQL\n * literal kinds the catalog supports so a declaration never needs graphql-js.\n */\nexport type ScalarLiteralNode =\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"float\"; readonly value: string }\n | { readonly kind: \"boolean\"; readonly value: boolean }\n | { readonly kind: \"null\" }\n | { readonly kind: \"enum\"; readonly value: string }\n | { readonly kind: \"list\"; readonly values: readonly ScalarLiteralNode[] }\n | {\n readonly kind: \"object\";\n readonly fields: readonly {\n readonly name: string;\n readonly value: ScalarLiteralNode;\n }[];\n }\n | { readonly kind: \"variable\"; readonly name: string };\n\nexport class ScalarLiteralVariableError extends TypeError {\n constructor(name: string) {\n super(\n `Variable $${name} cannot appear inside a scalar literal; GraphQL resolves variables before literal coercion.`,\n );\n this.name = \"ScalarLiteralVariableError\";\n }\n}\n\n/** Converts a literal node to its runtime value. A variable anywhere throws. */\nexport function scalarLiteralValue(node: ScalarLiteralNode): unknown {\n switch (node.kind) {\n case \"string\":\n case \"enum\":\n return node.value;\n case \"int\":\n case \"float\":\n return Number(node.value);\n case \"boolean\":\n return node.value;\n case \"null\":\n return null;\n case \"list\":\n return node.values.map(scalarLiteralValue);\n case \"object\":\n return Object.fromEntries(\n node.fields.map((field) => [\n field.name,\n scalarLiteralValue(field.value),\n ]),\n );\n case \"variable\":\n throw new ScalarLiteralVariableError(node.name);\n }\n}\n\nexport function objectFields(\n node: ScalarLiteralNode,\n): ReadonlyMap<string, ScalarLiteralNode> {\n if (node.kind !== \"object\")\n throw new TypeError(\"Value must be an object literal.\");\n return new Map(node.fields.map((field) => [field.name, field.value]));\n}\n\nexport function literalString(\n node: ScalarLiteralNode | undefined,\n field: string,\n): string {\n if (node?.kind !== \"string\")\n throw new TypeError(`${field} must be a string literal.`);\n return node.value;\n}\n\nexport function floatOnlyNumber(\n node: ScalarLiteralNode | undefined,\n field: string,\n): number {\n if (node?.kind !== \"float\")\n throw new TypeError(`${field} must be a float literal.`);\n return Number.parseFloat(node.value);\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { scalarLiteralValue } from \"../scalar-literal.js\";\n\nexport const unknownScalar = defineCatalogScalar({\n name: \"Unknown\",\n typescriptType: \"unknown\",\n zodSource: \"z.unknown()\",\n schema: z.unknown(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: scalarLiteralValue,\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateTimeScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"DateTime\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","export function matchesScalarPattern(pattern: RegExp, value: unknown): boolean {\n return Reflect.apply(pattern.test.bind(pattern), undefined, [value]) === true;\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const addressScalar = defineCatalogScalar({\n example: \"eip155:0x0000000000000000000000000000000000000000\",\n name: \"Address\",\n typescriptType: \"`${string}:0x${string}`\",\n zodSource:\n \"z.custom<`${string}:0x${string}`>((val) => /^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/.test(val as string))\",\n schema: z.custom<`${string}:0x${string}`>((val) =>\n matchesScalarPattern(/^[a-zA-Z0-9]+:0x[a-fA-F0-9]{40}$/, val),\n ),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { matchesScalarPattern } from \"../pattern.js\";\n\nexport const attachmentRefScalar = defineCatalogScalar({\n example:\n \"attachment://v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n name: \"AttachmentRef\",\n typescriptType: \"`attachment://v${number}:${string}`\",\n zodSource:\n \"z.custom<`attachment://v${number}:${string}`>((val) => /^attachment:\\\\/\\\\/v\\\\d+:.+$/.test(val as string))\",\n schema: z.custom<`attachment://v${number}:${string}`>((val) =>\n matchesScalarPattern(/^attachment:\\/\\/v\\d+:.+$/, val),\n ),\n representation: \"string\",\n});\n","import type { z } from \"zod\";\nimport type { ScalarLiteralNode } from \"./scalar-literal.js\";\nimport type { ScalarCoercion } from \"./types.js\";\n\n/** Runs `schema` on every path; `readLiteral` turns an inline literal into its value first. */\nexport function validatingCoercion<TValue>(\n schema: z.ZodType<TValue>,\n readLiteral: (node: ScalarLiteralNode) => unknown,\n): ScalarCoercion<TValue> {\n const parse = (value: unknown): TValue => schema.parse(value);\n return {\n parseValue: parse,\n parseLiteral: (node) => parse(readLiteral(node)),\n serialize: parse,\n };\n}\n","import type { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\n// The document-engineering scalar resolvers this catalog replaced parsed an\n// amount's number only from a float literal, so an integer literal such as 5\n// is refused even though the schema accepts 5. The host does not use this\n// coercion yet; it accepts 5.\nexport function floatAmountCoercion(schema: z.ZodType<number>) {\n return validatingCoercion(schema, (node) => floatOnlyNumber(node, \"value\"));\n}\n\nexport function stringAmountCoercion<TValue>(schema: z.ZodType<TValue>) {\n return validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const value = literalString(fields.get(\"value\"), \"value\");\n if (!/^\\d+(\\.\\d+)?$/.test(value)) {\n throw new TypeError(\"value must be a numeric string.\");\n }\n return { unit: literalString(fields.get(\"unit\"), \"unit\"), value };\n });\n}\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountTokensScalar = defineCatalogScalar({\n name: \"Amount_Tokens\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const ethereumAddressScalar = defineCatalogScalar({\n name: \"EthereumAddress\",\n typescriptType: \"string\",\n zodSource:\n \"z.string().regex(/^0x[a-fA-F0-9]{40}$/, { error: 'Invalid Ethereum address format' })\",\n schema: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {\n error: \"Invalid Ethereum address format\",\n }),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const emailAddressScalar = defineCatalogScalar({\n name: \"EmailAddress\",\n typescriptType: \"string\",\n zodSource: \"z.email()\",\n schema: z.email(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountPercentageScalar = defineCatalogScalar({\n name: \"Amount_Percentage\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const dateScalar = defineCatalogScalar({\n example: \"2024-01-01T00:00:00.000Z\",\n name: \"Date\",\n typescriptType: \"string\",\n zodSource: \"z.iso.datetime()\",\n schema: z.iso.datetime(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const urlScalar = defineCatalogScalar({\n example: \"https://example.com\",\n name: \"URL\",\n typescriptType: \"string\",\n zodSource: \"z.url()\",\n schema: z.url(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { floatAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.number();\n\nexport const amountMoneyScalar = defineCatalogScalar({\n name: \"Amount_Money\",\n typescriptType: \"number\",\n zodSource: \"z.number()\",\n schema,\n representation: \"number\",\n coercion: floatAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const olabelScalar = defineCatalogScalar({\n name: \"OLabel\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const currencyScalar = defineCatalogScalar({\n name: \"Currency\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const phidScalar = defineCatalogScalar({\n name: \"PHID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const oidScalar = defineCatalogScalar({\n name: \"OID\",\n typescriptType: \"string\",\n zodSource: \"z.string()\",\n schema: z.string(),\n representation: \"string\",\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.number() });\n\nexport const amountFiatScalar = defineCatalogScalar({\n name: \"Amount_Fiat\",\n typescriptType: \"{ unit: string, value: number }\",\n zodSource: \"z.object({ unit: z.string(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n return {\n unit: literalString(fields.get(\"unit\"), \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCurrencyScalar = defineCatalogScalar({\n name: \"Amount_Currency\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string()})\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport { stringAmountCoercion } from \"./amounts.js\";\n\nconst schema = z.object({ unit: z.string(), value: z.string() });\n\nexport const amountCryptoScalar = defineCatalogScalar({\n name: \"Amount_Crypto\",\n typescriptType: \"{ unit: string, value: string }\",\n zodSource: \"z.object({ unit: z.string(), value: z.string() })\",\n schema,\n representation: \"json-object\",\n coercion: stringAmountCoercion(schema),\n});\n","import { z } from \"zod\";\nimport { validatingCoercion } from \"../coercion.js\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\nimport {\n floatOnlyNumber,\n literalString,\n objectFields,\n} from \"../scalar-literal.js\";\n\nconst schema = z.object({ unit: z.string().optional(), value: z.number() });\n\nexport const amountScalar = defineCatalogScalar({\n name: \"Amount\",\n typescriptType: \"{ unit?: string, value?: number }\",\n zodSource: \"z.object({ unit: z.string().optional(), value: z.number() })\",\n schema,\n representation: \"json-object\",\n coercion: validatingCoercion(schema, (node) => {\n const fields = objectFields(node);\n const unit = fields.get(\"unit\");\n return {\n unit: unit === undefined ? undefined : literalString(unit, \"unit\"),\n value: floatOnlyNumber(fields.get(\"value\"), \"value\"),\n };\n }),\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const uploadScalar = defineCatalogScalar({\n name: \"Upload\",\n typescriptType: \"File\",\n zodSource: \"z.any()\",\n schema: z.any(),\n representation: \"opaque\",\n coercion: {\n parseValue: (value) => value,\n parseLiteral: () => {\n throw new TypeError(\"Upload literals are not supported.\");\n },\n serialize: (value) => value,\n },\n});\n","import { z } from \"zod\";\nimport { defineCatalogScalar } from \"../define-catalog-scalar.js\";\n\nexport const jsonObjectScalar = defineCatalogScalar({\n name: \"JSONObject\",\n typescriptType: null,\n zodSource: null,\n schema: z.record(z.string(), z.unknown()),\n representation: \"json-object\",\n});\n","import { unknownScalar } from \"./declarations/unknown.js\";\nimport { dateTimeScalar } from \"./declarations/date-time.js\";\nimport { addressScalar } from \"./declarations/address.js\";\nimport { attachmentRefScalar } from \"./declarations/attachment-ref.js\";\nimport { amountTokensScalar } from \"./declarations/amount-tokens.js\";\nimport { ethereumAddressScalar } from \"./declarations/ethereum-address.js\";\nimport { emailAddressScalar } from \"./declarations/email-address.js\";\nimport { amountPercentageScalar } from \"./declarations/amount-percentage.js\";\nimport { dateScalar } from \"./declarations/date.js\";\nimport { urlScalar } from \"./declarations/url.js\";\nimport { amountMoneyScalar } from \"./declarations/amount-money.js\";\nimport { olabelScalar } from \"./declarations/olabel.js\";\nimport { currencyScalar } from \"./declarations/currency.js\";\nimport { phidScalar } from \"./declarations/phid.js\";\nimport { oidScalar } from \"./declarations/oid.js\";\nimport { amountFiatScalar } from \"./declarations/amount-fiat.js\";\nimport { amountCurrencyScalar } from \"./declarations/amount-currency.js\";\nimport { amountCryptoScalar } from \"./declarations/amount-crypto.js\";\nimport { amountScalar } from \"./declarations/amount.js\";\nimport { uploadScalar } from \"./declarations/upload.js\";\nimport { jsonObjectScalar } from \"./declarations/json-object.js\";\nimport type { DescribedScalarDefinition } from \"./types.js\";\n\nconst declarations = [\n unknownScalar,\n dateTimeScalar,\n addressScalar,\n attachmentRefScalar,\n amountTokensScalar,\n ethereumAddressScalar,\n emailAddressScalar,\n amountPercentageScalar,\n dateScalar,\n urlScalar,\n amountMoneyScalar,\n olabelScalar,\n currencyScalar,\n phidScalar,\n oidScalar,\n amountFiatScalar,\n amountCurrencyScalar,\n amountCryptoScalar,\n amountScalar,\n uploadScalar,\n jsonObjectScalar,\n] as const;\n\nexport type CatalogScalarDefinition = (typeof declarations)[number];\n\nexport const scalarCatalog: readonly DescribedScalarDefinition[] =\n Object.freeze([...declarations]);\n\nconst byName = new Map(\n scalarCatalog.map((definition) => [definition.name, definition]),\n);\n\nexport function getCatalogScalar(\n name: string,\n): DescribedScalarDefinition | undefined {\n return byName.get(name);\n}\n\ntype DocumentModelScalar = DescribedScalarDefinition & {\n readonly typescriptType: string;\n readonly zodSource: string;\n};\n\n// A model's SDL may use every catalog scalar codegen can type. JSONObject is\n// host-only, so it has neither a TypeScript type nor a zod source.\nexport const documentModelScalars: readonly DocumentModelScalar[] =\n Object.freeze(\n scalarCatalog.filter(\n (definition): definition is DocumentModelScalar =>\n definition.typescriptType !== null && definition.zodSource !== null,\n ),\n );\n","import type {\n DefinitionDiagnostic,\n DefinitionRef,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n type DefinitionDiagnosticInput,\n DefinitionError,\n type DiagnosticCatalog,\n type DiagnosticCode,\n sortDefinitionDiagnostics,\n} from \"./diagnostics.js\";\n\nexport class DefinitionDiagnosticCollector<TCode extends DiagnosticCode> {\n readonly #catalog: DiagnosticCatalog<TCode>;\n readonly #definition: DefinitionRef | undefined;\n readonly #diagnostics: DefinitionDiagnostic[] = [];\n\n constructor(catalog: DiagnosticCatalog<TCode>, definition?: DefinitionRef) {\n this.#catalog = catalog;\n this.#definition = definition;\n }\n\n get diagnostics(): readonly DefinitionDiagnostic[] {\n return sortDefinitionDiagnostics(this.#diagnostics);\n }\n\n add(input: DefinitionDiagnosticInput<TCode>): void {\n this.#diagnostics.push(\n this.#catalog.create({\n ...(this.#definition !== undefined && { definition: this.#definition }),\n ...input,\n }),\n );\n }\n\n merge(diagnostics: readonly DefinitionDiagnostic[]): void {\n for (const diagnostic of diagnostics) {\n this.#diagnostics.push(\n this.#definition === undefined || diagnostic.definition !== undefined\n ? diagnostic\n : { ...diagnostic, definition: { ...this.#definition } },\n );\n }\n }\n\n capture<T>(attempt: () => T): T | undefined {\n try {\n return attempt();\n } catch (error) {\n if (!(error instanceof DefinitionError)) throw error;\n this.merge(error.diagnostics);\n return undefined;\n }\n }\n\n throwIfFailed(): void {\n if (!this.#diagnostics.some((entry) => entry.severity === \"error\")) return;\n throw new DefinitionError(\n this.#diagnostics as [DefinitionDiagnostic, ...DefinitionDiagnostic[]],\n );\n }\n}\n","import type { DefinitionPath } from \"@powerhousedao/shared/document-model\";\nimport { describeReceived } from \"./diagnostics.js\";\n\ntype DataLeaf = string | number | boolean | bigint | null | undefined;\n\nexport type DataValue =\n | DataLeaf\n | readonly DataValue[]\n | { readonly [key: string]: DataValue };\n\nexport type DataSnapshotRejection =\n | {\n readonly ok: false;\n readonly reason: \"not-record\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-array\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"custom-prototype\";\n readonly path: DefinitionPath;\n readonly expected: \"record\" | \"array\";\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"symbol-key\";\n readonly path: DefinitionPath;\n readonly key: symbol;\n }\n | {\n readonly ok: false;\n readonly reason: \"unknown-key\";\n readonly path: DefinitionPath;\n readonly key: string;\n readonly allowedKeys: readonly string[];\n }\n | {\n readonly ok: false;\n readonly reason: \"accessor\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"non-enumerable\";\n readonly path: DefinitionPath;\n readonly key: string | number;\n }\n | {\n readonly ok: false;\n readonly reason: \"sparse\";\n readonly path: DefinitionPath;\n readonly key: number;\n }\n | {\n readonly ok: false;\n readonly reason: \"array-property\";\n readonly path: DefinitionPath;\n readonly key: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"cycle\";\n readonly path: DefinitionPath;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-data\";\n readonly path: DefinitionPath;\n readonly received: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"inspection-failed\";\n readonly path: DefinitionPath;\n };\n\nexport type DataSnapshot<T> =\n | { readonly ok: true; readonly value: T }\n | DataSnapshotRejection;\n\nexport function rejectionReceived(rejection: DataSnapshotRejection): string {\n return \"received\" in rejection ? rejection.received : rejection.reason;\n}\n\nconst CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function snapshotDataRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n): DataSnapshot<{ readonly [key: string]: DataValue }> {\n return snapshotPlainObject(\n value,\n allowedKeys,\n path,\n snapshotDataValue,\n new Set(),\n );\n}\n\nexport function snapshotDataArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly DataValue[]> {\n return snapshotArrayValue(value, path, snapshotDataValue, new Set());\n}\n\nexport function snapshotArray(\n value: unknown,\n path: DefinitionPath,\n): DataSnapshot<readonly unknown[]> {\n return snapshotArrayValue<unknown>(\n value,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n );\n}\n\ntype MemberSnapshot<T> = (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n) => DataSnapshot<T>;\n\nfunction snapshotArrayValue<T>(\n value: unknown,\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n try {\n if (!Array.isArray(value)) {\n return {\n ok: false,\n reason: \"not-array\",\n path,\n received: describeReceived(value),\n };\n }\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotArrayMembers(value, path, member, ancestors);\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotArrayMembers<T>(\n value: readonly unknown[],\n path: DefinitionPath,\n member: MemberSnapshot<T>,\n ancestors: Set<object>,\n): DataSnapshot<readonly T[]> {\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n let lengthDescriptor: PropertyDescriptor | undefined;\n try {\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (prototype !== Array.prototype) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"array\",\n received: \"array of another prototype or realm\",\n };\n }\n const length: unknown = lengthDescriptor?.value;\n if (\n typeof length !== \"number\" ||\n !Number.isSafeInteger(length) ||\n length < 0\n ) {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n for (const key of keys) {\n if (key === \"length\") continue;\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (!CANONICAL_INDEX.test(key) || Number(key) >= length) {\n return { ok: false, reason: \"array-property\", path: [...path, key], key };\n }\n }\n const elements: T[] = [];\n for (let index = 0; index < length; index += 1) {\n const elementPath = [...path, index];\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, index);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: elementPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"sparse\", path: elementPath, key: index };\n }\n const propertyValue = dataPropertyValue(descriptor, index, elementPath);\n if (!propertyValue.ok) return propertyValue;\n const element = member(propertyValue.value, elementPath, ancestors);\n if (!element.ok) return element;\n elements.push(element.value);\n }\n return { ok: true, value: Object.freeze(elements) };\n}\n\nexport function snapshotRecord(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: unknown }> {\n return snapshotPlainObject<unknown>(\n value,\n allowedKeys,\n path,\n (member) => ({ ok: true, value: member }),\n new Set(),\n ignoredKeys,\n );\n}\n\nfunction snapshotPlainObject<T>(\n value: unknown,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[] = [],\n): DataSnapshot<{ readonly [key: string]: T }> {\n if (value === null || typeof value !== \"object\") {\n return {\n ok: false,\n reason: \"not-record\",\n path,\n received: describeReceived(value),\n };\n }\n if (ancestors.has(value)) {\n return { ok: false, reason: \"cycle\", path };\n }\n ancestors.add(value);\n try {\n return snapshotPlainObjectMembers(\n value,\n allowedKeys,\n path,\n member,\n ancestors,\n ignoredKeys,\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction snapshotPlainObjectMembers<T>(\n value: object,\n allowedKeys: readonly string[] | undefined,\n path: DefinitionPath,\n member: (\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n ) => DataSnapshot<T>,\n ancestors: Set<object>,\n ignoredKeys: readonly string[],\n): DataSnapshot<{ readonly [key: string]: T }> {\n let isArray: boolean;\n let prototype: unknown;\n let keys: readonly (string | symbol)[];\n try {\n isArray = Array.isArray(value);\n prototype = Object.getPrototypeOf(value);\n keys = Reflect.ownKeys(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n if (isArray) {\n return { ok: false, reason: \"not-record\", path, received: \"array\" };\n }\n if (prototype !== Object.prototype && prototype !== null) {\n return {\n ok: false,\n reason: \"custom-prototype\",\n path,\n expected: \"record\",\n received: \"object\",\n };\n }\n const entries: [string, T][] = [];\n for (const key of keys) {\n if (typeof key === \"symbol\") {\n return { ok: false, reason: \"symbol-key\", path, key };\n }\n if (ignoredKeys.includes(key)) continue;\n const memberPath = [...path, key];\n if (allowedKeys !== undefined && !allowedKeys.includes(key)) {\n return {\n ok: false,\n reason: \"unknown-key\",\n path: memberPath,\n key,\n allowedKeys,\n };\n }\n let descriptor: PropertyDescriptor | undefined;\n try {\n descriptor = Object.getOwnPropertyDescriptor(value, key);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n if (descriptor === undefined) {\n return { ok: false, reason: \"inspection-failed\", path: memberPath };\n }\n const propertyValue = dataPropertyValue(descriptor, key, memberPath);\n if (!propertyValue.ok) return propertyValue;\n const snapshot = member(propertyValue.value, memberPath, ancestors);\n if (!snapshot.ok) return snapshot;\n entries.push([key, snapshot.value]);\n }\n // `Object.fromEntries` defines own properties, so an own \"__proto__\" key stays\n // an own key instead of silently becoming the prototype as plain assignment would.\n return { ok: true, value: Object.freeze(Object.fromEntries(entries)) };\n}\n\nfunction dataPropertyValue(\n descriptor: PropertyDescriptor,\n key: string | number,\n path: DefinitionPath,\n): DataSnapshot<unknown> {\n if (!(\"value\" in descriptor)) {\n return { ok: false, reason: \"accessor\", path, key };\n }\n if (!descriptor.enumerable) {\n return { ok: false, reason: \"non-enumerable\", path, key };\n }\n const value: unknown = descriptor.value;\n return { ok: true, value };\n}\n\nfunction snapshotDataValue(\n value: unknown,\n path: DefinitionPath,\n ancestors: Set<object>,\n): DataSnapshot<DataValue> {\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"undefined\":\n return { ok: true, value };\n case \"function\":\n return { ok: false, reason: \"not-data\", path, received: \"function\" };\n case \"symbol\":\n return { ok: false, reason: \"not-data\", path, received: \"symbol\" };\n case \"object\": {\n if (value === null) return { ok: true, value };\n let isArray: boolean;\n try {\n isArray = Array.isArray(value);\n } catch {\n return { ok: false, reason: \"inspection-failed\", path };\n }\n return isArray\n ? snapshotArrayValue(value, path, snapshotDataValue, ancestors)\n : snapshotPlainObject(\n value,\n undefined,\n path,\n snapshotDataValue,\n ancestors,\n );\n }\n }\n}\n","import { defineDiagnosticCatalog } from \"./diagnostics.js\";\n\nexport const kernelDiagnostics = defineDiagnosticCatalog({\n \"PH-DEF-OPTION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An option is malformed: wrong type, accessor, symbol key, non-plain object, an explicit undefined or non-JSON default, or an @equals pattern the generator cannot write\",\n },\n \"PH-DEF-COMPATIBILITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies\",\n },\n});\n","import { kernelDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRelatedLocation,\n DirectiveUseDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLEnumValueDefinitionNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n GraphQLTypeSystemDefinitionNode,\n GraphQLTypeSystemExtensionNode,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n SchemaFirstGraphQLDocumentCompatibility,\n} from \"@powerhousedao/shared/document-model\";\nimport { rejectionReceived, snapshotRecord } from \"./data-properties.js\";\nimport { describeReceived } from \"./diagnostics.js\";\nimport { equalsPatternProblem } from \"./equals-pattern.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"./primitives.js\";\nimport { printTypeReference } from \"./printer.js\";\n\nconst AST_KINDS = {\n object: \"ObjectTypeDefinition\",\n interface: \"InterfaceTypeDefinition\",\n enum: \"EnumTypeDefinition\",\n union: \"UnionTypeDefinition\",\n input: \"InputObjectTypeDefinition\",\n} as const satisfies Record<NamedGraphQLTypeDefinition[\"kind\"], string>;\n\ntype NamedDefinitionKind = (typeof AST_KINDS)[keyof typeof AST_KINDS];\n\ntype NamedDefinitionNode = Extract<\n GraphQLTypeSystemDefinitionNode,\n { readonly kind: NamedDefinitionKind }\n>;\n\ntype NamedAstDefinition = {\n readonly kind: NamedDefinitionKind;\n readonly name: { readonly value: string };\n readonly description?: GraphQLStringValueNode;\n readonly directives?: readonly GraphQLDirectiveNode[];\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n readonly fields?: readonly (\n | GraphQLFieldDefinitionNode\n | GraphQLInputValueDefinitionNode\n )[];\n readonly values?: readonly GraphQLEnumValueDefinitionNode[];\n readonly types?: readonly { readonly name: { readonly value: string } }[];\n};\n\nconst EXTENSION_TARGETS = {\n ObjectTypeExtension: \"ObjectTypeDefinition\",\n InterfaceTypeExtension: \"InterfaceTypeDefinition\",\n EnumTypeExtension: \"EnumTypeDefinition\",\n UnionTypeExtension: \"UnionTypeDefinition\",\n InputObjectTypeExtension: \"InputObjectTypeDefinition\",\n} as const satisfies Record<string, NamedDefinitionKind>;\n\ntype NamedExtensionNode = Extract<\n GraphQLTypeSystemExtensionNode,\n { readonly kind: keyof typeof EXTENSION_TARGETS }\n>;\n\nconst KIND_SPELLING: Record<\n NamedDefinitionKind | \"ScalarTypeDefinition\",\n { readonly noun: string; readonly keyword: string }\n> = {\n ScalarTypeDefinition: { noun: \"a scalar\", keyword: \"scalar\" },\n ObjectTypeDefinition: { noun: \"an object type\", keyword: \"type\" },\n InterfaceTypeDefinition: { noun: \"an interface\", keyword: \"interface\" },\n EnumTypeDefinition: { noun: \"an enum\", keyword: \"enum\" },\n UnionTypeDefinition: { noun: \"a union\", keyword: \"union\" },\n InputObjectTypeDefinition: { noun: \"an input\", keyword: \"input\" },\n};\n\nconst MEMBER_LISTS = [\"fields\", \"values\", \"interfaces\", \"types\"] as const;\n\ntype MemberList = (typeof MEMBER_LISTS)[number];\n\ntype Member = { readonly name: { readonly value: string } };\n\ntype EffectiveTypeDefinition = {\n readonly node: NamedAstDefinition;\n readonly index: number;\n readonly contributors: ReadonlyMap<`${MemberList}:${string}`, number>;\n};\n\ntype FoldedTypeDefinitions = {\n readonly types: ReadonlyMap<string, EffectiveTypeDefinition>;\n readonly redefinitions: readonly {\n readonly name: string;\n readonly index: number;\n }[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\ntype TypeUnderFold = {\n readonly base: Omit<NamedAstDefinition, \"kind\">;\n readonly kind: NamedDefinitionKind;\n readonly index: number;\n readonly contributors: Map<`${MemberList}:${string}`, number>;\n readonly lists: Partial<Record<MemberList, Member[]>>;\n readonly directives: GraphQLDirectiveNode[];\n};\n\nfunction isNamedDefinition(node: {\n readonly kind: string;\n}): node is NamedDefinitionNode {\n return Object.values(AST_KINDS).includes(node.kind as NamedDefinitionKind);\n}\n\nfunction isNamedExtension(node: {\n readonly kind: string;\n}): node is NamedExtensionNode {\n return Object.hasOwn(EXTENSION_TARGETS, node.kind);\n}\n\nfunction foldTypeExtensions(\n definitions: LocationFreeGraphQLDocumentNode[\"definitions\"],\n path: DefinitionPath,\n): FoldedTypeDefinitions {\n const types = new Map<string, TypeUnderFold>();\n const redefinitions: { name: string; index: number }[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n const memberPath = (index: number, list: MemberList, name: string) => [\n ...path,\n \"definitions\",\n index,\n list,\n name,\n ];\n const addMembers = (\n target: TypeUnderFold,\n node: Partial<Record<MemberList, readonly Member[]>>,\n index: number,\n ): void => {\n for (const list of MEMBER_LISTS) {\n const members = node[list];\n if (members === undefined) continue;\n for (const member of members) {\n const name = member.name.value;\n const key = `${list}:${name}` as const;\n const first = target.contributors.get(key);\n if (first !== undefined) {\n const coordinate = `${target.base.name.value}.${name}`;\n diagnostics.push(\n compatibilityDiagnostic(\n memberPath(index, list, name),\n `${coordinate} is defined more than once.`,\n {\n expected: \"one definition per member\",\n received: \"a second definition\",\n repair: `Remove the repeated ${name}; the host rejects a member defined twice.`,\n related: [\n {\n path: memberPath(first, list, name),\n message: `${coordinate} is first defined here.`,\n },\n ],\n },\n ),\n );\n continue;\n }\n target.contributors.set(key, index);\n target.lists[list]?.push(member);\n }\n }\n };\n const start = (\n node: Omit<NamedAstDefinition, \"kind\">,\n kind: NamedDefinitionKind,\n index: number,\n ): TypeUnderFold => {\n const folding: TypeUnderFold = {\n base: node,\n kind,\n index,\n contributors: new Map(),\n lists: Object.fromEntries(\n MEMBER_LISTS.filter((list) => node[list] !== undefined).map((list) => [\n list,\n [],\n ]),\n ),\n directives: [...(node.directives ?? [])],\n };\n addMembers(folding, node, index);\n return folding;\n };\n\n const scalars = new Set<string>();\n const wrongKind = (\n index: number,\n name: string,\n defined: keyof typeof KIND_SPELLING,\n extension: { readonly kind: string },\n extendedAs: keyof typeof KIND_SPELLING,\n ): void => {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"definitions\", index],\n `${name} is ${KIND_SPELLING[defined].noun}, so it cannot be extended as ${KIND_SPELLING[extendedAs].noun}.`,\n {\n expected: defined.replace(\"Definition\", \"Extension\"),\n received: extension.kind,\n repair: `Extend ${name} with \"extend ${KIND_SPELLING[defined].keyword}\", or remove the extension; the host rejects an extension of a different kind.`,\n },\n ),\n );\n };\n const foldScalarExtensions = (\n foldedTypes: ReadonlyMap<string, TypeUnderFold>,\n ): void => {\n definitions.forEach((node, index) => {\n if (node.kind !== \"ScalarTypeExtension\") return;\n const target = foldedTypes.get(node.name.value);\n if (target !== undefined) {\n wrongKind(\n index,\n node.name.value,\n target.kind,\n node,\n \"ScalarTypeDefinition\",\n );\n }\n });\n };\n\n definitions.forEach((node, index) => {\n if (node.kind === \"ScalarTypeDefinition\") {\n scalars.add(\n (node as GraphQLTypeSystemDefinitionNode & Member).name.value,\n );\n return;\n }\n if (!isNamedDefinition(node)) return;\n const name = node.name.value;\n if (types.has(name)) {\n redefinitions.push({ name, index });\n return;\n }\n types.set(name, start(node, node.kind, index));\n });\n\n definitions.forEach((node, index) => {\n if (!isNamedExtension(node)) return;\n const kind = EXTENSION_TARGETS[node.kind];\n const name = node.name.value;\n const target = types.get(name);\n if (target === undefined) {\n if (scalars.has(name)) {\n wrongKind(index, name, \"ScalarTypeDefinition\", node, kind);\n return;\n }\n types.set(name, start(node, kind, index));\n return;\n }\n if (target.kind !== kind) {\n wrongKind(index, name, target.kind, node, kind);\n return;\n }\n target.directives.push(...node.directives);\n addMembers(target, node, index);\n });\n\n foldScalarExtensions(types);\n\n return {\n types: new Map(\n [...types].map(\n ([name, { base, kind, index, contributors, lists, directives }]) => [\n name,\n {\n node: { ...base, kind, directives, ...lists } as NamedAstDefinition,\n index,\n contributors,\n },\n ],\n ),\n ),\n redefinitions,\n diagnostics,\n };\n}\n\nfunction compatibilityDiagnostic(\n path: DefinitionPath,\n message: string,\n detail: {\n readonly expected?: string;\n readonly received?: string;\n readonly repair?: string;\n readonly related?: readonly DefinitionRelatedLocation[];\n } = {},\n): DefinitionDiagnostic {\n return kernelDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n path,\n message,\n ...(detail.expected !== undefined && { expected: detail.expected }),\n ...(detail.received !== undefined && { received: detail.received }),\n ...(detail.related !== undefined && { related: detail.related }),\n repair:\n detail.repair ??\n \"Regenerate the compatibility AST from the schema this declaration replaces, or change the descriptors to agree with it.\",\n });\n}\n\nconst ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;\n\nexport function validateLocationFreeDocument(\n value: unknown,\n path: DefinitionPath,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const refuse = (at: DefinitionPath, message: string, received: string) =>\n diagnostics.push(\n compatibilityDiagnostic(at, message, {\n expected: \"JSON data\",\n received,\n repair:\n \"Keep only JSON data in the AST: strings, finite numbers, booleans, null, plain arrays and plain objects with data properties.\",\n }),\n );\n const ancestors = new Set<object>();\n const visitProperty = (\n owner: object,\n key: string | number,\n at: DefinitionPath,\n ): void => {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n if (descriptor === undefined) {\n refuse(at, \"A compatibility AST array must not have holes.\", \"hole\");\n } else if (!(\"value\" in descriptor)) {\n refuse(\n at,\n \"A compatibility AST must hold data properties, not accessors.\",\n \"accessor\",\n );\n } else {\n visit(descriptor.value, at);\n }\n };\n const visit = (node: unknown, at: DefinitionPath): void => {\n if (\n node === null ||\n typeof node === \"string\" ||\n typeof node === \"boolean\"\n ) {\n return;\n }\n if (typeof node === \"number\") {\n if (!Number.isFinite(node)) {\n refuse(at, \"A compatibility AST number must be finite.\", String(node));\n }\n return;\n }\n if (typeof node !== \"object\") {\n refuse(\n at,\n `A compatibility AST must contain JSON data only, received ${typeof node}.`,\n typeof node,\n );\n return;\n }\n if (ancestors.has(node)) {\n refuse(at, \"A compatibility AST must not contain a cycle.\", \"cycle\");\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(node);\n const isArray = Array.isArray(node);\n if (\n isArray\n ? prototype !== Array.prototype\n : prototype !== Object.prototype && prototype !== null\n ) {\n refuse(\n at,\n \"A compatibility AST must hold plain arrays and plain objects only.\",\n describeReceived(node),\n );\n return;\n }\n ancestors.add(node);\n for (const key of Reflect.ownKeys(node)) {\n if (typeof key === \"symbol\") {\n refuse(at, \"A compatibility AST must not have symbol keys.\", \"symbol\");\n } else if (isArray) {\n if (key !== \"length\" && !ARRAY_INDEX.test(key)) {\n refuse(\n [...at, key],\n \"A compatibility AST array must hold only its items.\",\n key,\n );\n }\n } else if (key === \"loc\") {\n diagnostics.push(\n compatibilityDiagnostic(\n [...at, key],\n \"A compatibility AST must be location free.\",\n {\n expected: \"no loc property\",\n received: \"loc\",\n repair: \"Strip every loc property from the AST.\",\n },\n ),\n );\n } else {\n visitProperty(node, key, [...at, key]);\n }\n }\n if (isArray) {\n for (let index = 0; index < node.length; index += 1) {\n visitProperty(node, index, [...at, index]);\n }\n }\n ancestors.delete(node);\n };\n visit(value, path);\n return diagnostics;\n}\n\nfunction printAstType(node: GraphQLTypeNode): string {\n switch (node.kind) {\n case \"NamedType\":\n return node.name.value;\n case \"ListType\":\n return `[${printAstType(node.type)}]`;\n case \"NonNullType\":\n return `${printAstType(node.type)}!`;\n }\n}\n\nfunction astValue(node: GraphQLConstValueNode): JsonValue {\n switch (node.kind) {\n case \"IntValue\":\n case \"FloatValue\":\n return Number(node.value);\n case \"StringValue\":\n case \"EnumValue\":\n return node.value;\n case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(astValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, astValue(field.value)]),\n );\n }\n}\n\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nfunction astDeprecation(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const directive = (directives ?? []).find(\n (candidate) => candidate.name.value === \"deprecated\",\n );\n if (directive === undefined) return null;\n const reason = directive.arguments.find(\n (argument) => argument.name.value === \"reason\",\n );\n if (reason === undefined) return DEFAULT_DEPRECATION_REASON;\n return reason.value.kind === \"StringValue\" ? reason.value.value : null;\n}\n\nfunction astEquals(\n directives: readonly GraphQLDirectiveNode[] | undefined,\n): string | null {\n const value = (directives ?? [])\n .find((directive) => directive.name.value === \"equals\")\n ?.arguments.find((argument) => argument.name.value === \"value\")?.value;\n return value !== undefined &&\n \"value\" in value &&\n typeof value.value === \"string\"\n ? value.value\n : null;\n}\n\nfunction definitionEquals(field: {\n readonly directives?: readonly DirectiveUseDefinition[];\n}): string | null {\n const value = field.directives\n ?.find((directive) => directive.name === \"equals\")\n ?.arguments.find((argument) => argument.name === \"value\")?.value;\n return typeof value === \"string\" ? value : null;\n}\n\nfunction printEquals(equals: string | null): string {\n return equals === null\n ? \"no @equals\"\n : `@equals(value: ${JSON.stringify(equals)})`;\n}\n\ntype FieldFingerprint = {\n readonly name: string;\n readonly type: string;\n readonly defaultValue: string | null;\n readonly description: string | null;\n readonly deprecated: string | null;\n readonly equals: string | null;\n};\n\ntype TypeFingerprint = {\n readonly kind: string;\n readonly name: string;\n readonly description: string | null;\n readonly implemented: readonly string[];\n readonly fields: readonly FieldFingerprint[];\n readonly members: readonly string[];\n};\n\nfunction descriptorFingerprint(\n definition: NamedGraphQLTypeDefinition,\n): TypeFingerprint {\n const fields =\n definition.kind === \"enum\"\n ? definition.values.map((value): FieldFingerprint => ({\n name: value.name,\n type: \"\",\n defaultValue: null,\n description: value.description,\n deprecated: value.deprecated,\n equals: null,\n }))\n : definition.kind === \"union\"\n ? []\n : definition.kind === \"input\" && definition.fields.length === 0\n ? [\n {\n name: EMPTY_INPUT_FIELD_NAME,\n type: \"Boolean\",\n defaultValue: null,\n description: null,\n deprecated: null,\n equals: null,\n },\n ]\n : definition.fields.map((field): FieldFingerprint => {\n const hasDefault = Object.hasOwn(field, \"defaultValue\");\n return {\n name: field.name,\n type: printTypeReference(field.type),\n defaultValue: hasDefault\n ? canonicalJson(\n (field as { readonly defaultValue: JsonValue })\n .defaultValue,\n )\n : null,\n description: field.description,\n deprecated: field.deprecated,\n equals: definitionEquals(field),\n };\n });\n return {\n kind: AST_KINDS[definition.kind],\n name: definition.name,\n description: definition.description,\n implemented:\n definition.kind === \"object\" || definition.kind === \"interface\"\n ? (definition.implements ?? [])\n : [],\n fields,\n members: definition.kind === \"union\" ? definition.members : [],\n };\n}\n\nfunction astFingerprint(node: NamedAstDefinition): TypeFingerprint {\n const fields =\n node.kind === AST_KINDS.enum\n ? (node.values ?? []).map((value): FieldFingerprint => ({\n name: value.name.value,\n type: \"\",\n defaultValue: null,\n description: value.description?.value ?? null,\n deprecated: astDeprecation(value.directives),\n equals: null,\n }))\n : (node.fields ?? []).map((field): FieldFingerprint => {\n const defaultValue = (field as GraphQLInputValueDefinitionNode)\n .defaultValue;\n return {\n name: field.name.value,\n type: printAstType(field.type),\n defaultValue:\n defaultValue === undefined\n ? null\n : canonicalJson(astValue(defaultValue)),\n description: field.description?.value ?? null,\n deprecated: astDeprecation(field.directives),\n equals: astEquals(field.directives),\n };\n });\n return {\n kind: node.kind,\n name: node.name.value,\n description: node.description?.value ?? null,\n implemented: (node.interfaces ?? []).map(\n (implemented) => implemented.name.value,\n ),\n fields,\n members: (node.types ?? []).map((member) => member.name.value),\n };\n}\n\ntype ExtensionSource = {\n readonly documentPath: DefinitionPath;\n readonly effective: EffectiveTypeDefinition;\n};\n\nfunction missingMemberRepair(\n kind: NamedDefinitionKind,\n typeName: string,\n member: string,\n): string {\n switch (kind) {\n case \"EnumTypeDefinition\":\n return `Add the value \"${member}\" to the definition of enum ${typeName}.`;\n case \"UnionTypeDefinition\":\n return `Add the member ${member} to the definition of union ${typeName}.`;\n default:\n return `Add a \"${member}\" field to the definition of ${typeName}.`;\n }\n}\n\nfunction compareFields(\n descriptor: TypeFingerprint,\n ast: TypeFingerprint,\n path: DefinitionPath,\n memberNoun: \"field\" | \"enum value\",\n source: ExtensionSource,\n): readonly DefinitionDiagnostic[] {\n const diagnostics: DefinitionDiagnostic[] = [];\n const astFields = new Map(ast.fields.map((field) => [field.name, field]));\n const list: MemberList = memberNoun === \"enum value\" ? \"values\" : \"fields\";\n for (const field of descriptor.fields) {\n const match = astFields.get(field.name);\n if (match === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, field.name],\n `${descriptor.name}.${field.name} is declared by the descriptors and absent from the compatibility AST.`,\n {\n expected: `${memberNoun} ${field.name}`,\n received: \"absent\",\n },\n ),\n );\n continue;\n }\n astFields.delete(field.name);\n const contributor = source.effective.contributors.get(\n `${list}:${field.name}`,\n );\n const coordinate =\n contributor === undefined || contributor === source.effective.index\n ? [...path, field.name]\n : [\n ...source.documentPath,\n \"definitions\",\n contributor,\n list,\n field.name,\n ];\n if (field.type !== match.type) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"type\"],\n `${descriptor.name}.${field.name} has a different type in the compatibility AST.`,\n { expected: field.type, received: match.type },\n ),\n );\n }\n if (field.defaultValue !== match.defaultValue) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"defaultValue\"],\n `${descriptor.name}.${field.name} has a different default value in the compatibility AST.`,\n {\n expected: field.defaultValue ?? \"no default\",\n received: match.defaultValue ?? \"no default\",\n repair: `Remove the default from the compatibility AST, or declare a defaultValue the field's type accepts on the descriptor field ${descriptor.name}.${field.name}.`,\n },\n ),\n );\n }\n if (field.description !== match.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${descriptor.name}.${field.name} has a different description in the compatibility AST.`,\n {\n expected: field.description ?? \"no description\",\n received: match.description ?? \"no description\",\n },\n ),\n );\n }\n if (field.deprecated !== match.deprecated) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"deprecated\"],\n `${descriptor.name}.${field.name} has a different deprecation in the compatibility AST.`,\n {\n expected: field.deprecated ?? \"not deprecated\",\n received: match.deprecated ?? \"not deprecated\",\n },\n ),\n );\n }\n const astProblem =\n match.equals === null ? undefined : equalsPatternProblem(match.equals);\n if (match.equals !== null && astProblem !== undefined) {\n diagnostics.push(\n kernelDiagnostics.create({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...coordinate, \"equals\"],\n received: match.equals,\n ...astProblem,\n }),\n );\n } else if (field.equals !== match.equals) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"equals\"],\n `${descriptor.name}.${field.name} has a different @equals in the compatibility AST.`,\n {\n expected: printEquals(field.equals),\n received: printEquals(match.equals),\n repair:\n match.equals === null\n ? `Remove @equals from the definition of ${descriptor.name}.${field.name}, or add ${printEquals(field.equals)} to the field in the AST.`\n : `Give the definition of ${descriptor.name}.${field.name} ${printEquals(match.equals)}.`,\n },\n ),\n );\n }\n }\n for (const extra of astFields.keys()) {\n const received = `${memberNoun} ${extra}`;\n diagnostics.push(\n extensionMemberDiagnostic(\n descriptor.name,\n list,\n extra,\n received,\n source,\n ) ??\n compatibilityDiagnostic(\n [...path, extra],\n `${descriptor.name}.${extra} is in the compatibility AST and not in the descriptors.`,\n { expected: \"absent\", received },\n ),\n );\n }\n return diagnostics;\n}\n\nfunction extensionMemberDiagnostic(\n typeName: string,\n list: MemberList,\n member: string,\n received: string,\n { documentPath, effective }: ExtensionSource,\n): DefinitionDiagnostic | undefined {\n const index = effective.contributors.get(`${list}:${member}`);\n if (index === undefined || index === effective.index) return undefined;\n const keyword = KIND_SPELLING[effective.node.kind].keyword;\n return compatibilityDiagnostic(\n [...documentPath, \"definitions\", index, list, member],\n `${typeName}.${member} is added by \"extend ${keyword} ${typeName}\" and missing from the descriptors.`,\n {\n expected: \"absent\",\n received,\n repair: missingMemberRepair(effective.node.kind, typeName, member),\n },\n );\n}\n\nfunction refusedV1Member(record: {\n readonly [key: string]: unknown;\n}): { readonly member: string; readonly received: string } | undefined {\n if (record.kind !== \"graphql-ast-v1\") {\n return { member: \"kind\", received: spelledMember(record.kind) };\n }\n if (record.preserveDefinitionOrder !== true) {\n return {\n member: \"preserveDefinitionOrder\",\n received: spelledMember(record.preserveDefinitionOrder),\n };\n }\n return undefined;\n}\n\nfunction spelledMember(value: unknown): string {\n return typeof value === \"string\" || typeof value === \"boolean\"\n ? String(value)\n : describeReceived(value);\n}\n\nfunction sameMembers(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return (\n canonicalJson([...left].sort(compareCodeUnits)) ===\n canonicalJson([...right].sort(compareCodeUnits))\n );\n}\n\nfunction dataProperty(owner: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : undefined;\n}\n\nfunction rootOperationTypeNames(\n document: LocationFreeGraphQLDocumentNode,\n): ReadonlySet<string> {\n const names = new Set<string>([\"Query\", \"Mutation\", \"Subscription\"]);\n for (const node of document.definitions) {\n if (node.kind !== \"SchemaDefinition\" && node.kind !== \"SchemaExtension\") {\n continue;\n }\n for (const operationType of node.operationTypes) {\n names.add(operationType.type.name.value);\n }\n }\n return names;\n}\n\nexport function checkGraphQLDocumentAgreement(options: {\n readonly compatibility: SchemaFirstGraphQLDocumentCompatibility;\n readonly definitions: readonly NamedGraphQLTypeDefinition[];\n readonly path: DefinitionPath;\n}): readonly DefinitionDiagnostic[] {\n const { definitions, path } = options;\n const compatibility = snapshotRecord(options.compatibility, undefined, path);\n const refuse = (at: DefinitionPath, received: string) => [\n compatibilityDiagnostic(\n at,\n \"A GraphQL compatibility declaration must be a V1 location-free document with preserveDefinitionOrder.\",\n {\n expected: 'kind \"graphql-ast-v1\" with preserveDefinitionOrder: true',\n received,\n repair:\n 'Pass a location-free GraphQL document as { kind: \"graphql-ast-v1\", document, preserveDefinitionOrder: true }.',\n },\n ),\n ];\n if (!compatibility.ok) {\n return refuse(compatibility.path, rejectionReceived(compatibility));\n }\n const refused = refusedV1Member(compatibility.value);\n if (refused !== undefined) {\n return refuse([...path, refused.member], refused.received);\n }\n const document: unknown = compatibility.value.document;\n if (\n document === null ||\n typeof document !== \"object\" ||\n dataProperty(document, \"kind\") !== \"Document\" ||\n !Array.isArray(dataProperty(document, \"definitions\"))\n ) {\n return [\n compatibilityDiagnostic(\n [...path, \"document\"],\n \"A GraphQL compatibility document must be a location-free Document node.\",\n {\n expected: 'a { kind: \"Document\", definitions: [...] } node',\n received: describeReceived(document),\n },\n ),\n ];\n }\n const shape = validateLocationFreeDocument(document, [...path, \"document\"]);\n if (shape.length > 0) return shape;\n const validated = document as LocationFreeGraphQLDocumentNode;\n\n const documentPath = [...path, \"document\"];\n const folded = foldTypeExtensions(validated.definitions, documentPath);\n const diagnostics: DefinitionDiagnostic[] = [\n ...folded.redefinitions.map(({ name }) =>\n compatibilityDiagnostic(\n [...documentPath, name],\n `The compatibility AST defines ${name} twice.`,\n { expected: \"one definition per type name\", received: \"two\" },\n ),\n ),\n ...folded.diagnostics,\n ];\n\n const compared = new Set<string>();\n for (const definition of definitions) {\n if (compared.has(definition.name)) continue;\n compared.add(definition.name);\n const coordinate = [...path, \"document\", definition.name];\n const effective = folded.types.get(definition.name);\n if (effective === undefined) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is declared by the descriptors and absent from the compatibility AST.`,\n { expected: definition.name, received: \"absent\" },\n ),\n );\n continue;\n }\n const descriptor = descriptorFingerprint(definition);\n const ast = astFingerprint(effective.node);\n if (descriptor.kind !== ast.kind) {\n diagnostics.push(\n compatibilityDiagnostic(\n coordinate,\n `${definition.name} is a different kind of type in the compatibility AST.`,\n { expected: descriptor.kind, received: ast.kind },\n ),\n );\n continue;\n }\n if (descriptor.description !== ast.description) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"description\"],\n `${definition.name} has a different description in the compatibility AST.`,\n {\n expected: descriptor.description ?? \"no description\",\n received: ast.description ?? \"no description\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.implemented, ast.implemented)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"implements\"],\n `${definition.name} implements different interfaces in the compatibility AST.`,\n {\n expected: descriptor.implemented.join(\" & \") || \"none\",\n received: ast.implemented.join(\" & \") || \"none\",\n },\n ),\n );\n }\n if (!sameMembers(descriptor.members, ast.members)) {\n diagnostics.push(\n compatibilityDiagnostic(\n [...coordinate, \"members\"],\n `${definition.name} has different union members in the compatibility AST.`,\n {\n expected: descriptor.members.join(\" | \") || \"none\",\n received: ast.members.join(\" | \") || \"none\",\n },\n ),\n );\n }\n diagnostics.push(\n ...compareFields(\n descriptor,\n ast,\n [...coordinate, definition.kind === \"enum\" ? \"values\" : \"fields\"],\n definition.kind === \"enum\" ? \"enum value\" : \"field\",\n { documentPath, effective },\n ),\n );\n }\n\n const rootTypes = rootOperationTypeNames(validated);\n for (const [name, { node }] of folded.types) {\n if (compared.has(name) || rootTypes.has(name)) continue;\n diagnostics.push(\n compatibilityDiagnostic(\n [...path, \"document\", name],\n `The compatibility AST declares ${name}, which no descriptor represents.`,\n {\n expected: \"a descriptor for every named type in the AST\",\n received: node.kind,\n repair: `Add a definition for ${name}, or remove it from the AST.`,\n },\n ),\n );\n }\n return diagnostics;\n}\n","import { kernelDiagnostics } from \"../kernel/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const dslDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DEF-FIELD-OPTION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field use contains an option its builder or its position does not support\",\n },\n \"PH-DEF-TYPE-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A named type is used as a field without ph.ref\",\n },\n \"PH-DEF-NAME-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An authored GraphQL type, field, or enum value name is lexically invalid or reserved\",\n },\n \"PH-DEF-FIELD-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field position holds a value that is neither a field use nor a named type\",\n },\n \"PH-DEF-REFERENCE-TARGET-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input\",\n },\n \"PH-DEF-ENUM-VALUES-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An enum declares no values, a duplicate value, or a reserved value\",\n },\n \"PH-DEF-UNION-MEMBERS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A union declares no members, a duplicate member, or a member that is not a ph.object\",\n },\n \"PH-DEF-IMPLEMENTS-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or an interface implements something that is not a ph.interface, or the same interface twice\",\n },\n \"PH-SCALAR-FACTORY-AS-FIELD\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scalar field-use factory is used as a field without being called\",\n },\n \"PH-SCALAR-INTERNAL\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A field uses a catalog scalar that only the reactor host declares, such as JSONObject\",\n },\n \"PH-SCALAR-DEFINITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"ph.scalar received a value that is not a scalar definition of this release's format\",\n },\n },\n kernelDiagnostics,\n);\n\nexport type DslDiagnosticCode = keyof typeof dslDiagnostics.codes;\n","import { dslDiagnostics } from \"../dsl/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const compilerDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ACTION\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two operations derive the same persisted action type, or an operation derives one the document runtime owns\",\n },\n \"PH-DM-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two declarations derive the same module, GraphQL type, or creator name\",\n },\n \"PH-DM-IDENTITY-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An identity segment, compatibility ID, or derived UUID violates the V1 contract\",\n },\n \"PH-DM-DECLARATION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged\",\n },\n \"PH-DM-DEFAULT-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A document state field declares a GraphQL default value\",\n },\n \"PH-DM-INTERFACE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An object or interface does not satisfy an implemented interface's fields or ancestor requirements\",\n },\n \"PH-DM-INPUT-CYCLE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type contains itself through singular non-null input fields, so no finite value satisfies it\",\n },\n \"PH-DM-TYPE-POSITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"An input type is referenced from an output position, or an output type from an input position\",\n },\n \"PH-DM-INITIAL-VALUE-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A scope initial value cannot produce a stored JSON string, or its own state validator rejects it\",\n },\n \"PH-SCALAR-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"Two different project scalars of one model claim one name\",\n },\n },\n dslDiagnostics,\n);\n\nexport type CompilerDiagnosticCode = keyof typeof compilerDiagnostics.codes;\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n JsonValue,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars, scalarCatalog } from \"../../scalars/catalog.js\";\nimport { DefinitionDiagnosticCollector } from \"../kernel/diagnostic-collector.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport { describeReceived } from \"../kernel/diagnostics.js\";\nimport { validateLocationFreeDocument } from \"../kernel/graphql-ast.js\";\nimport { canonicalJson, isGraphQLName } from \"../kernel/primitives.js\";\nimport {\n type CompilerDiagnosticCode,\n compilerDiagnostics,\n} from \"./diagnostic-codes.js\";\n\ntype Node = { readonly [key: string]: unknown };\n\nconst BUILT_IN_SCALARS = [\"ID\", \"String\", \"Boolean\", \"Int\", \"Float\"] as const;\nconst CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);\nconst MODEL_SCALARS: ReadonlySet<string> = new Set([\n ...BUILT_IN_SCALARS,\n ...CATALOG_SCALARS,\n]);\nconst HOST_ONLY_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog\n .map(({ name }) => name)\n .filter((name) => !MODEL_SCALARS.has(name)),\n);\nconst SCALAR_REPRESENTATIONS = [\n \"string\",\n \"number\",\n \"boolean\",\n \"json-object\",\n \"json\",\n \"opaque\",\n] as const;\n\nclass ShapeChecker {\n readonly collector =\n new DefinitionDiagnosticCollector<CompilerDiagnosticCode>(\n compilerDiagnostics,\n );\n\n packageScalars: ReadonlySet<string> = new Set();\n\n fail(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: unknown,\n ): undefined {\n this.collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received:\n typeof received === \"string\"\n ? received\n : typeof received === \"number\" || typeof received === \"boolean\"\n ? String(received)\n : describeReceived(received),\n repair:\n \"Produce the definition with materialize or a document-model/tooling adapter; a hand-edited wire definition is not accepted.\",\n });\n return undefined;\n }\n\n record(\n value: unknown,\n keys: readonly string[],\n path: DefinitionPath,\n ): Node | undefined {\n const snapshot = snapshotRecord(value, keys, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n `This node is not a plain object with the V1 members (${snapshot.reason}).`,\n keys.join(\", \"),\n rejectionReceived(snapshot),\n );\n }\n\n array(value: unknown, path: DefinitionPath): readonly unknown[] | undefined {\n const snapshot = snapshotArray(value, path);\n if (snapshot.ok) return snapshot.value;\n return this.fail(\n snapshot.path,\n \"This node must be an array.\",\n \"an array\",\n rejectionReceived(snapshot),\n );\n }\n\n string(value: unknown, path: DefinitionPath): string | undefined {\n if (typeof value === \"string\") return value;\n return this.fail(path, \"This member must be a string.\", \"string\", value);\n }\n\n nullableString(value: unknown, path: DefinitionPath): void {\n if (value === null || typeof value === \"string\") return;\n this.fail(\n path,\n \"This member must be a string or null.\",\n \"string | null\",\n value,\n );\n }\n\n literal(\n value: unknown,\n expected: string | number | boolean,\n path: DefinitionPath,\n ): void {\n if (value === expected) return;\n this.fail(path, \"This member has a fixed value.\", String(expected), value);\n }\n\n oneOf<T extends string>(\n value: unknown,\n allowed: readonly T[],\n path: DefinitionPath,\n ): T | undefined {\n if ((allowed as readonly unknown[]).includes(value)) return value as T;\n return this.fail(\n path,\n \"This member is outside its closed set.\",\n allowed.join(\" | \"),\n value,\n );\n }\n\n json(value: unknown, path: DefinitionPath): JsonValue | undefined {\n try {\n canonicalJson(value);\n } catch (error) {\n return this.fail(\n path,\n `This member must be a JSON value: ${error instanceof Error ? error.message : String(error)}`,\n \"a JSON value\",\n value,\n );\n }\n return value as JsonValue;\n }\n\n graphQLName(value: unknown, path: DefinitionPath): string | undefined {\n if (isGraphQLName(value)) return value;\n return this.fail(\n path,\n \"This member must be a GraphQL name.\",\n \"a GraphQL name\",\n value,\n );\n }\n\n rejectHostOnlyScalar(value: unknown, path: DefinitionPath): boolean {\n if (typeof value !== \"string\" || !HOST_ONLY_SCALARS.has(value)) {\n return false;\n }\n this.collector.add({\n code: \"PH-SCALAR-INTERNAL\",\n definition: { kind: \"scalar\", key: value },\n path,\n message: `${value} is internal to the reactor host. A document model cannot use it.`,\n received: value,\n repair:\n \"Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one.\",\n });\n return true;\n }\n}\n\nfunction typeReference(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const kind = (value as Node | null)?.kind;\n const node =\n kind === \"list\"\n ? check.record(value, [\"kind\", \"required\", \"item\"], path)\n : check.record(value, [\"kind\", \"name\", \"required\"], path);\n if (node === undefined) return;\n if (typeof node.required !== \"boolean\") {\n check.fail(\n [...path, \"required\"],\n \"A type reference records nullability.\",\n \"boolean\",\n node.required,\n );\n }\n if (kind === \"list\") {\n typeReference(check, node.item, [...path, \"item\"]);\n } else if (kind === \"scalar\") {\n if (check.rejectHostOnlyScalar(node.name, [...path, \"name\"])) return;\n if (\n typeof node.name !== \"string\" ||\n !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))\n ) {\n check.fail(\n [...path, \"name\"],\n \"A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.\",\n [...MODEL_SCALARS, ...check.packageScalars].join(\" | \"),\n node.name,\n );\n }\n } else if (kind === \"named\") {\n check.graphQLName(node.name, [...path, \"name\"]);\n } else {\n check.fail(\n [...path, \"kind\"],\n \"A type reference has three kinds.\",\n \"scalar | named | list\",\n kind,\n );\n }\n}\n\nfunction directiveUses(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n check.array(value, path)?.forEach((use, index) => {\n const node = check.record(use, [\"name\", \"arguments\"], [...path, index]);\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, index, \"name\"]);\n const args = check.array(node.arguments, [...path, index, \"arguments\"]);\n args?.forEach((argument, argumentIndex) => {\n const at = [...path, index, \"arguments\", argumentIndex];\n const entry = check.record(argument, [\"name\", \"value\"], at);\n if (entry === undefined) return;\n check.graphQLName(entry.name, [...at, \"name\"]);\n check.json(entry.value, [...at, \"value\"]);\n });\n });\n}\n\nconst FIELD_KEYS = [\"key\", \"name\", \"description\", \"deprecated\", \"type\"];\n\nfunction field(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n const node = check.record(\n value,\n [...FIELD_KEYS, \"directives\", input ? \"defaultValue\" : \"args\"],\n path,\n );\n if (node === undefined) return;\n check.string(node.key, [...path, \"key\"]);\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n typeReference(check, node.type, [...path, \"type\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n if (input) {\n if (Object.hasOwn(node, \"defaultValue\")) {\n check.json(node.defaultValue, [...path, \"defaultValue\"]);\n }\n } else if (node.args !== undefined) {\n check\n .array(node.args, [...path, \"args\"])\n ?.forEach((argument, index) =>\n field(check, argument, [...path, \"args\", index], true),\n );\n }\n}\n\nfunction fields(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n input: boolean,\n): void {\n check\n .array(value, path)\n ?.forEach((entry, index) => field(check, entry, [...path, index], input));\n}\n\nfunction enumValue(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\"name\", \"description\", \"deprecated\", \"directives\"],\n path,\n );\n if (node === undefined) return;\n check.graphQLName(node.name, [...path, \"name\"]);\n check.nullableString(node.description, [...path, \"description\"]);\n check.nullableString(node.deprecated, [...path, \"deprecated\"]);\n if (node.directives !== undefined) {\n directiveUses(check, node.directives, [...path, \"directives\"]);\n }\n}\n\nconst NAMED_TYPE_MEMBERS = {\n enum: \"values\",\n object: \"fields\",\n interface: \"fields\",\n input: \"fields\",\n union: \"members\",\n} as const;\n\nfunction namedType(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const kind = (value as Node | null)?.kind;\n if (typeof kind !== \"string\" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) {\n return check.fail(\n [...path, \"kind\"],\n \"A named type has five kinds.\",\n Object.keys(NAMED_TYPE_MEMBERS).join(\" | \"),\n kind,\n );\n }\n const typed = kind as keyof typeof NAMED_TYPE_MEMBERS;\n const member = NAMED_TYPE_MEMBERS[typed];\n const extra =\n typed === \"object\" || typed === \"interface\"\n ? [\"implements\"]\n : typed === \"input\"\n ? [\"unknownKeys\"]\n : [];\n const node = check.record(\n value,\n [\"kind\", \"name\", \"description\", ...extra, member],\n path,\n );\n if (node === undefined) return undefined;\n check.nullableString(node.description, [...path, \"description\"]);\n const members = check.array(node[member], [...path, member]);\n switch (typed) {\n case \"enum\":\n members?.forEach((entry, index) =>\n enumValue(check, entry, [...path, \"values\", index]),\n );\n break;\n case \"union\":\n members?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"members\", index]),\n );\n break;\n case \"input\":\n check.oneOf(\n node.unknownKeys,\n [\"preserve\", \"reject\"],\n [...path, \"unknownKeys\"],\n );\n fields(check, node.fields, [...path, \"fields\"], true);\n break;\n default:\n if (node.implements !== undefined) {\n check\n .array(node.implements, [...path, \"implements\"])\n ?.forEach((entry, index) =>\n check.graphQLName(entry, [...path, \"implements\", index]),\n );\n }\n fields(check, node.fields, [...path, \"fields\"], false);\n }\n return check.graphQLName(node.name, [...path, \"name\"]);\n}\n\nfunction examples(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n keys: readonly string[],\n): void {\n check.array(value, path)?.forEach((entry, index) => {\n const node = check.record(entry, keys, [...path, index]);\n if (node === undefined) return;\n for (const key of keys) check.string(node[key], [...path, index, key]);\n });\n}\n\nfunction state(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n): void {\n const node = check.record(\n value,\n [\"root\", \"initialValue\", \"examples\", \"unknownKeys\", \"materialized\"],\n path,\n );\n if (node === undefined) return;\n if (node.root === null) {\n if (scope === \"global\") {\n check.fail(\n [...path, \"root\"],\n \"A global state always has a root.\",\n \"a named type reference\",\n null,\n );\n }\n if (\n check.json(node.initialValue, [...path, \"initialValue\"]) !== undefined\n ) {\n if (canonicalJson(node.initialValue) !== \"{}\") {\n check.fail(\n [...path, \"initialValue\"],\n \"An empty local state carries an exact empty object.\",\n \"{}\",\n node.initialValue,\n );\n }\n }\n } else {\n typeReference(check, node.root, [...path, \"root\"]);\n check.json(node.initialValue, [...path, \"initialValue\"]);\n }\n check.literal(node.unknownKeys, \"preserve\", [...path, \"unknownKeys\"]);\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n const materializedPath = [...path, \"materialized\"];\n const materialized = check.record(\n node.materialized,\n [\"schema\", \"initialValue\", \"examples\"],\n materializedPath,\n );\n if (materialized === undefined) return;\n const schema = check.string(materialized.schema, [\n ...materializedPath,\n \"schema\",\n ]);\n if (node.root === null && schema !== undefined && schema !== \"\") {\n check.fail(\n [...materializedPath, \"schema\"],\n \"An empty local state materializes an empty schema.\",\n '\"\"',\n schema,\n );\n }\n check.string(materialized.initialValue, [\n ...materializedPath,\n \"initialValue\",\n ]);\n examples(\n check,\n materialized.examples,\n [...materializedPath, \"examples\"],\n [\"id\", \"value\"],\n );\n}\n\nconst OPERATION_KEYS = [\n \"id\",\n \"key\",\n \"name\",\n \"description\",\n \"actionType\",\n \"creatorKey\",\n \"scope\",\n \"input\",\n \"errors\",\n \"examples\",\n \"template\",\n \"reducer\",\n];\nconst ERROR_KEYS = [\"id\", \"key\", \"code\", \"name\", \"description\", \"template\"];\n\nfunction operation(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(value, OPERATION_KEYS, path);\n if (node === undefined) return;\n for (const key of [\"id\", \"key\", \"actionType\", \"creatorKey\"]) {\n check.string(node[key], [...path, key]);\n }\n for (const key of [\"name\", \"description\", \"template\", \"reducer\"]) {\n check.nullableString(node[key], [...path, key]);\n }\n check.oneOf(node.scope, [\"global\", \"local\"], [...path, \"scope\"]);\n if (node.input !== null) {\n const kind = (node.input as Node | null)?.kind;\n if (kind !== \"input\") {\n check.fail(\n [...path, \"input\", \"kind\"],\n \"An operation input is an input type.\",\n \"input\",\n kind,\n );\n } else {\n namedType(check, node.input, [...path, \"input\"]);\n }\n }\n check.array(node.errors, [...path, \"errors\"])?.forEach((entry, index) => {\n const at = [...path, \"errors\", index];\n const error = check.record(entry, ERROR_KEYS, at);\n if (error === undefined) return;\n check.string(error.id, [...at, \"id\"]);\n check.string(error.key, [...at, \"key\"]);\n for (const key of [\"code\", \"name\", \"description\", \"template\"]) {\n check.nullableString(error[key], [...at, key]);\n }\n });\n examples(check, node.examples, [...path, \"examples\"], [\"id\", \"key\", \"value\"]);\n}\n\nfunction storedScalar(\n check: ShapeChecker,\n value: unknown,\n name: string,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"kind\",\n \"formatVersion\",\n \"name\",\n \"representation\",\n \"description\",\n \"coercion\",\n \"coercionProfile\",\n ],\n path,\n );\n if (node === undefined) return;\n check.literal(node.kind, \"powerhouse.scalar\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n check.literal(node.name, name, [...path, \"name\"]);\n check.oneOf(node.representation, SCALAR_REPRESENTATIONS, [\n ...path,\n \"representation\",\n ]);\n check.string(node.description, [...path, \"description\"]);\n check.literal(node.coercionProfile, \"catalog-v1\", [\n ...path,\n \"coercionProfile\",\n ]);\n const coercion = check.record(\n node.coercion,\n [\"source\"],\n [...path, \"coercion\"],\n );\n if (coercion !== undefined) {\n check.oneOf(\n coercion.source,\n [\"derived\", \"explicit\"],\n [...path, \"coercion\", \"source\"],\n );\n }\n}\n\nfunction scalars(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n check.array(value, path)?.forEach((entry, index) => {\n const at = [...path, index];\n const isPackage =\n typeof entry === \"object\" &&\n entry !== null &&\n Object.hasOwn(entry, \"definition\");\n const scalar = check.record(\n entry,\n [\"name\", \"implementation\", \"coercionProfile\", \"definition\"],\n at,\n );\n if (scalar === undefined) return;\n check.literal(scalar.coercionProfile, \"catalog-v1\", [\n ...at,\n \"coercionProfile\",\n ]);\n if (check.rejectHostOnlyScalar(scalar.name, [...at, \"name\"])) return;\n if (!isPackage) {\n const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, \"name\"]);\n if (name !== undefined) {\n check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [\n ...at,\n \"implementation\",\n ]);\n }\n return;\n }\n const name = check.graphQLName(scalar.name, [...at, \"name\"]);\n if (name === undefined) return;\n if (MODEL_SCALARS.has(name) || declared.has(name)) {\n check.fail(\n [...at, \"name\"],\n \"A package scalar has a name no catalog scalar, GraphQL built-in, or other package scalar uses.\",\n \"an unused GraphQL name\",\n name,\n );\n return;\n }\n check.literal(scalar.implementation, `package#${name}`, [\n ...at,\n \"implementation\",\n ]);\n storedScalar(check, scalar.definition, name, [...at, \"definition\"]);\n declared.add(name);\n });\n return declared;\n}\n\nfunction specification(\n check: ShapeChecker,\n value: unknown,\n path: DefinitionPath,\n): void {\n const node = check.record(\n value,\n [\n \"version\",\n \"scalars\",\n \"graphQLCompatibility\",\n \"types\",\n \"state\",\n \"modules\",\n \"changeLog\",\n ],\n path,\n );\n if (node === undefined) return;\n if (\n typeof node.version !== \"number\" ||\n !Number.isSafeInteger(node.version) ||\n node.version <= 0\n ) {\n check.fail(\n [...path, \"version\"],\n \"A specification version is a positive safe integer.\",\n \"a positive safe integer\",\n node.version,\n );\n }\n check.packageScalars = scalars(check, node.scalars, [...path, \"scalars\"]);\n\n if (node.graphQLCompatibility !== null) {\n const at = [...path, \"graphQLCompatibility\"];\n const compatibility = check.record(\n node.graphQLCompatibility,\n [\"kind\", \"document\", \"preserveDefinitionOrder\"],\n at,\n );\n if (compatibility !== undefined) {\n check.literal(compatibility.kind, \"graphql-ast-v1\", [...at, \"kind\"]);\n check.literal(compatibility.preserveDefinitionOrder, true, [\n ...at,\n \"preserveDefinitionOrder\",\n ]);\n check.collector.merge(\n validateLocationFreeDocument(compatibility.document, [\n ...at,\n \"document\",\n ]),\n );\n }\n }\n\n const declared = new Set<string>();\n check.array(node.types, [...path, \"types\"])?.forEach((entry, index) => {\n const name = namedType(check, entry, [...path, \"types\", index]);\n if (name === undefined) return;\n if (declared.has(name) || check.packageScalars.has(name)) {\n check.fail(\n [...path, \"types\", index, \"name\"],\n \"A named type is declared once per specification, and never under a package scalar's name.\",\n \"one definition per name\",\n name,\n );\n }\n declared.add(name);\n });\n\n const stateNode = check.record(\n node.state,\n [\"global\", \"local\"],\n [...path, \"state\"],\n );\n if (stateNode !== undefined) {\n for (const scope of [\"global\", \"local\"] as const) {\n state(check, stateNode[scope], [...path, \"state\", scope], scope);\n const root = (stateNode[scope] as Node | undefined)?.root as\n | Node\n | null\n | undefined;\n if (typeof root?.name === \"string\" && !declared.has(root.name)) {\n check.fail(\n [...path, \"state\", scope, \"root\", \"name\"],\n \"A state root is declared in this specification's types.\",\n [...declared].join(\" | \"),\n root.name,\n );\n }\n }\n }\n\n check.array(node.modules, [...path, \"modules\"])?.forEach((entry, index) => {\n const at = [...path, \"modules\", index];\n const module = check.record(\n entry,\n [\"id\", \"key\", \"name\", \"description\", \"operations\"],\n at,\n );\n if (module === undefined) return;\n check.string(module.id, [...at, \"id\"]);\n check.string(module.key, [...at, \"key\"]);\n check.string(module.name, [...at, \"name\"]);\n check.nullableString(module.description, [...at, \"description\"]);\n check\n .array(module.operations, [...at, \"operations\"])\n ?.forEach((candidate, operationIndex) =>\n operation(check, candidate, [...at, \"operations\", operationIndex]),\n );\n });\n\n check\n .array(node.changeLog, [...path, \"changeLog\"])\n ?.forEach((entry, index) =>\n check.string(entry, [...path, \"changeLog\", index]),\n );\n}\n\nexport function checkDocumentModelDefinitionShape(\n value: unknown,\n path: DefinitionPath = [],\n): readonly DefinitionDiagnostic[] {\n const check = new ShapeChecker();\n const node = check.record(\n value,\n [\"kind\", \"formatVersion\", \"compatibility\", \"model\", \"specifications\"],\n path,\n );\n if (node === undefined) return check.collector.diagnostics;\n check.literal(node.kind, \"powerhouse.document-model\", [...path, \"kind\"]);\n check.literal(node.formatVersion, 1, [...path, \"formatVersion\"]);\n\n const compatibilityPath = [...path, \"compatibility\"];\n const compatibility = check.record(\n node.compatibility,\n [\"identity\", \"scalarCoercion\", \"serialization\"],\n compatibilityPath,\n );\n if (compatibility !== undefined) {\n check.oneOf(\n compatibility.identity,\n [\"derived-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"identity\"],\n );\n check.literal(compatibility.scalarCoercion, \"catalog-v1\", [\n ...compatibilityPath,\n \"scalarCoercion\",\n ]);\n check.oneOf(\n compatibility.serialization,\n [\"canonical-v1\", \"explicit-schema-first\"],\n [...compatibilityPath, \"serialization\"],\n );\n }\n\n const modelPath = [...path, \"model\"];\n const model = check.record(\n node.model,\n [\n \"documentType\",\n \"graphQLName\",\n \"name\",\n \"description\",\n \"extension\",\n \"author\",\n ],\n modelPath,\n );\n if (model !== undefined) {\n if (\n check.string(model.documentType, [...modelPath, \"documentType\"]) === \"\"\n ) {\n check.fail(\n [...modelPath, \"documentType\"],\n \"A document type is not empty.\",\n \"a document type\",\n '\"\"',\n );\n }\n check.graphQLName(model.graphQLName, [...modelPath, \"graphQLName\"]);\n for (const key of [\"name\", \"description\", \"extension\"]) {\n check.string(model[key], [...modelPath, key]);\n }\n const author = check.record(\n model.author,\n [\"name\", \"website\"],\n [...modelPath, \"author\"],\n );\n if (author !== undefined) {\n check.string(author.name, [...modelPath, \"author\", \"name\"]);\n check.nullableString(author.website, [...modelPath, \"author\", \"website\"]);\n }\n }\n\n const specifications = check.array(node.specifications, [\n ...path,\n \"specifications\",\n ]);\n if (specifications?.length === 0) {\n check.fail(\n [...path, \"specifications\"],\n \"A definition carries at least one specification.\",\n \"a nonempty specification history\",\n \"an empty array\",\n );\n }\n specifications?.forEach((entry, index) =>\n specification(check, entry, [...path, \"specifications\", index]),\n );\n return check.collector.diagnostics;\n}\n","import { compilerDiagnostics } from \"../compiler/diagnostic-codes.js\";\nimport { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\n\nexport const modelDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-STATE-ROOT-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A required state root is absent, is not an object, or has the wrong canonical name\",\n },\n \"PH-DM-SCOPE-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A definition requests a scope outside global or local\",\n },\n \"PH-AUTH-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"authorization\",\n meaning: \"A document model declares authorization, which core v1 rejects\",\n },\n },\n compilerDiagnostics,\n);\n\nexport type ModelDiagnosticCode = keyof typeof modelDiagnostics.codes;\n","import { defineDiagnosticCatalog } from \"../kernel/diagnostics.js\";\nimport { modelDiagnostics } from \"../model/diagnostic-codes.js\";\n\nexport const toolingDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-CONFIG-SOURCE-INVALID\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"The config file, a definition source entry, or an export pointer cannot select a module export\",\n },\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"A definition source path, or the real path behind its symlinks, leaves the package root\",\n },\n \"PH-CONFIG-DUPLICATE-SOURCE\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning: \"Two entries select the same module and export path\",\n },\n \"PH-CONFIG-VERSION-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"configuration\",\n meaning:\n \"definitionSources declares a format version this release does not read\",\n },\n \"PH-IMPORT-FAILED\": {\n severity: \"error\",\n phase: \"import\",\n meaning:\n \"A selected module is missing, throws while it is evaluated, or the import adapter returned no namespace\",\n },\n \"PH-PKG-DEFINITION-UNRECOGNIZED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export holds no materialized document model, family, or upgrade manifest\",\n },\n \"PH-PKG-DEFINITION-UNINSPECTABLE\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A selected export hides its members behind an accessor or a Proxy\",\n },\n \"PH-PKG-LOGICAL-COLLISION\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two distinct values claim one document type and version, or one upgrade manifest document type\",\n },\n },\n modelDiagnostics,\n);\n\nexport type ToolingDiagnosticCode = keyof typeof toolingDiagnostics.codes;\n","import type {\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelPHState,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport { canonicalDigest, canonicalJson } from \"../../kernel/primitives.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport type {\n NormalizedDocumentModelArtifact,\n NormalizedDocumentModelResult,\n} from \"./types.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\nconst MODULE_KEYS =\n \"version, reducer, actions, utils, documentModel, definition\";\nconst REPAIR =\n \"Export the module materialize returned, or family.at(version), without replacing its members.\";\n\nfunction sourceOf(\n source: DefinitionSource,\n exportPath: readonly string[],\n): DefinitionSource {\n const path = [...(source.exportPath ?? []), ...exportPath];\n return {\n specifier: source.specifier,\n ...(path.length > 0 && { exportPath: path }),\n };\n}\n\nfunction invalid(\n collector: Collector,\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair = REPAIR,\n): undefined {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message,\n expected,\n received,\n repair,\n });\n return undefined;\n}\n\nfunction storedDocumentType(\n collector: Collector,\n value: unknown,\n path: DefinitionPath,\n): string | undefined {\n const documentModel = snapshotRecord(value, undefined, path);\n const global = documentModel.ok\n ? snapshotRecord(documentModel.value.global, undefined, [...path, \"global\"])\n : documentModel;\n if (!global.ok) {\n return invalid(\n collector,\n global.path,\n `A module keeps its stored model in documentModel.global as plain data, and it cannot be read (${global.reason}).`,\n \"documentModel.global as a plain record of data properties\",\n rejectionReceived(global),\n );\n }\n const id = global.value.id;\n if (typeof id !== \"string\" || id === \"\") {\n return invalid(\n collector,\n [...path, \"global\", \"id\"],\n \"A module has a stored model ID.\",\n \"a nonempty document type\",\n typeof id === \"string\" ? '\"\"' : describeReceived(id),\n \"Declare id in defineDocumentModel; the stored model ID is the document type every consumer registers.\",\n );\n }\n return id;\n}\n\nfunction artifact(\n collector: Collector,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): NormalizedDocumentModelArtifact | undefined {\n const snapshot = snapshotRecord(value, undefined, path);\n if (!snapshot.ok) {\n return invalid(\n collector,\n snapshot.path,\n `This export is not a document-model module (${snapshot.reason}).`,\n MODULE_KEYS,\n rejectionReceived(snapshot),\n );\n }\n const module = snapshot.value;\n let usable = true;\n if (typeof module.reducer !== \"function\") {\n usable = false;\n invalid(\n collector,\n [...path, \"reducer\"],\n \"A module has a callable reducer.\",\n \"a reducer function\",\n describeReceived(module.reducer),\n );\n }\n const version = module.version;\n if (\n typeof version !== \"number\" ||\n !Number.isSafeInteger(version) ||\n version <= 0\n ) {\n usable = false;\n invalid(\n collector,\n [...path, \"version\"],\n \"A code-first module declares its registry version as a positive safe integer.\",\n \"a positive safe integer\",\n typeof version === \"number\" ? String(version) : describeReceived(version),\n );\n }\n const documentType = storedDocumentType(collector, module.documentModel, [\n ...path,\n \"documentModel\",\n ]);\n if (module.definition === undefined) {\n return invalid(\n collector,\n [...path, \"definition\"],\n \"This module carries no structured definition, so it was not made by materialize.\",\n \"the definition materialize attaches\",\n \"undefined\",\n \"Export the module materialize returned.\",\n );\n }\n const shape = checkDocumentModelDefinitionShape(module.definition, [\n ...path,\n \"definition\",\n ]);\n collector.merge(shape);\n if (\n !usable ||\n documentType === undefined ||\n shape.length > 0 ||\n typeof version !== \"number\"\n ) {\n return undefined;\n }\n const definition = module.definition as DocumentModelDefinition;\n\n if (definition.model.documentType !== documentType) {\n return invalid(\n collector,\n [...path, \"definition\", \"model\", \"documentType\"],\n \"The structured definition and the stored model describe different document types.\",\n documentType,\n definition.model.documentType,\n \"Materialize the module and its definition from the same declaration.\",\n );\n }\n if (!definition.specifications.some((entry) => entry.version === version)) {\n return invalid(\n collector,\n [...path, \"definition\", \"specifications\"],\n `The specification history carries no version ${version}, which is the version this module serves.`,\n `a specification for version ${version}`,\n definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n \"Compose the versions with defineDocumentModelFamily so every module carries the complete history.\",\n );\n }\n return {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: module.documentModel as DocumentModelPHState,\n };\n}\n\nfunction familyManifest(\n collector: Collector,\n value: unknown,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n path: DefinitionPath,\n): UpgradeManifest<readonly number[]> | null {\n const snapshot = snapshotRecord(value, undefined, path);\n const manifest = snapshot.ok ? snapshot.value : undefined;\n const versions = artifacts.map((entry) => entry.version);\n const supported = manifest?.supportedVersions;\n const declared =\n Array.isArray(supported) && supported.every(Number.isSafeInteger)\n ? canonicalJson(supported)\n : describeReceived(supported);\n if (\n manifest === undefined ||\n declared !== canonicalJson(versions) ||\n manifest.latestVersion !== versions.at(-1)\n ) {\n invalid(\n collector,\n snapshot.ok ? path : snapshot.path,\n \"A family's upgrade manifest covers exactly the versions its modules serve.\",\n canonicalJson(versions),\n snapshot.ok ? declared : rejectionReceived(snapshot),\n \"Export the family materialize returned, so its manifest and modules stay one declaration.\",\n );\n return null;\n }\n const documentTypes = new Set(artifacts.map((entry) => entry.documentType));\n if (\n documentTypes.size !== 1 ||\n !documentTypes.has(manifest.documentType as string)\n ) {\n invalid(\n collector,\n [...path, \"documentType\"],\n \"A family's upgrade manifest and its modules name one document type.\",\n [...documentTypes].join(\", \"),\n String(manifest.documentType),\n \"Compose one family per document type.\",\n );\n return null;\n }\n return value as UpgradeManifest<readonly number[]>;\n}\n\n/**\n * @experimental Normalizes one materialized code-first module, or a family\n * and its versions in order. A family reports every malformed member: a\n * valid sibling never makes a broken one pass.\n */\nexport function adaptCodeFirstDocumentModelSource(\n value: unknown,\n source: DefinitionSource,\n): NormalizedDocumentModelResult {\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const family = snapshotRecord(value, undefined, []);\n const modules =\n family.ok && typeof family.value.at === \"function\"\n ? snapshotArray(family.value.modules, [\"modules\"])\n : undefined;\n if (family.ok && modules?.ok === true) {\n const artifacts = modules.value.flatMap((module, index) => {\n const entry = artifact(\n collector,\n module,\n sourceOf(source, [\"modules\", String(index)]),\n [\"modules\", index],\n );\n return entry === undefined ? [] : [entry];\n });\n const manifest =\n artifacts.length === modules.value.length\n ? familyManifest(collector, family.value.upgradeManifest, artifacts, [\n \"upgradeManifest\",\n ])\n : null;\n return {\n artifacts,\n upgradeManifest: manifest,\n diagnostics: collector.diagnostics,\n };\n }\n const single = artifact(collector, value, source, []);\n return {\n artifacts: single === undefined ? [] : [single],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import {\n DEFAULT_AUTHORING_MODE,\n parseDefinitionSourcesConfig,\n} from \"@powerhousedao/shared/clis/definition-sources\";\nimport type {\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, isAbsolute, posix, relative, resolve, sep } from \"node:path\";\nimport {\n compareDefinitionPaths,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n compareCodeUnits,\n isNFC,\n} from \"../kernel/primitives.js\";\nimport type {\n DefinitionSourceOrigin,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n DefinitionSourceSet,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\n\nexport type ResolvedDefinitionSource = {\n readonly source: DefinitionSource;\n\n readonly position: DefinitionPath;\n\n readonly moduleIdentity: string;\n};\n\nexport type InternalResolution = DefinitionSourceResolution & {\n readonly packageRootIdentity: string;\n readonly resolved: readonly ResolvedDefinitionSource[];\n};\n\nconst CONFIG_FILE_NAME = \"./powerhouse.config.json\";\n\nconst IDENTITY_SEPARATOR = String.fromCharCode(0);\n\nfunction render(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined) return \"undefined\";\n try {\n // `JSON.stringify` returns `undefined` for a function or a symbol.\n const json = JSON.stringify(value) as string | undefined;\n return json ?? typeof value;\n } catch {\n return typeof value;\n }\n}\n\nfunction sourceSet(\n mode: DefinitionSourceSet[\"mode\"],\n origin: DefinitionSourceOrigin,\n sources: readonly DefinitionSource[],\n): DefinitionSourceSet {\n const value = { mode, origin, sources };\n return { ...value, digest: canonicalDigest(value) };\n}\n\nexport function compareDefinitionSources(\n left: DefinitionSource,\n right: DefinitionSource,\n): number {\n const specifier = compareCodeUnits(left.specifier, right.specifier);\n if (specifier !== 0) return specifier;\n const leftPath = left.exportPath ?? [];\n const rightPath = right.exportPath ?? [];\n for (\n let index = 0;\n index < Math.min(leftPath.length, rightPath.length);\n index += 1\n ) {\n const segment = compareCodeUnits(leftPath[index], rightPath[index]);\n if (segment !== 0) return segment;\n }\n return leftPath.length - rightPath.length;\n}\n\nfunction isCanonicalText(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) {\n return false;\n }\n }\n return isNFC(value);\n}\n\nfunction isWithin(root: string, path: string): boolean {\n const child = relative(root, path);\n return child !== \"..\" && !child.startsWith(`..${sep}`) && !isAbsolute(child);\n}\n\ntype SpecifierResult =\n | { readonly ok: true; readonly specifier: `./${string}` }\n | {\n readonly ok: false;\n readonly code:\n | \"PH-CONFIG-SOURCE-INVALID\"\n | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\";\n readonly message: string;\n };\n\nfunction normalizeSpecifier(value: string): SpecifierResult {\n if (\n !value.startsWith(\"./\") ||\n /[\\\\#?]/.test(value) ||\n !isCanonicalText(value)\n ) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source is a POSIX package-relative path beginning with './'.\",\n };\n }\n const normalized = posix.normalize(value.slice(2));\n if (normalized === \".\" || normalized === \"./\") {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message: \"A definition source names a module file, not the package root.\",\n };\n }\n if (normalized === \"..\" || normalized.startsWith(\"../\")) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: \"The normalized definition source path leaves the package root.\",\n };\n }\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/.test(value)) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source names a JavaScript or TypeScript module file with its extension.\",\n };\n }\n return { ok: true, specifier: `./${normalized}` };\n}\n\n/**\n * Resolves symlinks as far as the path exists, so a source that is not\n * written yet is still judged against the real package root.\n */\nfunction realPathThroughExistingParent(path: string): string {\n let current = path;\n const suffix: string[] = [];\n while (!existsSync(current)) {\n const parent = dirname(current);\n if (parent === current) return path;\n suffix.unshift(relative(parent, current));\n current = parent;\n }\n return resolve(realpathSync.native(current), ...suffix);\n}\n\ntype EntryResult =\n | { readonly source: ResolvedDefinitionSource }\n | { readonly diagnostic: DefinitionDiagnostic };\n\nfunction invalidEntry(\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n repair: string,\n source?: DefinitionSource,\n): EntryResult {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n ...(source !== undefined && { source }),\n path,\n message,\n expected,\n received,\n repair,\n }),\n };\n}\n\nfunction normalizeEntry(\n value: unknown,\n position: DefinitionPath,\n packageRoot: string,\n packageRootIdentity: string,\n): EntryResult {\n if (\n value === null ||\n typeof value !== \"object\" ||\n Object.getPrototypeOf(value) !== Object.prototype\n ) {\n return invalidEntry(\n position,\n \"A definition source entry must be a plain object.\",\n \"{ specifier, exportPath? }\",\n render(value),\n 'Replace this entry with { \"specifier\": \"./src/<module>.ts\" }.',\n );\n }\n const entry = value as Record<string, unknown>;\n const extra = Object.keys(entry)\n .filter((key) => key !== \"specifier\" && key !== \"exportPath\")\n .sort(compareCodeUnits);\n if (extra.length > 0) {\n return invalidEntry(\n position,\n \"A definition source entry carries unsupported properties.\",\n \"specifier and optional exportPath\",\n extra.join(\", \"),\n `Remove ${extra.join(\", \")} from this entry.`,\n );\n }\n const specifierPath = [...position, \"specifier\"];\n if (typeof entry.specifier !== \"string\") {\n return invalidEntry(\n specifierPath,\n \"A definition source specifier must be a string.\",\n \"a './' POSIX package-relative path\",\n render(entry.specifier),\n \"Set specifier to the package-relative TypeScript module path.\",\n );\n }\n const normalized = normalizeSpecifier(entry.specifier);\n if (!normalized.ok) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: normalized.code,\n path: specifierPath,\n message: normalized.message,\n expected: \"a './' path contained by the selected package root\",\n received: entry.specifier,\n repair:\n \"Move the module inside the package and spell its path relative to the config file.\",\n }),\n };\n }\n const { specifier } = normalized;\n\n let exportPath: readonly string[] | undefined;\n if (entry.exportPath !== undefined) {\n const valid =\n Array.isArray(entry.exportPath) &&\n entry.exportPath.every(\n (segment) => typeof segment === \"string\" && isCanonicalText(segment),\n );\n if (!valid) {\n return invalidEntry(\n [...position, \"exportPath\"],\n \"An exportPath is an array of exact property keys in NFC, without control characters.\",\n \"an array of property-key strings\",\n render(entry.exportPath),\n \"Replace exportPath with the exported property keys, outermost first.\",\n { specifier },\n );\n }\n const segments = entry.exportPath as readonly string[];\n if (segments.length > 0) exportPath = [...segments];\n }\n\n const source: DefinitionSource =\n exportPath === undefined ? { specifier } : { specifier, exportPath };\n const declaredPath = resolve(packageRoot, ...specifier.slice(2).split(\"/\"));\n let moduleIdentity: string;\n try {\n moduleIdentity = realPathThroughExistingParent(declaredPath);\n } catch {\n return invalidEntry(\n specifierPath,\n \"The definition source path could not be resolved.\",\n \"a resolvable path inside the package root\",\n specifier,\n \"Fix the path, or the permissions of a directory on the way to it.\",\n source,\n );\n }\n if (!isWithin(packageRootIdentity, moduleIdentity)) {\n return {\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source,\n path: specifierPath,\n message:\n \"The definition source resolves through a symlink that leaves the package root.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a module that really lives in this package.\",\n }),\n };\n }\n return { source: { source, position, moduleIdentity } };\n}\n\nfunction duplicateDiagnostics(\n sources: readonly ResolvedDefinitionSource[],\n): readonly DefinitionDiagnostic[] {\n const groups = new Map<string, ResolvedDefinitionSource[]>();\n for (const entry of sources) {\n const key = [\n entry.moduleIdentity,\n JSON.stringify(entry.source.exportPath ?? []),\n ].join(IDENTITY_SEPARATOR);\n groups.set(key, [...(groups.get(key) ?? []), entry]);\n }\n return [...groups.values()]\n .filter((group) => group.length > 1)\n .map((group) => {\n const [first, ...rest] = [...group].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.position, right.position),\n );\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-DUPLICATE-SOURCE\",\n source: first.source,\n path: first.position,\n message:\n \"Several entries select the same module and export path, so one of them can only repeat the other's definitions.\",\n expected: \"one entry per module and export path\",\n received: `${group.length} entries`,\n repair: \"Remove every duplicate entry except one.\",\n related: rest.map((entry) => ({\n source: entry.source,\n path: entry.position,\n message: \"This entry resolves to the same module and export path.\",\n })),\n });\n });\n}\n\ntype Roots = {\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n};\n\nfunction failed(\n roots: Roots,\n diagnostics: readonly DefinitionDiagnostic[],\n origin: DefinitionSourceOrigin = \"config\",\n sources: readonly DefinitionSource[] = [],\n): InternalResolution {\n return {\n ...roots,\n status: \"failed\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: sortDefinitionDiagnostics(diagnostics),\n resolved: [],\n };\n}\n\nfunction skipped(\n roots: Roots,\n skipReason: DefinitionCheckSkipReason,\n mode: DefinitionSourceSet[\"mode\"],\n): InternalResolution {\n return {\n ...roots,\n status: \"skipped\",\n skipReason,\n sourceSet: sourceSet(mode, \"config\", []),\n diagnostics: [],\n resolved: [],\n };\n}\n\ntype ConfigReadFailure =\n | \"missing\"\n | \"read-failed\"\n | \"parse-failed\"\n | \"not-an-object\";\n\nconst CONFIG_FAILURE_REPAIR: Record<ConfigReadFailure, string> = {\n missing:\n \"Create the config file, or point --config-file at the package's existing one.\",\n \"read-failed\": \"Fix the permissions of the selected config file.\",\n \"parse-failed\": \"Repair the JSON in the selected config file.\",\n \"not-an-object\": \"Make the config file a single JSON object.\",\n};\n\nfunction readConfigObject(\n configFile: string,\n):\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | { readonly ok: false; readonly reason: ConfigReadFailure } {\n let text: string;\n try {\n text = readFileSync(configFile, \"utf8\");\n } catch (error) {\n const code = (error as { code?: unknown } | null)?.code;\n return {\n ok: false,\n reason:\n code === \"ENOENT\" || code === \"ENOTDIR\" ? \"missing\" : \"read-failed\",\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, reason: \"parse-failed\" };\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { ok: false, reason: \"not-an-object\" };\n }\n return { ok: true, value: parsed as Readonly<Record<string, unknown>> };\n}\n\nfunction selectionDiagnostic(\n narrowed: Exclude<\n ReturnType<typeof parseDefinitionSourcesConfig>,\n { ok: true } | { reason: \"missing\" }\n >,\n): DefinitionDiagnostic {\n if (narrowed.reason === \"unsupported-version\") {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-VERSION-UNSUPPORTED\",\n path: narrowed.path,\n message:\n \"The definitionSources format version is not one this release reads.\",\n expected: \"1\",\n received: render(narrowed.received),\n repair: \"Set definitionSources.formatVersion to 1, or upgrade ph.\",\n });\n }\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: narrowed.path,\n message: \"The definitionSources selection is malformed.\",\n expected: narrowed.expected,\n received: render(narrowed.received),\n repair: `Set this member to ${narrowed.expected}.`,\n });\n}\n\nexport function resolveDefinitionSources(\n request: DefinitionSourceSelectionRequest,\n): InternalResolution {\n const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);\n const packageRoot = dirname(configFile);\n let packageRootIdentity = packageRoot;\n try {\n packageRootIdentity = realpathSync.native(packageRoot);\n } catch {\n // The config read below reports the missing directory.\n }\n const roots = { packageRoot, packageRootIdentity };\n\n if (request.allowMissingConfig === true && !existsSync(configFile)) {\n return skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE);\n }\n\n const config = readConfigObject(configFile);\n if (!config.ok) {\n return failed(roots, [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"configFile\"],\n message:\n \"The selected Powerhouse config file could not be read; its directory is the package root.\",\n expected: \"an existing config file holding one JSON object\",\n received: config.reason,\n repair: CONFIG_FAILURE_REPAIR[config.reason],\n }),\n ]);\n }\n\n const origin = \"config\";\n const narrowed = parseDefinitionSourcesConfig(config.value.definitionSources);\n if (!narrowed.ok) {\n return narrowed.reason === \"missing\"\n ? skipped(roots, \"definition-sources-absent\", DEFAULT_AUTHORING_MODE)\n : failed(roots, [selectionDiagnostic(narrowed)], origin);\n }\n if (narrowed.mode === \"schema-first\") {\n return skipped(roots, \"explicit-schema-first-mode\", \"schema-first\");\n }\n if (narrowed.entries.length === 0) {\n return skipped(roots, \"definition-sources-empty\", \"code-first\");\n }\n const entries = narrowed.entries;\n\n const normalized = entries.map((value, index) =>\n normalizeEntry(\n value,\n [\"definitionSources\", \"entries\", index],\n packageRoot,\n packageRootIdentity,\n ),\n );\n\n const resolved = normalized\n .flatMap((result) => (\"source\" in result ? [result.source] : []))\n .sort((left, right) => compareDefinitionSources(left.source, right.source));\n const sources = resolved.map((entry) => entry.source);\n const entryDiagnostics = normalized.flatMap((result) =>\n \"diagnostic\" in result ? [result.diagnostic] : [],\n );\n if (entryDiagnostics.length > 0) {\n return failed(roots, entryDiagnostics, origin, sources);\n }\n const duplicates = duplicateDiagnostics(resolved);\n if (duplicates.length > 0) {\n return failed(roots, duplicates, origin, sources);\n }\n return {\n ...roots,\n status: \"ready\",\n sourceSet: sourceSet(\"code-first\", origin, sources),\n diagnostics: [],\n resolved,\n };\n}\n\nexport function publicResolution(\n value: InternalResolution,\n): DefinitionSourceResolution {\n const common = {\n packageRoot: value.packageRoot,\n sourceSet: value.sourceSet,\n diagnostics: value.diagnostics,\n };\n return value.status === \"skipped\"\n ? { ...common, status: \"skipped\", skipReason: value.skipReason }\n : { ...common, status: value.status };\n}\n\n/**\n * @experimental The selection a command would load, resolved without\n * importing anything and without any machine-specific path but the root.\n */\nexport function resolveDefinitionSelection(\n request: DefinitionSourceSelectionRequest,\n): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRef,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { snapshotArray, snapshotRecord } from \"../kernel/data-properties.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"./diagnostic-codes.js\";\n\nexport function describeThrown(error: unknown): string {\n if (error === null) return \"null\";\n try {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n } catch {\n // A revoked Proxy or a throwing getter makes these reads throw.\n }\n return typeof error;\n}\n\n/** Reads an own data property without running a getter or a Proxy trap twice. */\nexport function readProperty(\n value: object,\n key: string,\n): { readonly ok: true; readonly value: unknown } | { readonly ok: false } {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !(\"value\" in descriptor)) {\n return { ok: false };\n }\n return { ok: true, value: descriptor.value as unknown };\n } catch {\n return { ok: false };\n }\n}\n\nconst DEFINITION_KINDS: readonly unknown[] = [\n \"document-model\",\n \"subgraph\",\n \"scalar\",\n \"package\",\n];\n\nfunction definitionRef(value: unknown): DefinitionRef | undefined {\n const snapshot = snapshotRecord(value, undefined, []);\n if (!snapshot.ok) return undefined;\n const { kind, key, version } = snapshot.value;\n if (\n typeof key !== \"string\" ||\n key === \"\" ||\n !DEFINITION_KINDS.includes(kind)\n ) {\n return undefined;\n }\n return {\n kind: kind as DefinitionRef[\"kind\"],\n key,\n ...(typeof version === \"number\" && { version }),\n };\n}\n\nfunction isPathSegment(segment: unknown): boolean {\n return (\n typeof segment === \"string\" ||\n (typeof segment === \"number\" && Number.isSafeInteger(segment))\n );\n}\n\nexport function structuredDiagnostics(\n value: unknown,\n source: DefinitionSource,\n): readonly DefinitionDiagnostic[] | undefined {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return undefined;\n }\n const list = readProperty(value, \"diagnostics\");\n if (!list.ok) return undefined;\n const snapshot = snapshotArray(list.value, []);\n if (!snapshot.ok || snapshot.value.length === 0) return undefined;\n\n const rebuilt: DefinitionDiagnostic[] = [];\n for (const candidate of snapshot.value) {\n const entry = snapshotRecord(candidate, undefined, []);\n if (!entry.ok) return undefined;\n const { code, message, repair, expected, received } = entry.value;\n const path = snapshotArray(entry.value.path, []);\n if (\n typeof code !== \"string\" ||\n !Object.hasOwn(toolingDiagnostics.codes, code) ||\n typeof message !== \"string\" ||\n typeof repair !== \"string\" ||\n !path.ok ||\n !path.value.every(isPathSegment) ||\n (expected !== undefined && typeof expected !== \"string\") ||\n (received !== undefined && typeof received !== \"string\")\n ) {\n return undefined;\n }\n const definition = definitionRef(entry.value.definition);\n rebuilt.push(\n toolingDiagnostics.create({\n code: code as ToolingDiagnosticCode,\n source,\n ...(definition !== undefined && { definition }),\n path: path.value as DefinitionPath,\n message,\n ...(expected !== undefined && { expected }),\n ...(received !== undefined && { received }),\n repair,\n }),\n );\n }\n return rebuilt;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n DocumentModelModule,\n Sha256Digest,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport {\n compareDefinitionPaths,\n describeReceived,\n sortDefinitionDiagnostics,\n} from \"../kernel/diagnostics.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\nimport {\n compareDefinitionSources,\n type InternalResolution,\n publicResolution,\n resolveDefinitionSources,\n} from \"./definition-source-resolution.js\";\nimport type {\n DefinitionSourceLoadRequest,\n DefinitionSourceResolution,\n DefinitionSourceSelectionRequest,\n LoadedDefinition,\n LoadedDefinitionSet,\n TypeScriptSourceImportInterface,\n} from \"./definition-source-types.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\nimport {\n describeThrown,\n readProperty,\n structuredDiagnostics,\n} from \"./structured-diagnostics.js\";\n\ntype Manifest = UpgradeManifest<readonly number[]>;\n\ntype Collected = {\n readonly documentModels: LoadedDefinition<DocumentModelModule>[];\n readonly upgradeManifests: LoadedDefinition<Manifest>[];\n readonly diagnostics: DefinitionDiagnostic[];\n\n readonly visited: Map<object, number>;\n readonly claimed: Map<\n string,\n { readonly source: DefinitionSource; readonly path: DefinitionPath }\n >;\n};\n\ntype ImportedNamespace =\n | { readonly ok: true; readonly value: Readonly<Record<string, unknown>> }\n | {\n readonly ok: false;\n readonly diagnostics: (\n source: DefinitionSource,\n ) => readonly DefinitionDiagnostic[];\n };\n\nconst KEY_SEPARATOR = String.fromCharCode(0);\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === \"string\" && /^sha256:[0-9a-f]{64}$/.test(value);\n}\n\nfunction isVersionList(value: unknown): value is readonly number[] {\n return (\n Array.isArray(value) &&\n value.every(\n (version) => Number.isSafeInteger(version) && (version as number) > 0,\n )\n );\n}\n\nfunction isDocumentModelModule(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.reducer === \"function\" &&\n snapshotRecord(record.documentModel, undefined, []).ok\n );\n}\n\nfunction isUpgradeManifest(record: Readonly<Record<string, unknown>>) {\n return (\n typeof record.documentType === \"string\" &&\n Number.isSafeInteger(record.latestVersion) &&\n isVersionList(record.supportedVersions) &&\n snapshotRecord(record.upgrades, undefined, []).ok\n );\n}\n\nfunction familyMembers(\n record: Readonly<Record<string, unknown>>,\n): readonly unknown[] | undefined {\n if (typeof record.at !== \"function\" || record.upgradeManifest === undefined) {\n return undefined;\n }\n const modules = snapshotArray(record.modules, []);\n return modules.ok ? modules.value : undefined;\n}\n\nfunction documentTypeOf(module: unknown): string {\n const stored = snapshotRecord(\n (module as { documentModel?: unknown }).documentModel,\n undefined,\n [],\n );\n const global = stored.ok\n ? snapshotRecord(stored.value.global, undefined, [])\n : undefined;\n return global?.ok === true && typeof global.value.id === \"string\"\n ? global.value.id\n : \"\";\n}\n\nfunction extendSource(\n source: DefinitionSource,\n path: DefinitionPath,\n): DefinitionSource {\n const exportPath = [...(source.exportPath ?? []), ...path.map(String)];\n return {\n specifier: source.specifier,\n ...(exportPath.length > 0 && { exportPath }),\n };\n}\n\nfunction claim(\n collected: Collected,\n logicalKey: string,\n describe: string,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const existing = collected.claimed.get(logicalKey);\n if (existing === undefined) {\n collected.claimed.set(logicalKey, { source, path });\n return;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source,\n path,\n message: `Two different values both declare ${describe}, so a host registering this package would keep only one of them.`,\n expected: \"one value per logical definition\",\n received: describe,\n repair:\n \"Export one canonical value for this definition and remove the other source entry.\",\n related: [\n {\n source: existing.source,\n path: existing.path,\n message: \"The first value claiming it is here.\",\n },\n ],\n }),\n );\n}\n\nfunction collectDocumentModel(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const module = value as DocumentModelModule;\n collected.documentModels.push({ source, path, value: module });\n const documentType = documentTypeOf(module);\n const version = (module as { version?: unknown }).version;\n\n if (documentType === \"\" || typeof version !== \"number\") return;\n claim(\n collected,\n [\"document-model\", documentType, String(version)].join(KEY_SEPARATOR),\n `document model ${documentType} version ${String(version)}`,\n source,\n path,\n );\n}\n\nfunction collectUpgradeManifest(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): void {\n const manifest = value as Manifest;\n collected.upgradeManifests.push({ source, path, value: manifest });\n claim(\n collected,\n [\"upgrade-manifest\", manifest.documentType].join(KEY_SEPARATOR),\n `the upgrade manifest of ${manifest.documentType}`,\n source,\n path,\n );\n}\n\nfunction visit(\n collected: Collected,\n value: unknown,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n if (value === null || typeof value !== \"object\") return 0;\n const alias = collected.visited.get(value);\n if (alias !== undefined) return alias;\n\n collected.visited.set(value, 0);\n const found = walk(collected, value, source, path);\n collected.visited.set(value, found);\n return found;\n}\n\nfunction walk(\n collected: Collected,\n value: object,\n source: DefinitionSource,\n path: DefinitionPath,\n): number {\n const array = snapshotArray(value, path);\n if (array.ok) {\n return array.value.reduce<number>(\n (count, member, index) =>\n count + visit(collected, member, source, [...path, index]),\n 0,\n );\n }\n const plain = snapshotRecord(value, undefined, path);\n if (!plain.ok) {\n if (plain.reason !== \"accessor\" && plain.reason !== \"inspection-failed\") {\n return 0;\n }\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNINSPECTABLE\",\n source: extendSource(source, path),\n path,\n message: `This export could not be read safely (${plain.reason}).`,\n expected: \"a plain object, an array, or a materialized definition\",\n received: rejectionReceived(plain),\n repair:\n \"Export plain values: a getter or a Proxy hides what the loader reads.\",\n }),\n );\n return 0;\n }\n const record = plain.value;\n const members = familyMembers(record);\n if (members !== undefined) {\n const count = members.reduce<number>(\n (total, member, index) =>\n total + visit(collected, member, source, [...path, \"modules\", index]),\n 0,\n );\n return (\n count +\n visit(collected, record.upgradeManifest, source, [\n ...path,\n \"upgradeManifest\",\n ])\n );\n }\n if (isDocumentModelModule(record)) {\n collectDocumentModel(collected, value, extendSource(source, path), path);\n return 1;\n }\n if (isUpgradeManifest(record)) {\n collectUpgradeManifest(collected, value, extendSource(source, path), path);\n return 1;\n }\n return Object.keys(record)\n .sort(compareCodeUnits)\n .reduce<number>(\n (count, key) =>\n count + visit(collected, record[key], source, [...path, key]),\n 0,\n );\n}\n\nfunction checkManifestCoverage(collected: Collected): void {\n const versionsByType = new Map<string, number[]>();\n for (const entry of collected.documentModels) {\n const documentType = documentTypeOf(entry.value);\n const version = (entry.value as { version?: unknown }).version;\n if (documentType === \"\" || typeof version !== \"number\") continue;\n versionsByType.set(documentType, [\n ...(versionsByType.get(documentType) ?? []),\n version,\n ]);\n }\n const ascending = (left: number, right: number) => left - right;\n for (const manifest of collected.upgradeManifests) {\n const { documentType, supportedVersions, latestVersion, upgrades } =\n manifest.value;\n const definition = { kind: \"document-model\", key: documentType } as const;\n const loaded = [...(versionsByType.get(documentType) ?? [])].sort(\n ascending,\n );\n const declared = [...supportedVersions].sort(ascending);\n if (\n JSON.stringify(loaded) !== JSON.stringify(declared) ||\n latestVersion !== declared.at(-1)\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: manifest.path,\n message:\n \"The upgrade manifest and the selected modules of this document type describe different version sets.\",\n expected: `supportedVersions ${JSON.stringify(loaded)} with latestVersion ${String(loaded.at(-1))}`,\n received: `supportedVersions ${JSON.stringify(declared)} with latestVersion ${String(latestVersion)}`,\n repair:\n \"Select the whole family that materialize returned, so its modules and its manifest stay one declaration.\",\n }),\n );\n continue;\n }\n const expected = declared.slice(1).map((version) => `v${version}`);\n const actual = Object.keys(upgrades).sort(compareCodeUnits);\n if (\n JSON.stringify(actual) !==\n JSON.stringify([...expected].sort(compareCodeUnits))\n ) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: manifest.source,\n definition,\n path: [...manifest.path, \"upgrades\"],\n message:\n \"The upgrade manifest does not carry exactly one transition for each version after the first.\",\n expected: expected.join(\", \") || \"no transitions\",\n received: actual.join(\", \") || \"no transitions\",\n repair: \"Publish the manifest materialize returned, unmodified.\",\n }),\n );\n }\n }\n}\n\n/**\n * A native namespace carries a `Symbol.toStringTag` key and Vite's SSR\n * namespace exposes exports through getters; the data-property rules would\n * reject both without this flattening.\n */\nfunction namespaceSnapshot(value: unknown): Readonly<Record<string, unknown>> {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n throw new TypeError(\n `The import adapter returned ${describeReceived(value)} instead of a module namespace.`,\n );\n }\n return Object.freeze({ ...(value as Record<string, unknown>) });\n}\n\nfunction unresolvedBareImportOf(error: unknown): string | undefined {\n if (!(error instanceof Error)) return undefined;\n const match =\n /^Cannot find (?:package|module) '([^']+)' imported from '?(.+?)'?$/m.exec(\n error.message,\n );\n if (match === null) return undefined;\n const [, specifier, importer] = match;\n if (/^(?:[./\\\\]|[a-zA-Z][\\w+.-]*:)/.test(specifier)) return undefined;\n const name = specifier\n .split(\"/\")\n .slice(0, specifier.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n const from = importer.startsWith(\"file:\")\n ? fileURLToPath(importer)\n : importer;\n if (!isAbsolute(from)) return undefined;\n for (let directory = dirname(from); ; directory = dirname(directory)) {\n if (existsSync(join(directory, \"node_modules\", name))) return undefined;\n if (dirname(directory) === directory) return name;\n }\n}\n\nfunction importDiagnostics(\n error: unknown,\n source: DefinitionSource,\n missing: boolean,\n): readonly DefinitionDiagnostic[] {\n if (missing) {\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"definitionSources lists a module that does not exist.\",\n expected: \"an existing module inside the package\",\n received: source.specifier,\n repair:\n \"Fix the specifier, or remove the entry from definitionSources.entries in powerhouse.config.json.\",\n }),\n ];\n }\n const structured = structuredDiagnostics(error, source);\n if (structured !== undefined) return structured;\n const unresolved = unresolvedBareImportOf(error);\n return [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message:\n unresolved === undefined\n ? \"This definition source could not be imported.\"\n : `This definition source could not resolve the import ${unresolved}.`,\n expected:\n unresolved === undefined\n ? \"an importable TypeScript module\"\n : `a project alias or installed dependency resolving ${unresolved}`,\n received: describeThrown(error),\n repair:\n unresolved === undefined\n ? \"Fix this module or one of its imports, then load it again.\"\n : `Check the project tsconfig paths and package dependencies for ${unresolved}. If it is an npm package, list it in package.json and install dependencies.`,\n }),\n ];\n}\n\ntype SelectedExport =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\nfunction selectExport(\n source: DefinitionSource,\n namespace: Readonly<Record<string, unknown>>,\n): SelectedExport {\n let current: unknown = namespace;\n const exportPath = source.exportPath ?? [];\n for (const [index, key] of exportPath.entries()) {\n const read =\n current !== null &&\n (typeof current === \"object\" || typeof current === \"function\")\n ? readProperty(current, key)\n : undefined;\n if (read?.ok !== true) {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n source,\n path: [\"exportPath\", index],\n message:\n read === undefined\n ? `The export pointer reads \"${key}\" from a value that has no properties.`\n : `The configured export \"${key}\" is absent, or is not a plain readable property.`,\n expected: read === undefined ? \"an object or a namespace\" : key,\n received: read === undefined ? describeReceived(current) : \"missing\",\n repair:\n \"Point the export pointer at an exact exported property, spelled as it is exported.\",\n }),\n };\n }\n current = read.value;\n }\n return { ok: true, value: current };\n}\n\nfunction sortBySource<T>(\n entries: readonly LoadedDefinition<T>[],\n): readonly LoadedDefinition<T>[] {\n return [...entries].sort(\n (left, right) =>\n compareDefinitionSources(left.source, right.source) ||\n compareDefinitionPaths(left.path, right.path),\n );\n}\n\nfunction empty(resolution: DefinitionSourceResolution): LoadedDefinitionSet {\n return { ...resolution, documentModels: [], upgradeManifests: [] };\n}\n\n/**\n * @experimental Imports the selected definition sources and finds the\n * materialized document models, families and upgrade manifests they export.\n * It folds aliases, reports two values that claim one `documentType@version`,\n * and returns everything sorted by source, so neither config order nor\n * import completion order changes a result. Validity belongs to the\n * adapters; registration belongs to the host.\n */\nexport class DefinitionSourceLoader {\n readonly #importer: TypeScriptSourceImportInterface;\n readonly #imports = new Map<\n string,\n Promise<Readonly<Record<string, unknown>>>\n >();\n #revision: Sha256Digest | undefined;\n\n constructor(importer: TypeScriptSourceImportInterface) {\n this.#importer = importer;\n }\n\n resolve(\n request: DefinitionSourceSelectionRequest,\n ): DefinitionSourceResolution {\n return publicResolution(resolveDefinitionSources(request));\n }\n\n async normalizeDefinitionSources(\n request: DefinitionSourceLoadRequest,\n ): Promise<LoadedDefinitionSet> {\n request.signal?.throwIfAborted();\n const resolution = resolveDefinitionSources(request);\n if (resolution.status !== \"ready\") {\n return empty(publicResolution(resolution));\n }\n if (!isSha256Digest(request.packageRevision)) {\n return empty({\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: \"failed\",\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"packageRevision\"],\n message:\n \"The package revision is not a SHA-256 identifier, so no import can be bound to it.\",\n expected: \"sha256: followed by 64 lowercase hexadecimal digits\",\n received:\n typeof request.packageRevision === \"string\"\n ? request.packageRevision\n : describeReceived(request.packageRevision),\n repair: \"Pass a revision digest of the package's current files.\",\n }),\n ],\n });\n }\n await this.#retainRevision(request.packageRevision);\n const namespaces = await this.#importModules(resolution, request);\n request.signal?.throwIfAborted();\n\n const collected: Collected = {\n documentModels: [],\n upgradeManifests: [],\n diagnostics: [],\n visited: new Map(),\n claimed: new Map(),\n };\n\n for (const entry of resolution.resolved) {\n const namespace = namespaces.get(entry.moduleIdentity);\n if (namespace === undefined) continue;\n if (!namespace.ok) {\n collected.diagnostics.push(...namespace.diagnostics(entry.source));\n continue;\n }\n const selected = selectExport(entry.source, namespace.value);\n if (!selected.ok) {\n collected.diagnostics.push(selected.diagnostic);\n continue;\n }\n if (visit(collected, selected.value, entry.source, []) === 0) {\n collected.diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNRECOGNIZED\",\n source: entry.source,\n path: [],\n message:\n \"This source exports no materialized document model, so selecting it loads nothing.\",\n expected:\n \"a module or family materialize returned, or a collection holding them\",\n received: \"no recognized definition\",\n repair:\n \"Point this entry at the export that materialize(...) returned.\",\n }),\n );\n }\n }\n checkManifestCoverage(collected);\n\n const diagnostics = sortDefinitionDiagnostics(collected.diagnostics);\n return {\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: diagnostics.some(({ severity }) => severity === \"error\")\n ? \"failed\"\n : \"ready\",\n diagnostics,\n documentModels: sortBySource(collected.documentModels),\n upgradeManifests: sortBySource(collected.upgradeManifests),\n };\n }\n\n async dispose(): Promise<void> {\n const revision = this.#revision;\n this.#imports.clear();\n this.#revision = undefined;\n if (revision !== undefined) {\n await this.#importer.disposeRevision?.(revision);\n }\n }\n\n async #retainRevision(revision: Sha256Digest): Promise<void> {\n if (this.#revision === revision) return;\n const superseded = this.#revision;\n this.#imports.clear();\n this.#revision = revision;\n if (superseded !== undefined) {\n await this.#importer.disposeRevision?.(superseded);\n }\n }\n\n async #importModules(\n resolution: InternalResolution,\n request: DefinitionSourceLoadRequest,\n ): Promise<Map<string, ImportedNamespace>> {\n const results = new Map<string, ImportedNamespace>();\n\n // Evaluate serially so aliases and their family share one module evaluation.\n for (const entry of resolution.resolved) {\n const { moduleIdentity, source } = entry;\n if (results.has(moduleIdentity)) continue;\n let namespace = this.#imports.get(moduleIdentity);\n if (namespace === undefined) {\n namespace = this.#importer.importModule({\n // Use the real root so symlink aliases cannot evaluate the module twice.\n packageRoot: resolution.packageRootIdentity,\n specifier: source.specifier,\n packageRevision: request.packageRevision,\n ...(request.signal !== undefined && { signal: request.signal }),\n });\n this.#imports.set(moduleIdentity, namespace);\n\n void namespace.catch(() => this.#imports.delete(moduleIdentity));\n }\n try {\n results.set(moduleIdentity, {\n ok: true,\n value: namespaceSnapshot(await namespace),\n });\n } catch (error) {\n const missing = !existsSync(moduleIdentity);\n results.set(moduleIdentity, {\n ok: false,\n diagnostics: (failedSource) =>\n importDiagnostics(error, failedSource, missing),\n });\n }\n }\n return results;\n }\n}\n"],"mappings":";;;;;;AAKA,SAAS,YAAY,OAAe,OAAuB;CACzD,QAAS,UAAU,QAAU,SAAU,KAAK,WAAa;AAC3D;AAEA,MAAM,mBAAmB,IAAI,YAAY;CACvC;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;CAAY;CAAY;CAC5D;CAAY;CAAY;CAAY;AACtC,CAAC;AAED,SAAgB,OAAO,OAA6B;CAClD,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;CAC5C,MAAM,eAAe,KAAK,MAAM,MAAM,SAAS,KAAK,EAAE,IAAI;CAC1D,MAAM,QAAQ,IAAI,WAAW,YAAY;CACzC,MAAM,IAAI,KAAK;CACf,MAAM,MAAM,UAAU;CACtB,MAAM,OAAO,IAAI,SAAS,MAAM,MAAM;CACtC,MAAM,YAAY,OAAO,MAAM,MAAM,IAAI;CACzC,KAAK,UAAU,eAAe,GAAG,OAAO,aAAa,GAAG,GAAG,KAAK;CAChE,KAAK,UAAU,eAAe,GAAG,OAAO,YAAY,WAAY,GAAG,KAAK;CAExE,MAAM,QAAQ,IAAI,YAAY;E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