document-model 6.2.3 → 6.3.0-dev.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tooling.mjs","names":["schema","schema","schema","schema","schema","schema","declarations","BUILT_IN_SCALARS","CATALOG_SCALARS","typeReference","enumValue","namedType","examples","packageSpecifier","unreadable","packageSpecifier","checkArtifact","description","namedType","exhaustive","namedType","ROOT_TYPES","ROOT_TYPES","ROOT_TYPES"],"sources":["../src/definition/kernel/hashes.ts","../src/definition/kernel/primitives.ts","../src/definition/kernel/diagnostics.ts","../src/definition/compiler/module-definition.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/equals-pattern.ts","../src/definition/kernel/printer.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/structured-diagnostics.ts","../src/definition/tooling/model-directories.ts","../src/definition/tooling/definition-source-resolution.ts","../src/definition/tooling/definition-source-loader.ts","../src/definition/compiler/naming.ts","../src/definition/tooling/check/diagnostic-codes.ts","../src/definition/tooling/report/served-specification.ts","../src/definition/tooling/check/checks/duplicate-identities.ts","../src/definition/tooling/graphql/parse-schema.ts","../src/definition/tooling/check/checks/graphql-schema.ts","../src/definition/tooling/report/logical-collisions.ts","../src/definition/tooling/check/checks/logical-collisions.ts","../src/definition/tooling/check/checks/package-scalar-names.ts","../src/definition/compiler/segments.ts","../src/definition/tooling/graphql/ast-to-structured.ts","../src/definition/tooling/check/stored-specification.ts","../src/definition/tooling/check/checks/retained-serialization.ts","../src/definition/tooling/check/checks/stored-materialization.ts","../src/definition/tooling/check/checks/unregistered-definitions.ts","../src/definition/tooling/report/status.ts","../src/definition/tooling/check/check-project-definitions.ts","../src/definition/tooling/release/diagnostic-codes.ts","../src/definition/tooling/release/checks/host-validation.ts","../src/definition/tooling/release/release-checks.ts","../src/definition/tooling/inspect/diagnostic-codes.ts","../src/definition/tooling/inspect/inspect-project-definitions.ts","../src/definition/tooling/project/unregistered-definitions.ts","../src/definition/tooling/schema-first/project-scalars.ts","../src/definition/compiler/initial-value.ts","../src/scalars/stored-definition.ts","../src/definition/compiler/stored-scalar.ts","../src/definition/kernel/global-registry.ts","../src/definition/dsl/descriptor-registry.ts","../src/definition/dsl/types.ts","../src/definition/dsl/zod.ts","../src/definition/dsl/field-options.ts","../src/definition/dsl/scalar-fields.ts","../src/definition/dsl/field.ts","../src/definition/tooling/schema-first/state-descriptor.ts","../src/definition/tooling/schema-first/schema-first-document-model-module-adapter.ts","../src/definition/tooling/schema-first/stored-locations.ts","../src/definition/tooling/schema-first/stored-models.ts","../src/definition/tooling/project/project-definitions.ts","../src/definition/compiler/graphql-nodes.ts","../src/definition/compiler/graphql-projection.ts","../src/definition/subgraph/projection.ts","../src/definition/tooling/subgraph/claims.ts","../src/definition/tooling/subgraph/diagnostic-codes.ts","../src/definition/tooling/subgraph/schema-first/sdl-conflicts.ts","../src/definition/tooling/subgraph/checks.ts","../src/definition/tooling/subgraph/input.ts","../src/definition/tooling/subgraph/inspection.ts","../src/definition/subgraph/protocol.ts","../src/definition/tooling/subgraph/read.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 return source === undefined ? \"(no source)\" : formatDefinitionSource(source);\n}\n\n/** @experimental A source as `specifier#/export/path`, each segment escaped as a JSON Pointer token. */\nexport function formatDefinitionSource(source: DefinitionSource): string {\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 {\n DefinitionPath,\n DocumentModelDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionDiagnosticInput } from \"../kernel/diagnostics.js\";\nimport type { CompilerDiagnosticCode } from \"./diagnostic-codes.js\";\n\n/**\n * Why `definition` cannot serve the module it is attached to: another\n * document type, or no specification for the module's version.\n */\nexport function definitionModuleMismatch(\n definition: DocumentModelDefinition,\n module: { readonly documentType: string; readonly version?: number },\n path: DefinitionPath,\n): DefinitionDiagnosticInput<CompilerDiagnosticCode> | undefined {\n if (definition.model.documentType !== module.documentType) {\n return {\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"model\", \"documentType\"],\n message:\n \"The structured definition and the stored model describe different document types.\",\n expected: module.documentType,\n received: definition.model.documentType,\n repair:\n \"Materialize the module and its definition from the same declaration.\",\n };\n }\n const { version } = module;\n if (\n version !== undefined &&\n !definition.specifications.some((entry) => entry.version === version)\n ) {\n return {\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"specifications\"],\n message: `The specification history carries no version ${version}, which is the version this module serves.`,\n expected: `a specification for version ${version}`,\n received: definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n repair:\n \"Compose the versions with defineDocumentModelFamily so every module carries the complete history.\",\n };\n }\n return undefined;\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","/**\n * The regular expression source the generator writes for `@equals(value: v)`.\n * The plugin fills its template `/^$1$/` with `String.prototype.replace`, so\n * `v` is inserted unescaped and its replacement tokens (`$&`, `` $` ``, `$'`,\n * `$$`) are expanded first.\n */\nexport function equalsPattern(value: string): string {\n return \"/^$1$/\".replace(\"$1\", value).slice(1, -1);\n}\n\nconst LINE_TERMINATORS = new Set([\"\\n\", \"\\r\", \"
\", \"
\"]);\n\n/**\n * Why an `@equals` pattern cannot be validated the way the generator does,\n * if it cannot. The generator writes the pattern, as `equalsPattern`\n * expands it, into a regex literal: a `/` outside a character class ends\n * that literal, and a line terminator cannot appear in one, so either leaves\n * generated code that does not compile or does not validate.\n */\nexport function equalsPatternProblem(pattern: string):\n | {\n readonly message: string;\n readonly expected: string;\n readonly repair: string;\n }\n | undefined {\n const expected =\n \"a regular expression pattern the generator can write as /^pattern$/\";\n const source = equalsPattern(pattern);\n let inClass = false;\n for (let index = 0; index < source.length; index++) {\n const character = source[index];\n const escaped = character === \"\\\\\";\n if (escaped) index++;\n if (LINE_TERMINATORS.has(source[index])) {\n return {\n message:\n \"The @equals pattern contains a line terminator, which a regular expression literal cannot hold.\",\n expected,\n repair:\n \"Write the line terminator as an escape such as \\\\n, which the regular expression reads the same way.\",\n };\n }\n if (escaped) continue;\n if (character === \"[\") inClass = true;\n else if (character === \"]\") inClass = false;\n else if (character === \"/\" && !inClass) {\n return {\n message:\n \"The @equals pattern contains a / outside a character class, which ends the generated regular expression literal.\",\n expected,\n repair:\n 'Escape the slash as \\\\/ (written \"\\\\\\\\/\" in a JavaScript string), or put it in a character class such as [/].',\n };\n }\n }\n try {\n new RegExp(source);\n } catch (error) {\n return {\n message: `The @equals pattern is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`,\n expected,\n repair:\n \"Fix the pattern, or escape the characters that have a meaning in a regular expression.\",\n };\n }\n return undefined;\n}\n","import type {\n DirectiveUseDefinition,\n EnumTypeDefinition,\n FieldDefinition,\n InputFieldDefinition,\n JsonValue,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { EMPTY_INPUT_FIELD_NAME } from \"./primitives.js\";\n\nconst INDENT = \" \";\nconst LINE = \"\\n\";\n\ntype NamedTypeInventory = ReadonlyMap<string, NamedGraphQLTypeDefinition>;\n\nfunction namedTypeInventory(\n definitions: readonly NamedGraphQLTypeDefinition[],\n): NamedTypeInventory {\n const inventory = new Map<string, NamedGraphQLTypeDefinition>();\n for (const definition of definitions) {\n inventory.set(definition.name, definition);\n }\n return inventory;\n}\n\nconst ESCAPES: Readonly<Record<string, string | undefined>> = {\n '\"': '\\\\\"',\n \"\\\\\": \"\\\\\\\\\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n};\n\nfunction isControlCodePoint(code: number): boolean {\n return code < 0x20 || code === 0x7f;\n}\n\nfunction stringLiteral(value: string): string {\n let printed = '\"';\n for (const point of value) {\n const escape = ESCAPES[point];\n if (escape !== undefined) {\n printed += escape;\n continue;\n }\n const code = point.codePointAt(0) ?? 0;\n printed += isControlCodePoint(code)\n ? `\\\\u${code.toString(16).toUpperCase().padStart(4, \"0\")}`\n : point;\n }\n return `${printed}\"`;\n}\n\nfunction hasControlCodePoint(value: string): boolean {\n for (const point of value) {\n if (isControlCodePoint(point.codePointAt(0) ?? 0)) return true;\n }\n return false;\n}\n\n/**\n * A block string survives the lexer's dedent only when every line is nonempty\n * and carries no leading or trailing whitespace of its own, and the value ends\n * in neither a quote nor a backslash. Every other description prints as an\n * escaped single-line string, which always round-trips.\n */\nexport function blockStringable(value: string): boolean {\n if (!value.includes(LINE)) return false;\n if (value.includes('\"\"\"')) return false;\n if (value.endsWith('\"') || value.endsWith(\"\\\\\")) return false;\n return value\n .split(LINE)\n .every(\n (line) =>\n line.length > 0 &&\n line.trim() === line &&\n !hasControlCodePoint(line) &&\n !line.includes(\"\\r\"),\n );\n}\n\nfunction descriptionLiteral(value: string, indent: string): string {\n if (!blockStringable(value)) return stringLiteral(value);\n const lines = value.split(LINE).map((line) => `${indent}${line}`);\n return ['\"\"\"', ...lines, `${indent}\"\"\"`].join(LINE);\n}\n\nfunction descriptionLine(\n description: string | null,\n indent: string = \"\",\n): string {\n if (description === null) return \"\";\n return `${indent}${descriptionLiteral(description, indent)}${LINE}`;\n}\n\nfunction inlineDescription(description: string | null): string {\n return description === null ? \"\" : `${stringLiteral(description)} `;\n}\n\nfunction printNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new TypeError(\n `A GraphQL value must be finite, received ${String(value)}.`,\n );\n }\n return JSON.stringify(value);\n}\n\nfunction printGraphQLLiteral(value: JsonValue): string {\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return String(value);\n if (typeof value === \"number\") return printNumber(value);\n if (typeof value === \"string\") return stringLiteral(value);\n if (Array.isArray(value)) {\n return `[${value.map(printGraphQLLiteral).join(\", \")}]`;\n }\n const entries = Object.entries(value).map(\n ([key, member]) => `${key}: ${printGraphQLLiteral(member)}`,\n );\n return `{${entries.join(\", \")}}`;\n}\n\nfunction enumValueNames(definition: EnumTypeDefinition): ReadonlySet<string> {\n return new Set(definition.values.map((value) => value.name));\n}\n\nfunction printTypedValue(\n value: JsonValue,\n type: TypeReferenceDefinition,\n inventory: NamedTypeInventory,\n): string {\n if (value === null) return \"null\";\n if (type.kind === \"list\") {\n // GraphQL coerces a single value into a one-item list, so a nonarray\n // default prints against the item type rather than failing here.\n if (!Array.isArray(value)) {\n return printTypedValue(value, type.item, inventory);\n }\n const items = (value as readonly JsonValue[]).map((item) =>\n printTypedValue(item, type.item, inventory),\n );\n return `[${items.join(\", \")}]`;\n }\n if (type.kind === \"scalar\") return printGraphQLLiteral(value);\n const definition = inventory.get(type.name);\n if (definition === undefined) return printGraphQLLiteral(value);\n if (definition.kind === \"enum\") {\n return typeof value === \"string\" && enumValueNames(definition).has(value)\n ? value\n : printGraphQLLiteral(value);\n }\n if (\n definition.kind !== \"input\" ||\n typeof value !== \"object\" ||\n Array.isArray(value)\n ) {\n return printGraphQLLiteral(value);\n }\n const fields = new Map(definition.fields.map((field) => [field.name, field]));\n const entries = Object.entries(value).map(([key, member]) => {\n const field = fields.get(key);\n const printed =\n field === undefined\n ? printGraphQLLiteral(member)\n : printTypedValue(member, field.type, inventory);\n return `${key}: ${printed}`;\n });\n return `{${entries.join(\", \")}}`;\n}\n\nexport function printTypeReference(type: TypeReferenceDefinition): string {\n const base =\n type.kind === \"list\" ? `[${printTypeReference(type.item)}]` : type.name;\n return type.required ? `${base}!` : base;\n}\n\nfunction printDeprecated(deprecated: string | null): string {\n return deprecated === null\n ? \"\"\n : ` @deprecated(reason: ${stringLiteral(deprecated)})`;\n}\n\nfunction printDirectives(\n directives: readonly DirectiveUseDefinition[] | undefined,\n): string {\n if (directives === undefined || directives.length === 0) return \"\";\n return directives\n .map((directive) => {\n if (directive.arguments.length === 0) return ` @${directive.name}`;\n const args = directive.arguments\n .map(\n (argument) =>\n `${argument.name}: ${printGraphQLLiteral(argument.value)}`,\n )\n .join(\", \");\n return ` @${directive.name}(${args})`;\n })\n .join(\"\");\n}\n\nfunction printInputValue(\n field: InputFieldDefinition,\n inventory: NamedTypeInventory,\n): string {\n const defaultValue = Object.hasOwn(field, \"defaultValue\")\n ? ` = ${printTypedValue(field.defaultValue as JsonValue, field.type, inventory)}`\n : \"\";\n return `${field.name}: ${printTypeReference(field.type)}${defaultValue}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;\n}\n\nfunction printInputField(\n field: InputFieldDefinition,\n inventory: NamedTypeInventory,\n): string {\n return `${descriptionLine(field.description, INDENT)}${INDENT}${printInputValue(field, inventory)}`;\n}\n\nfunction printArguments(\n args: readonly InputFieldDefinition[] | undefined,\n inventory: NamedTypeInventory,\n): string {\n if (args === undefined || args.length === 0) return \"\";\n const printed = args\n .map(\n (argument) =>\n `${inlineDescription(argument.description)}${printInputValue(argument, inventory)}`,\n )\n .join(\", \");\n return `(${printed})`;\n}\n\nfunction printField(\n field: FieldDefinition,\n inventory: NamedTypeInventory,\n): string {\n return `${descriptionLine(field.description, INDENT)}${INDENT}${field.name}${printArguments(field.args, inventory)}: ${printTypeReference(field.type)}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;\n}\n\nfunction printImplements(implemented: readonly string[] | undefined): string {\n return implemented === undefined || implemented.length === 0\n ? \"\"\n : ` implements ${implemented.join(\" & \")}`;\n}\n\nfunction printBlock(members: readonly string[]): string {\n return members.length === 0 ? \"\" : ` {${LINE}${members.join(LINE)}${LINE}}`;\n}\n\nexport function printNamedDefinition(\n definition: NamedGraphQLTypeDefinition,\n inventory: NamedTypeInventory = namedTypeInventory([definition]),\n): string {\n const description = descriptionLine(definition.description);\n switch (definition.kind) {\n case \"enum\": {\n const values = definition.values.map(\n (value) =>\n `${descriptionLine(value.description, INDENT)}${INDENT}${value.name}${printDeprecated(value.deprecated)}${printDirectives(value.directives)}`,\n );\n return `${description}enum ${definition.name}${printBlock(values)}`;\n }\n case \"object\": {\n const fields = definition.fields.map((field) =>\n printField(field, inventory),\n );\n return `${description}type ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;\n }\n case \"interface\": {\n const fields = definition.fields.map((field) =>\n printField(field, inventory),\n );\n return `${description}interface ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;\n }\n case \"input\": {\n const fields =\n definition.fields.length === 0\n ? [`${INDENT}${EMPTY_INPUT_FIELD_NAME}: Boolean`]\n : definition.fields.map((field) => printInputField(field, inventory));\n return `${description}input ${definition.name}${printBlock(fields)}`;\n }\n case \"union\":\n return `${description}union ${definition.name} = ${definition.members.join(\" | \")}`;\n }\n}\n\nexport function printSchemaSegment(\n definitions: readonly NamedGraphQLTypeDefinition[],\n known: readonly NamedGraphQLTypeDefinition[] = definitions,\n): string {\n if (definitions.length === 0) return \"\";\n const inventory = namedTypeInventory(known);\n return `${definitions\n .map((definition) => printNamedDefinition(definition, inventory))\n .join(`${LINE}${LINE}`)}${LINE}`;\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\n/**\n * Folds every extension into the type it extends. A repeated definition or\n * member keeps its first occurrence and is reported; an extension-only type\n * starts from its first extension.\n */\nexport function 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\nexport function 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 \"PH-SCALAR-UNKNOWN\": {\n severity: \"error\",\n phase: \"definition\",\n meaning: \"A ph.<Scalar>() factory names no catalog scalar\",\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, the models directory, a model directory's 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 \"The models directory, a model directory, 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 sources select the same module and export path\",\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-STORED-SPEC-MISSING\": {\n severity: \"warning\",\n phase: \"package\",\n meaning:\n \"A model directory holds generated schema-first code without its stored specification\",\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 { definitionModuleMismatch } from \"../../compiler/module-definition.js\";\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 const mismatch = definitionModuleMismatch(\n definition,\n { documentType, version },\n [...path, \"definition\"],\n );\n if (mismatch !== undefined) {\n collector.add(mismatch);\n return undefined;\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 type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRef,\n DefinitionRelatedLocation,\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\nfunction definitionPath(value: unknown): DefinitionPath | undefined {\n const path = snapshotArray(value, []);\n return path.ok && path.value.every(isPathSegment)\n ? (path.value as DefinitionPath)\n : undefined;\n}\n\nfunction relatedSource(value: unknown): DefinitionSource | undefined | null {\n if (value === undefined) return undefined;\n const snapshot = snapshotRecord(value, undefined, []);\n if (!snapshot.ok) return null;\n const { specifier, exportPath } = snapshot.value;\n if (typeof specifier !== \"string\" || !specifier.startsWith(\"./\")) {\n return null;\n }\n const source = { specifier: specifier as `./${string}` };\n if (exportPath === undefined) return source;\n const path = snapshotArray(exportPath, []);\n if (!path.ok || !path.value.every((key) => typeof key === \"string\")) {\n return null;\n }\n return { ...source, exportPath: path.value as string[] };\n}\n\nfunction relatedLocations(\n value: unknown,\n): readonly DefinitionRelatedLocation[] | undefined | null {\n if (value === undefined) return undefined;\n const list = snapshotArray(value, []);\n if (!list.ok) return null;\n const locations: DefinitionRelatedLocation[] = [];\n for (const candidate of list.value) {\n const entry = snapshotRecord(candidate, undefined, []);\n if (!entry.ok) return null;\n const path = definitionPath(entry.value.path);\n const source = relatedSource(entry.value.source);\n const { message } = entry.value;\n if (path === undefined || source === null || typeof message !== \"string\") {\n return null;\n }\n locations.push({\n ...(source !== undefined && { source }),\n path,\n message,\n });\n }\n return locations;\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 = definitionPath(entry.value.path);\n const related = relatedLocations(entry.value.related);\n if (\n typeof code !== \"string\" ||\n !Object.hasOwn(toolingDiagnostics.codes, code) ||\n typeof message !== \"string\" ||\n typeof repair !== \"string\" ||\n path === undefined ||\n related === null ||\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,\n message,\n ...(expected !== undefined && { expected }),\n ...(received !== undefined && { received }),\n repair,\n ...(related !== undefined && { related }),\n }),\n );\n }\n return rebuilt;\n}\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { DOCUMENT_MODEL_ENTRY_FILES } from \"@powerhousedao/shared/clis/definition-sources\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport {\n lstatSync,\n readdirSync,\n realpathSync,\n statSync,\n type Stats,\n} from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\nimport { toolingDiagnostics } from \"./diagnostic-codes.js\";\nimport { describeThrown } from \"./structured-diagnostics.js\";\n\n/** @experimental The models directory a config without `documentModelsDir` uses. */\nexport const DEFAULT_DOCUMENT_MODELS_DIR = \"./document-models\";\n\n/**\n * @experimental What one immediate directory of the models directory holds.\n *\n * - `stored`: a schema-first model, because `<name>/<name>.json` exists. An\n * unreadable or invalid file is still this model's, never a code-first one.\n * - `generated`: schema-first generated code (`gen/` or `v<N>/gen/`) without\n * its stored specification. Its generated modules stay; nothing is pruned.\n * - `module`: a code-first model, whose entry is the directory's one\n * `index.<ext>` module. Generated code wins over an index, which codegen\n * writes into schema-first directories too.\n * - `invalid`: a directory discovery cannot classify; a diagnostic says why.\n * - `none`: no model entry. The declaration scan reports code-first models\n * declared here without an entry.\n */\nexport type DocumentModelDirectory = {\n readonly name: string;\n /** Absolute, as spelled under the models directory. */\n readonly path: string;\n} & (\n | { readonly kind: \"stored\"; readonly specification: `./${string}` }\n | { readonly kind: \"generated\" }\n | { readonly kind: \"module\"; readonly entry: `./${string}` }\n | { readonly kind: \"invalid\" }\n | { readonly kind: \"none\" }\n);\n\n/** @experimental The classified model directories, sorted by name. */\nexport type DocumentModelDirectories = {\n /** Absolute. */\n readonly documentModelsDir: string;\n readonly directories: readonly DocumentModelDirectory[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\n/** `./`-prefixed POSIX path of `path` inside `packageRoot`. */\nexport function packageSpecifier(\n packageRoot: string,\n path: string,\n): `./${string}` {\n return `./${relative(packageRoot, path).split(sep).join(\"/\")}`;\n}\n\nfunction statOrUndefined(\n path: string,\n stat: typeof statSync | typeof lstatSync = statSync,\n): Stats | undefined {\n return stat(path, { throwIfNoEntry: false });\n}\n\nfunction isDirectory(path: string): boolean {\n return statOrUndefined(path)?.isDirectory() === true;\n}\n\nfunction hasGeneratedSchemaFirstLayout(directory: string): boolean {\n if (isDirectory(join(directory, \"gen\"))) return true;\n return readdirSync(directory).some(\n (name) => /^v\\d+$/.test(name) && isDirectory(join(directory, name, \"gen\")),\n );\n}\n\nfunction entryFiles(directory: string): readonly string[] {\n return DOCUMENT_MODEL_ENTRY_FILES.filter(\n (name) => statOrUndefined(join(directory, name))?.isFile() === true,\n );\n}\n\n/**\n * The configured models directory, resolved inside the package, or why it\n * cannot be read. The package root itself is refused: its directories are\n * the package's other sources, not models.\n */\nexport function resolveDocumentModelsDir(\n packageRoot: string,\n config: Readonly<Record<string, unknown>>,\n):\n | { readonly ok: true; readonly path: string }\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n const configured = config.documentModelsDir ?? DEFAULT_DOCUMENT_MODELS_DIR;\n const invalid = (message: string, received: string) => ({\n ok: false as const,\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n path: [\"documentModelsDir\"],\n message,\n expected: \"a package-relative directory such as ./document-models\",\n received,\n repair:\n \"Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models.\",\n }),\n });\n if (typeof configured !== \"string\" || configured.trim() === \"\") {\n return invalid(\n \"documentModelsDir is not a directory path.\",\n JSON.stringify(configured),\n );\n }\n const path = resolve(packageRoot, configured);\n let inside = pathWithin(packageRoot, path) !== null;\n try {\n inside &&=\n pathWithin(\n realpathSync.native(packageRoot),\n realPathThroughExistingParent(path),\n ) !== null;\n } catch {\n inside = false;\n }\n if (!inside) {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n path: [\"documentModelsDir\"],\n message:\n \"documentModelsDir leaves the package root, so its models are not this package's.\",\n expected: \"a directory inside the package\",\n received: configured,\n repair: \"Point documentModelsDir at a directory inside the package.\",\n }),\n };\n }\n if (resolve(path) === resolve(packageRoot)) {\n return invalid(\n \"documentModelsDir names the package root, whose directories are not document models.\",\n configured,\n );\n }\n let stats: Stats | undefined;\n try {\n stats = statOrUndefined(path);\n } catch {\n stats = undefined;\n }\n if (stats !== undefined && !stats.isDirectory()) {\n return invalid(\n \"documentModelsDir names a file, not a directory.\",\n configured,\n );\n }\n return { ok: true, path };\n}\n\nfunction classify(\n packageRoot: string,\n packageRootIdentity: string,\n name: string,\n path: string,\n diagnostics: DefinitionDiagnostic[],\n): DocumentModelDirectory {\n const at = { name, path };\n const specification = join(path, `${name}.json`);\n const stored = statOrUndefined(specification, lstatSync) !== undefined;\n const generated = !stored && hasGeneratedSchemaFirstLayout(path);\n const entries = stored || generated ? [] : entryFiles(path);\n if (!stored && !generated && entries.length === 0) {\n return { ...at, kind: \"none\" };\n }\n const real = realpathSync.native(path);\n if (pathWithin(packageRootIdentity, real) === null) {\n diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message:\n \"This model directory resolves through a symlink that leaves the package root, so its model is not this package's.\",\n expected: \"a model directory whose real path stays inside the package\",\n received: packageSpecifier(packageRoot, path),\n repair:\n \"Replace the symlink with a model directory that really lives in this package.\",\n }),\n );\n return { ...at, kind: \"invalid\" };\n }\n if (stored) {\n return {\n ...at,\n kind: \"stored\",\n specification: packageSpecifier(packageRoot, specification),\n };\n }\n if (generated) {\n diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-PKG-STORED-SPEC-MISSING\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message: `This directory holds generated schema-first code but no ${name}.json, so the model it generated cannot be checked or regenerated.`,\n expected: packageSpecifier(packageRoot, specification),\n received: \"generated code only\",\n repair: `Restore ${name}.json from version control or export it again from the document model editor.`,\n }),\n );\n return { ...at, kind: \"generated\" };\n }\n if (entries.length > 1) {\n const found = entries.map((entry) =>\n packageSpecifier(packageRoot, join(path, entry)),\n );\n diagnostics.push(\n toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-INVALID\",\n source: { specifier: found[0] },\n path: [],\n message:\n \"This model directory has several entry modules, so discovery cannot tell which one exports the model.\",\n expected: \"one index module per model directory\",\n received: found.join(\", \"),\n repair: `Keep one of ${found.join(\", \")} and delete or rename the others.`,\n }),\n );\n return { ...at, kind: \"invalid\" };\n }\n return {\n ...at,\n kind: \"module\",\n entry: packageSpecifier(packageRoot, join(path, entries[0])),\n };\n}\n\n/**\n * @experimental Classifies each immediate directory of the models directory\n * by the files it holds, without importing anything. Discovery never reads\n * the generated barrels beside the directories. A missing models directory\n * holds no models; a directory that cannot be read is `invalid` with a\n * diagnostic, so no caller mistakes it for an absent model.\n */\nexport function discoverDocumentModelDirectories(\n packageRoot: string,\n documentModelsDir: string,\n): DocumentModelDirectories {\n const diagnostics: DefinitionDiagnostic[] = [];\n let names: string[];\n let packageRootIdentity: string;\n try {\n packageRootIdentity = realpathSync.native(packageRoot);\n names = readdirSync(documentModelsDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n diagnostics.push(unreadable(packageRoot, documentModelsDir, error));\n }\n return { documentModelsDir, directories: [], diagnostics };\n }\n const directories = names\n .filter((name) => name !== \"node_modules\" && !name.startsWith(\".\"))\n .sort(compareCodeUnits)\n .flatMap((name): DocumentModelDirectory[] => {\n const path = join(documentModelsDir, name);\n try {\n if (!isDirectory(path)) return [];\n return [\n classify(packageRoot, packageRootIdentity, name, path, diagnostics),\n ];\n } catch (error) {\n diagnostics.push(unreadable(packageRoot, path, error));\n return [{ name, path, kind: \"invalid\" }];\n }\n });\n return { documentModelsDir, directories, diagnostics };\n}\n\nfunction unreadable(\n packageRoot: string,\n path: string,\n error: unknown,\n): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message:\n \"This path under the document models directory could not be read, so discovery cannot tell which model it holds.\",\n expected: \"a readable directory\",\n received: describeThrown(error),\n repair:\n \"Fix the permissions of the path, or move it out of the document models directory.\",\n });\n}\n","import {\n COMMONJS_DEFINITION_SOURCE,\n COMMONJS_DEFINITION_SOURCE_REPAIR,\n DEFINITION_SOURCE_EXTENSION,\n} from \"@powerhousedao/shared/clis/definition-sources\";\nimport type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n pathWithin,\n realPathThroughExistingParent,\n} from \"@powerhousedao/shared/clis/real-paths\";\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\nimport { dirname, posix, resolve } 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\";\nimport {\n discoverDocumentModelDirectories,\n type DocumentModelDirectory,\n packageSpecifier,\n resolveDocumentModelsDir,\n} from \"./model-directories.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\n/** What discovery read besides the sources it resolved. */\nexport type DiscoveryResolution = InternalResolution & {\n /** Absolute; absent when the configured directory cannot be read. */\n readonly documentModelsDir?: string;\n readonly directories: readonly DocumentModelDirectory[];\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 origin: DefinitionSourceOrigin,\n documentModelsDir: `./${string}`,\n sources: readonly DefinitionSource[],\n stored: readonly DefinitionSource[] = [],\n): DefinitionSourceSet {\n const value = { origin, documentModelsDir, sources, stored };\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\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 readonly expected?: string;\n readonly repair?: string;\n };\n\nexport function 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 (COMMONJS_DEFINITION_SOURCE.test(value)) {\n return {\n ok: false,\n code: \"PH-CONFIG-SOURCE-INVALID\",\n message:\n \"A definition source is evaluated as an ES module, so a CommonJS module cannot be one.\",\n expected: \"a .ts, .mts, .tsx, .js, .mjs or .jsx module\",\n repair: COMMONJS_DEFINITION_SOURCE_REPAIR,\n };\n }\n if (!DEFINITION_SOURCE_EXTENSION.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/** Where a lexically contained module really lives, unless a symlink takes it out of the package. */\nexport function realModulePath(\n packageRoot: string,\n packageRootIdentity: string,\n specifier: `./${string}`,\n):\n | { readonly ok: true; readonly moduleIdentity: string }\n | { readonly ok: false; readonly reason: \"unresolvable\" | \"outside\" } {\n let moduleIdentity: string;\n try {\n moduleIdentity = realPathThroughExistingParent(\n resolve(packageRoot, ...specifier.slice(2).split(\"/\")),\n );\n } catch {\n return { ok: false, reason: \"unresolvable\" };\n }\n return pathWithin(packageRootIdentity, moduleIdentity) !== null\n ? { ok: true, moduleIdentity }\n : { ok: false, reason: \"outside\" };\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:\n normalized.expected ??\n \"a './' path contained by the selected package root\",\n received: entry.specifier,\n repair:\n normalized.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 real = realModulePath(packageRoot, packageRootIdentity, specifier);\n if (!real.ok && real.reason === \"unresolvable\") {\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 (!real.ok) {\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: real.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 sources reach the same module and export path, so one of them can only repeat the other's definitions. A model directory symlinked to another is one of them.\",\n expected: \"one source per module and export path\",\n received: `${group.length} sources`,\n repair:\n \"Remove every duplicate except one, or replace a symlinked model directory with the directory itself.\",\n related: rest.map((entry) => ({\n source: entry.source,\n path: entry.position,\n message: \"This source 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\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\nexport function 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\n/** The selected config file, its directory, and that directory's real path when it exists. */\nexport function packageRoots(request: DefinitionSourceSelectionRequest): {\n readonly configFile: string;\n readonly packageRoot: string;\n readonly packageRootIdentity: string;\n} {\n const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);\n const packageRoot = dirname(configFile);\n try {\n const packageRootIdentity = realpathSync.native(packageRoot);\n return { configFile, packageRoot, packageRootIdentity };\n } catch {\n // Reading the config reports the missing directory.\n return { configFile, packageRoot, packageRootIdentity: packageRoot };\n }\n}\n\ntype ResolutionBase = Roots & {\n readonly documentModelsDir: `./${string}`;\n readonly documentModelsPath?: string;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\nfunction readPackage(\n request: DefinitionSourceSelectionRequest,\n): ResolutionBase & { readonly ok: boolean } {\n const { configFile, ...roots } = packageRoots(request);\n const fallback = {\n ...roots,\n documentModelsDir: \"./document-models\" as const,\n };\n let config: Readonly<Record<string, unknown>> = {};\n if (request.allowMissingConfig !== true || existsSync(configFile)) {\n const read = readConfigObject(configFile);\n if (!read.ok) {\n return {\n ...fallback,\n ok: false,\n diagnostics: [\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: read.reason,\n repair: CONFIG_FAILURE_REPAIR[read.reason],\n }),\n ],\n };\n }\n config = read.value;\n }\n const directory = resolveDocumentModelsDir(roots.packageRoot, config);\n if (!directory.ok) {\n return { ...fallback, ok: false, diagnostics: [directory.diagnostic] };\n }\n return {\n ...roots,\n ok: true,\n documentModelsDir: packageSpecifier(roots.packageRoot, directory.path),\n documentModelsPath: directory.path,\n diagnostics: [],\n };\n}\n\nfunction failed(\n base: ResolutionBase,\n origin: DefinitionSourceOrigin,\n diagnostics: readonly DefinitionDiagnostic[],\n sources: readonly DefinitionSource[] = [],\n stored: readonly DefinitionSource[] = [],\n): InternalResolution {\n return {\n packageRoot: base.packageRoot,\n packageRootIdentity: base.packageRootIdentity,\n status: \"failed\",\n sourceSet: sourceSet(origin, base.documentModelsDir, sources, stored),\n diagnostics: sortDefinitionDiagnostics(diagnostics),\n resolved: [],\n };\n}\n\nfunction resolveSources(\n base: ResolutionBase,\n origin: DefinitionSourceOrigin,\n entries: readonly {\n readonly value: unknown;\n readonly position: DefinitionPath;\n }[],\n stored: readonly DefinitionSource[],\n diagnostics: readonly DefinitionDiagnostic[],\n): InternalResolution {\n const normalized = entries.map(({ value, position }) =>\n normalizeEntry(value, position, base.packageRoot, base.packageRootIdentity),\n );\n const candidates = normalized\n .flatMap((result) => (\"source\" in result ? [result.source] : []))\n .sort((left, right) => compareDefinitionSources(left.source, right.source));\n const resolved =\n origin === \"discovery\"\n ? candidates.filter(\n (entry, index) =>\n candidates.findIndex(\n (other) => other.moduleIdentity === entry.moduleIdentity,\n ) === index,\n )\n : candidates;\n const sources = resolved.map((entry) => entry.source);\n const errors = [\n ...normalized.flatMap((result) =>\n \"diagnostic\" in result ? [result.diagnostic] : [],\n ),\n ...duplicateDiagnostics(resolved),\n ];\n if (\n errors.length > 0 ||\n diagnostics.some(({ severity }) => severity === \"error\")\n ) {\n return failed(base, origin, [...diagnostics, ...errors], sources, stored);\n }\n const common = {\n packageRoot: base.packageRoot,\n packageRootIdentity: base.packageRootIdentity,\n sourceSet: sourceSet(origin, base.documentModelsDir, sources, stored),\n diagnostics: sortDefinitionDiagnostics(diagnostics),\n };\n return sources.length === 0\n ? {\n ...common,\n status: \"skipped\",\n skipReason: \"no-document-models\",\n resolved: [],\n }\n : { ...common, status: \"ready\", resolved };\n}\n\n/**\n * Discovers the package's model directories: each code-first directory's\n * entry module becomes a source, each schema-first one's stored file is\n * listed beside them. Nothing is imported.\n */\nexport function resolveDefinitionSources(\n request: DefinitionSourceSelectionRequest,\n): DiscoveryResolution {\n const base = readPackage(request);\n if (!base.ok || base.documentModelsPath === undefined) {\n return {\n ...failed(base, \"discovery\", base.diagnostics),\n directories: [],\n };\n }\n const found = discoverDocumentModelDirectories(\n base.packageRoot,\n base.documentModelsPath,\n );\n const entries = found.directories.flatMap((directory) =>\n directory.kind === \"module\"\n ? [{ value: { specifier: directory.entry }, position: [] }]\n : [],\n );\n const stored = found.directories.flatMap((directory) =>\n directory.kind === \"stored\" ? [{ specifier: directory.specification }] : [],\n );\n return {\n ...resolveSources(base, \"discovery\", entries, stored, found.diagnostics),\n documentModelsDir: base.documentModelsPath,\n directories: found.directories,\n };\n}\n\n/**\n * @experimental Resolves sources a caller names instead of discovering them.\n */\nexport function resolveRequestedSources(\n request: DefinitionSourceSelectionRequest & {\n readonly sources: readonly unknown[];\n },\n): InternalResolution {\n const base = readPackage(request);\n if (!base.ok) return failed(base, \"request\", base.diagnostics);\n return resolveSources(\n base,\n \"request\",\n request.sources.map((value, index) => ({\n value,\n position: [\"sources\", index],\n })),\n [],\n [],\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 sources discovery finds, resolved without importing\n * 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 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 normalizeSpecifier,\n packageRoots,\n publicResolution,\n realModulePath,\n resolveDefinitionSources,\n resolveRequestedSources,\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 export.\",\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\n/**\n * How many definitions `value` holds. One that an earlier source already\n * collected is counted again without being collected twice.\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 \"Export 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: \"This source module does not exist.\",\n expected: \"an existing module inside the package\",\n received: source.specifier,\n repair:\n \"Restore the module, or remove the model directory that names it.\",\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 revisionDiagnostic(revision: unknown): DefinitionDiagnostic {\n return 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 revision === \"string\" ? revision : describeReceived(revision),\n repair: \"Pass a revision digest of the package's current files.\",\n });\n}\n\nfunction refusedModule(\n specifier: `./${string}`,\n code: \"PH-CONFIG-SOURCE-INVALID\" | \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n message: string,\n refusal: { readonly expected?: string; readonly repair?: string } = {},\n): { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n return {\n ok: false,\n diagnostic: toolingDiagnostics.create({\n code,\n source: { specifier },\n path: [],\n message,\n expected:\n refusal.expected ??\n \"a './' module path whose real path stays inside the package root\",\n received: specifier,\n repair:\n refusal.repair ??\n \"Keep the module inside the package, and do not reach it through a symlink that leaves the package.\",\n }),\n };\n}\n\ntype PackageModule = {\n readonly specifier: `./${string}`;\n readonly packageRootIdentity: string;\n readonly moduleIdentity: string;\n};\n\n/** The selected sources' containment rules, so a module outside the package is never imported. */\nfunction containedPackageModule(\n request: DefinitionSourceSelectionRequest & {\n readonly specifier: `./${string}`;\n },\n):\n | ({ readonly ok: true } & PackageModule)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic } {\n const { packageRoot, packageRootIdentity } = packageRoots(request);\n const normalized = normalizeSpecifier(request.specifier);\n if (!normalized.ok) {\n return refusedModule(\n request.specifier,\n normalized.code,\n normalized.message,\n normalized,\n );\n }\n const real = realModulePath(\n packageRoot,\n packageRootIdentity,\n normalized.specifier,\n );\n if (real.ok) {\n return {\n ok: true,\n specifier: normalized.specifier,\n packageRootIdentity,\n moduleIdentity: real.moduleIdentity,\n };\n }\n return real.reason === \"outside\"\n ? refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n \"The package module resolves through a symlink that leaves the package root.\",\n )\n : refusedModule(\n request.specifier,\n \"PH-CONFIG-SOURCE-INVALID\",\n \"The package module path could not be resolved.\",\n );\n}\n\n/** What discovery read besides its sources; absent for requested sources. */\ntype Discovered = Pick<\n LoadedDefinitionSet,\n \"documentModelsDir\" | \"directories\"\n>;\n\nfunction empty(\n resolution: DefinitionSourceResolution,\n discovered: Discovered,\n): LoadedDefinitionSet {\n return {\n ...resolution,\n ...discovered,\n documentModels: [],\n upgradeManifests: [],\n sourcesWithDefinitions: [],\n };\n}\n\n/**\n * @experimental Imports the discovered 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 directory 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 /**\n * Imports the entry module of every model directory discovery finds and\n * collects the models, families and upgrade manifests it exports.\n */\n async normalizeDefinitionSources(\n request: DefinitionSourceLoadRequest,\n ): Promise<LoadedDefinitionSet> {\n request.signal?.throwIfAborted();\n const resolution = resolveDefinitionSources(request);\n return await this.#normalize(resolution, request, {\n ...(resolution.documentModelsDir !== undefined && {\n documentModelsDir: resolution.documentModelsDir,\n }),\n directories: resolution.directories,\n });\n }\n\n /**\n * @experimental Loads sources the caller names, through the same imports\n * and checks as discovered ones.\n */\n async normalizeRequestedSources(\n request: DefinitionSourceLoadRequest & {\n readonly sources: readonly unknown[];\n },\n ): Promise<LoadedDefinitionSet> {\n request.signal?.throwIfAborted();\n return await this.#normalize(resolveRequestedSources(request), request, {});\n }\n\n async #normalize(\n resolution: InternalResolution,\n request: DefinitionSourceLoadRequest,\n discovered: Discovered,\n ): Promise<LoadedDefinitionSet> {\n if (resolution.status !== \"ready\") {\n return empty(publicResolution(resolution), discovered);\n }\n if (!isSha256Digest(request.packageRevision)) {\n return empty(\n {\n packageRoot: resolution.packageRoot,\n sourceSet: resolution.sourceSet,\n status: \"failed\",\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n },\n discovered,\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: [...resolution.diagnostics],\n visited: new Map(),\n claimed: new Map(),\n };\n const sourcesWithDefinitions: DefinitionSource[] = [];\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 sourcesWithDefinitions.push(entry.source);\n } else if (resolution.sourceSet.origin === \"request\") {\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 it adds no model to the package.\",\n expected:\n \"a module or family materialize returned, or a collection holding them\",\n received: \"no recognized definition\",\n repair:\n \"Export the value materialize(...) returned from this module.\",\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 ...discovered,\n status: diagnostics.some(({ severity }) => severity === \"error\")\n ? \"failed\"\n : \"ready\",\n diagnostics,\n documentModels: sortBySource(collected.documentModels),\n upgradeManifests: sortBySource(collected.upgradeManifests),\n sourcesWithDefinitions,\n };\n }\n\n /**\n * @experimental Imports one package module through the same importer and\n * package revision as the selected sources, so a module both reach is\n * evaluated once. A module outside the package root is refused as an\n * outside source is. Experimental: tooling uses it for the project scalars\n * module while code-first projects are introduced.\n */\n async importPackageModule(\n request: DefinitionSourceLoadRequest & {\n readonly specifier: `./${string}`;\n },\n ): Promise<\n | {\n readonly ok: true;\n readonly namespace: Readonly<Record<string, unknown>>;\n }\n | {\n readonly ok: false;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n }\n > {\n request.signal?.throwIfAborted();\n if (!isSha256Digest(request.packageRevision)) {\n return {\n ok: false,\n diagnostics: [revisionDiagnostic(request.packageRevision)],\n };\n }\n const contained = containedPackageModule(request);\n if (!contained.ok)\n return { ok: false, diagnostics: [contained.diagnostic] };\n await this.#retainRevision(request.packageRevision);\n const imported = await this.#import(contained, request);\n return imported.ok\n ? { ok: true, namespace: imported.value }\n : {\n ok: false,\n diagnostics: imported.diagnostics({ specifier: request.specifier }),\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 /** One evaluation per module and revision, whichever path asks first. */\n async #import(\n module: PackageModule,\n request: DefinitionSourceLoadRequest,\n ): Promise<ImportedNamespace> {\n const { moduleIdentity } = module;\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: module.packageRootIdentity,\n specifier: module.specifier,\n packageRevision: request.packageRevision,\n ...(request.signal !== undefined && { signal: request.signal }),\n });\n this.#imports.set(moduleIdentity, namespace);\n void namespace.catch(() => this.#imports.delete(moduleIdentity));\n }\n try {\n return { ok: true, value: namespaceSnapshot(await namespace) };\n } catch (error) {\n const missing = !existsSync(moduleIdentity);\n return {\n ok: false,\n diagnostics: (source) => importDiagnostics(error, source, missing),\n };\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 // Evaluate serially so aliases and their family share one module evaluation.\n for (const { moduleIdentity, source } of resolution.resolved) {\n if (results.has(moduleIdentity)) continue;\n const module = {\n specifier: source.specifier,\n packageRootIdentity: resolution.packageRootIdentity,\n moduleIdentity,\n };\n results.set(moduleIdentity, await this.#import(module, request));\n }\n return results;\n }\n}\n","import { compilerDiagnostics } from \"./diagnostic-codes.js\";\nimport type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { camelCase, constantCase, pascalCase } from \"change-case\";\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\n\ntype ActionTypeWords<\n TKey extends string,\n TPrevious extends string = \"\",\n TResult extends string = \"\",\n TSeparator extends string = \"\",\n> = TKey extends `${infer TFirst}${infer TRest}`\n ? TFirst extends \"_\"\n ? ActionTypeWords<TRest, \"\", TResult, TResult extends \"\" ? \"\" : \"_\">\n : ActionTypeWords<\n TRest,\n TFirst,\n `${TResult}${TSeparator extends \"_\"\n ? \"_\"\n : TFirst extends Lowercase<TFirst>\n ? \"\"\n : TPrevious extends \"\"\n ? \"\"\n : TPrevious extends Digit\n ? \"_\"\n : TPrevious extends Uppercase<TPrevious>\n ? TRest extends `${infer TNext}${string}`\n ? TNext extends Uppercase<TNext>\n ? \"\"\n : \"_\"\n : \"\"\n : \"_\"}${Uppercase<TFirst>}`\n >\n : TResult;\n\nexport type DocumentModelActionType<TKey extends string> = string extends TKey\n ? string\n : ActionTypeWords<TKey>;\n\nexport type DocumentModelNames = {\n readonly documentType: string;\n readonly graphQLName: string;\n readonly globalStateRootName: string;\n readonly localStateRootName: string;\n};\n\ntype DocumentModelModuleNames = {\n readonly storedName: string;\n readonly operationsInterfaceName: string;\n readonly actionNamespaceName: string;\n};\n\ntype DocumentModelOperationNames = {\n readonly storedName: string;\n readonly actionType: string;\n readonly inputTypeName: string;\n readonly creatorKey: string;\n readonly reducerMethod: string;\n};\n\ntype DocumentModelErrorNames = {\n readonly key: string;\n readonly storedName: string;\n readonly storedCode: string;\n};\n\nexport function deriveDocumentModelNames(\n model: { readonly id: string; readonly name: string },\n overrides: Partial<DocumentModelNames> = {},\n): DocumentModelNames {\n const graphQLName = overrides.graphQLName ?? pascalCase(model.name);\n return {\n documentType: overrides.documentType ?? model.id,\n graphQLName,\n globalStateRootName: overrides.globalStateRootName ?? `${graphQLName}State`,\n localStateRootName:\n overrides.localStateRootName ?? `${graphQLName}LocalState`,\n };\n}\n\nexport function deriveDocumentModelModuleNames(\n modelName: string,\n moduleKey: string,\n overrides: Partial<DocumentModelModuleNames> = {},\n): DocumentModelModuleNames {\n const modulePascal = pascalCase(moduleKey);\n return {\n storedName: overrides.storedName ?? modulePascal,\n operationsInterfaceName:\n overrides.operationsInterfaceName ??\n `${pascalCase(modelName)}${modulePascal}Operations`,\n actionNamespaceName:\n overrides.actionNamespaceName ??\n `${camelCase(modelName)}${modulePascal}Actions`,\n };\n}\n\nexport function deriveDocumentModelOperationNames(\n operationKey: string,\n overrides: Partial<DocumentModelOperationNames> = {},\n): DocumentModelOperationNames {\n const operationPascal = pascalCase(operationKey);\n const actionType = overrides.actionType ?? constantCase(operationKey);\n return {\n storedName: overrides.storedName ?? operationPascal,\n actionType,\n inputTypeName: overrides.inputTypeName ?? `${operationPascal}Input`,\n creatorKey: overrides.creatorKey ?? camelCase(constantCase(operationKey)),\n reducerMethod:\n overrides.reducerMethod ?? `${camelCase(operationKey)}Operation`,\n };\n}\n\n// Action types the base reducer or the reactor reduces before a model's own\n// reducer sees them, and RETRACT, which replay reads as a retraction. NOOP is\n// left out because the model's reducer still runs.\nexport const PLATFORM_ACTION_TYPES: ReadonlySet<string> = new Set([\n \"SET_NAME\",\n \"SET_PREFERRED_EDITOR\",\n \"UNDO\",\n \"REDO\",\n \"RETRACT\",\n \"CREATE_DOCUMENT\",\n \"DELETE_DOCUMENT\",\n \"UPGRADE_DOCUMENT\",\n \"ADD_RELATIONSHIP\",\n \"REMOVE_RELATIONSHIP\",\n \"UPDATE_RELATIONSHIP\",\n \"PURGE_DOCUMENT\",\n]);\n\nexport function deriveOperationErrorClassName(errorKey: string): string {\n return pascalCase(errorKey);\n}\n\nexport function deriveDocumentModelErrorNames(\n errorKey: string,\n authored: {\n readonly name?: string | null;\n readonly code?: string | null;\n } = {},\n): DocumentModelErrorNames {\n return {\n key: errorKey,\n storedName: authored.name ?? errorKey,\n storedCode: authored.code ?? errorKey,\n };\n}\n\nexport type DerivedOperationNames = {\n readonly key: string;\n readonly names: DocumentModelOperationNames;\n};\n\nexport type DerivedModuleNames = {\n readonly key: string;\n readonly names: DocumentModelModuleNames;\n readonly operations: readonly DerivedOperationNames[];\n};\n\ntype Claim = {\n readonly path: readonly string[];\n readonly label: string;\n};\n\ntype NameClaim = {\n readonly kind: string;\n readonly slot: string;\n readonly value: string;\n};\n\ntype Collision = {\n readonly first: Claim;\n readonly names: string[];\n actionType: boolean;\n};\n\nconst MODULE_NAME_KINDS = [\n \"storedName\",\n \"operationsInterfaceName\",\n \"actionNamespaceName\",\n] as const satisfies readonly (keyof DocumentModelModuleNames)[];\n\nconst OPERATION_NAME_KINDS = [\n \"actionType\",\n \"storedName\",\n \"inputTypeName\",\n \"creatorKey\",\n \"reducerMethod\",\n] as const satisfies readonly (keyof DocumentModelOperationNames)[];\n\nfunction nameSlot(\n owner: \"module\" | \"operation\",\n scope: string,\n kind: string,\n value: string,\n): string {\n return JSON.stringify([owner, scope, kind, value]);\n}\n\nfunction moduleNameClaims(\n names: DocumentModelModuleNames,\n): readonly NameClaim[] {\n return MODULE_NAME_KINDS.map((kind) => ({\n kind,\n slot: nameSlot(\"module\", \"model\", kind, names[kind]),\n value: names[kind],\n }));\n}\n\nfunction operationNameClaims(\n moduleKey: string,\n names: DocumentModelOperationNames,\n): readonly NameClaim[] {\n return OPERATION_NAME_KINDS.map((kind) => {\n const scope =\n kind === \"storedName\" || kind === \"reducerMethod\" ? moduleKey : \"model\";\n return {\n kind,\n slot: nameSlot(\"operation\", scope, kind, names[kind]),\n value: names[kind],\n };\n });\n}\n\nfunction claim(\n claims: Map<string, Claim>,\n claimant: Claim,\n nameClaims: readonly NameClaim[],\n): readonly Collision[] {\n const collisions = new Map<Claim, Collision>();\n for (const { kind, slot, value } of nameClaims) {\n const first = claims.get(slot);\n if (first === undefined) {\n claims.set(slot, claimant);\n continue;\n }\n const collision = collisions.get(first) ?? {\n first,\n names: [],\n actionType: false,\n };\n collision.names.push(`${kind} ${JSON.stringify(value)}`);\n if (kind === \"actionType\") collision.actionType = true;\n collisions.set(first, collision);\n }\n return [...collisions.values()];\n}\n\nfunction collisionDiagnostic(\n claimant: Claim,\n collision: Collision,\n): DefinitionDiagnostic {\n const list = collision.names.join(\", \");\n return compilerDiagnostics.create({\n code: collision.actionType\n ? \"PH-DM-DUPLICATE-ACTION\"\n : \"PH-DM-DUPLICATE-NAME\",\n path: claimant.path,\n message: `${claimant.label} derives ${list}, already derived by ${collision.first.label}.`,\n expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,\n received: list,\n repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,\n related: [\n {\n path: collision.first.path,\n message: `${collision.first.label} derives the same ${collision.names.length === 1 ? \"name\" : \"names\"}.`,\n },\n ],\n });\n}\n\nexport function checkDerivedNameCollisions(\n modules: readonly DerivedModuleNames[],\n): readonly DefinitionDiagnostic[] {\n const claims = new Map<string, Claim>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const module of modules) {\n const moduleClaim: Claim = {\n path: [\"modules\", module.key],\n label: `module ${JSON.stringify(module.key)}`,\n };\n for (const collision of claim(\n claims,\n moduleClaim,\n moduleNameClaims(module.names),\n )) {\n diagnostics.push(collisionDiagnostic(moduleClaim, collision));\n }\n for (const operation of module.operations) {\n const operationClaim: Claim = {\n path: [\"modules\", module.key, \"operations\", operation.key],\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n for (const collision of claim(\n claims,\n operationClaim,\n operationNameClaims(module.key, operation.names),\n )) {\n diagnostics.push(collisionDiagnostic(operationClaim, collision));\n }\n }\n }\n return diagnostics;\n}\n\n/** The symbol spellings codegen derives from a stored schema-first name. */\nexport function deriveDocumentModelSymbolNames(name: string) {\n return {\n typeName: pascalCase(name),\n memberName: camelCase(name),\n constantName: constantCase(name),\n };\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const checkDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-DM-DUPLICATE-ERROR-CODE\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one operation persist the same error code, so a caller cannot tell them apart\",\n },\n \"PH-DM-ERROR-CLASS-CONFLICT\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"Two errors of one module generate the same error class with different codes\",\n },\n \"PH-PKG-SCALAR-CONFLICT\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"Two models of one package use different project scalars with one name, and a host declares each scalar once\",\n },\n \"PH-PKG-DEFINITION-UNREGISTERED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first document model under the document models directory is exported by no model entry module, so the package leaves it out\",\n },\n },\n toolingDiagnostics,\n);\n\nexport type CheckDiagnosticCode = keyof typeof checkDiagnostics.codes;\n","import type {\n DefinitionRef,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\n\n/**\n * The specification an artifact serves, and its index in the history. Every\n * member of a family carries the whole history, so a check that read every\n * specification of every artifact would report one defect once per member.\n */\nexport function servedSpecification(artifact: NormalizedDocumentModelArtifact):\n | {\n readonly specification: DocumentModelSpecificationDefinition;\n readonly index: number;\n }\n | undefined {\n const index = artifact.definition.specifications.findIndex(\n ({ version }) => version === artifact.version,\n );\n return index === -1\n ? undefined\n : { specification: artifact.definition.specifications[index], index };\n}\n\nexport function documentModelRef(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRef {\n return {\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n deriveOperationErrorClassName,\n PLATFORM_ACTION_TYPES,\n} from \"../../../compiler/naming.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Claim = { readonly path: DefinitionPath; readonly label: string };\n\n/** Codegen's rule: an empty or absent code falls back to the class name. */\nfunction effectiveErrorCode(code: string | null, className: string): string {\n return code?.trim() || className;\n}\n\n/**\n * The compiler refuses duplicate module keys, action types and creator keys,\n * an action type the document runtime owns, and an error class with two codes\n * in one module, before a code-first module exists, so for those this check fires only on a stored schema-first model.\n * Two errors of one operation sharing a code pass the compiler in both modes.\n */\nfunction duplicates(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const diagnostics: DefinitionDiagnostic[] = [];\n const report = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n detail: {\n readonly message: string;\n readonly expected: string;\n readonly received: string;\n readonly repair: string;\n },\n ) =>\n diagnostics.push(\n checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: claimant.path,\n ...detail,\n related: [\n {\n source: artifact.source,\n path: first.path,\n message: `${first.label} claims it first.`,\n },\n ],\n }),\n );\n const shared = (\n code: CheckDiagnosticCode,\n claimant: Claim,\n first: Claim,\n [kind, value]: readonly [string, string],\n repair: string,\n ) =>\n report(code, claimant, first, {\n message: `${claimant.label} and ${first.label} share the ${kind} ${value}.`,\n expected: `one declaration per ${kind}`,\n received: value,\n repair,\n });\n\n const modules = new Map<string, Claim>();\n const actionTypes = new Map<string, Claim>();\n const operationKeys = new Map<string, Claim>();\n specification.modules.forEach((module, moduleIndex) => {\n const modulePath = [\"specifications\", index, \"modules\", moduleIndex];\n const moduleClaim = {\n path: modulePath,\n label: `module ${JSON.stringify(module.key)}`,\n };\n const firstModule = modules.get(module.key);\n if (firstModule === undefined) modules.set(module.key, moduleClaim);\n else {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n moduleClaim,\n firstModule,\n [\"key\", module.key],\n \"Rename one of the modules.\",\n );\n }\n const errorClasses = new Map<string, Claim & { readonly code: string }>();\n module.operations.forEach((operation, operationIndex) => {\n const operationPath = [...modulePath, \"operations\", operationIndex];\n const claim = {\n path: operationPath,\n label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`,\n };\n if (PLATFORM_ACTION_TYPES.has(operation.actionType)) {\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DM-DUPLICATE-ACTION\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: [...operationPath, \"key\"],\n message: `${claim.label} has action type ${operation.actionType}, which the document runtime reduces itself, so this operation's reducer would never run.`,\n expected: \"an action type the document runtime does not own\",\n received: operation.actionType,\n repair: \"Rename the operation.\",\n }),\n );\n }\n const firstAction = actionTypes.get(operation.actionType);\n const firstKey = operationKeys.get(operation.key);\n if (firstAction !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ACTION\",\n claim,\n firstAction,\n [\"action type\", operation.actionType],\n \"Rename one of the operations; a replayed history cannot tell which reducer wrote a shared action type.\",\n );\n } else if (firstKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n claim,\n firstKey,\n [\"creator key\", operation.key],\n \"Rename one of the operations; action creators share one namespace.\",\n );\n }\n actionTypes.set(operation.actionType, firstAction ?? claim);\n operationKeys.set(operation.key, firstKey ?? claim);\n\n const errorKeys = new Map<string, Claim>();\n const errorCodes = new Map<string, Claim>();\n operation.errors.forEach((error, errorIndex) => {\n const errorClaim = {\n path: [...operationPath, \"errors\", errorIndex],\n label: `error ${JSON.stringify(error.key)}`,\n };\n const className = deriveOperationErrorClassName(\n error.name ?? error.key,\n );\n const code = effectiveErrorCode(error.code, className);\n const sameKey = errorKeys.get(error.key);\n const sameCode = errorCodes.get(code);\n const sameClass = errorClasses.get(className);\n if (sameKey !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-NAME\",\n errorClaim,\n sameKey,\n [\"key\", error.key],\n \"Rename one of the errors; each generates its own class.\",\n );\n } else if (sameCode !== undefined) {\n shared(\n \"PH-DM-DUPLICATE-ERROR-CODE\",\n errorClaim,\n sameCode,\n [\"code\", code],\n \"Give each error of the operation its own code, so a caller can tell them apart.\",\n );\n } else if (sameClass !== undefined && sameClass.code !== code) {\n report(\"PH-DM-ERROR-CLASS-CONFLICT\", errorClaim, sameClass, {\n message: `${errorClaim.label} of ${claim.label} gives the error class ${className} the code ${JSON.stringify(code)}, and ${sameClass.label} gives it ${JSON.stringify(sameClass.code)}.`,\n expected: sameClass.code,\n received: code,\n repair: `Give both ${className} errors the same code, or give one another name; a module generates one ${className} class.`,\n });\n }\n errorKeys.set(error.key, sameKey ?? errorClaim);\n errorCodes.set(code, sameCode ?? errorClaim);\n if (sameClass === undefined) {\n errorClasses.set(className, {\n ...errorClaim,\n label: `${errorClaim.label} of ${claim.label}`,\n code,\n });\n }\n });\n });\n });\n return diagnostics;\n}\n\nexport const duplicateIdentitiesCheck: DefinitionCheck = {\n name: \"duplicate-identities\",\n run: ({ artifacts }) => artifacts.flatMap(duplicates),\n};\n","import type { LocationFreeGraphQLDocumentNode } from \"@powerhousedao/shared/document-model\";\nimport type * as GraphQL from \"graphql\";\nimport type { validateSDL } from \"graphql/validation/validate.js\";\nimport { createRequire } from \"node:module\";\n\n/** graphql-js, plus the SDL validation its package index does not export. */\nexport type GraphQLModule = typeof GraphQL & {\n readonly validateSDL: typeof validateSDL;\n};\n\nlet graphql: GraphQLModule | undefined;\n\n/**\n * `graphql` is an optional peer: only tooling that reads SDL needs it, and a\n * package that imports document-model at runtime must not pay for it.\n */\nexport function loadGraphQL(): GraphQLModule {\n if (graphql !== undefined) return graphql;\n const require = createRequire(import.meta.url);\n let loaded: unknown;\n let validation: Partial<Pick<GraphQLModule, \"validateSDL\">>;\n try {\n loaded = require(\"graphql\");\n validation = require(\"graphql/validation/validate.js\") as typeof validation;\n } catch (error) {\n throw new Error(\n \"Reading GraphQL SDL needs the optional peer dependency graphql@^16. Install it in the package that runs this tool.\",\n { cause: error },\n );\n }\n if (\n loaded === null ||\n typeof loaded !== \"object\" ||\n typeof (loaded as Partial<GraphQLModule>).parse !== \"function\" ||\n typeof (loaded as Partial<GraphQLModule>).buildASTSchema !== \"function\" ||\n typeof validation.validateSDL !== \"function\"\n ) {\n throw new Error(\n \"The installed graphql package does not export parse, buildASTSchema and validateSDL; install graphql@^16.\",\n );\n }\n graphql = {\n ...(loaded as typeof GraphQL),\n validateSDL: validation.validateSDL,\n };\n return graphql;\n}\n\nfunction withoutLocations(node: unknown): unknown {\n if (Array.isArray(node)) return node.map(withoutLocations);\n if (node === null || typeof node !== \"object\") return node;\n return Object.fromEntries(\n Object.entries(node)\n .filter(([key, value]) => key !== \"loc\" && value !== undefined)\n .map(([key, value]) => [key, withoutLocations(value)]),\n );\n}\n\nexport const EMPTY_DOCUMENT: LocationFreeGraphQLDocumentNode = {\n kind: \"Document\",\n definitions: [],\n};\n\n/** Parses one stored SDL segment. A missing `graphql` peer throws; bad SDL does not. */\nexport function parseSchema(\n sdl: string,\n):\n | { readonly ok: true; readonly document: LocationFreeGraphQLDocumentNode }\n | { readonly ok: false; readonly message: string } {\n if (sdl.trim() === \"\") return { ok: true, document: EMPTY_DOCUMENT };\n const { parse } = loadGraphQL();\n try {\n return {\n ok: true,\n document: withoutLocations(\n parse(sdl, { noLocation: true }),\n ) as LocationFreeGraphQLDocumentNode,\n };\n } catch (error) {\n return {\n ok: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DocumentModelSpecificationDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode, GraphQLError } from \"graphql\";\nimport { scalarCatalog } from \"../../../../scalars/catalog.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { type GraphQLModule, loadGraphQL } from \"../../graphql/parse-schema.js\";\nimport {\n type CheckDiagnosticCode,\n checkDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Node = {\n readonly kind: string;\n readonly name?: { readonly value: string };\n readonly interfaces?: readonly {\n readonly name: { readonly value: string };\n }[];\n};\n\n/** The top-level node an error node sits in, and where a diagnostic points for it. */\ntype Owner = {\n readonly name: string | undefined;\n readonly implements: readonly string[];\n readonly path: DefinitionPath;\n};\n\ntype ErrorCode = {\n readonly code: CheckDiagnosticCode;\n readonly repair: string;\n};\n\n/** The first graphql-js message pattern that matches picks the code. */\nconst ERROR_CODES: readonly (ErrorCode & { readonly pattern: RegExp })[] = [\n {\n pattern:\n /^(?:Interface field |Object field \\S+ includes required argument |Type \\S+ (?:must only implement|cannot implement|can only implement|must implement) )/,\n code: \"PH-DM-INTERFACE-INVALID\",\n repair:\n \"Give the type every field, argument and ancestor interface its interfaces declare, with compatible types.\",\n },\n {\n pattern: / must be (?:Input|Output) Type but got: /,\n code: \"PH-DM-TYPE-POSITION-INVALID\",\n repair:\n \"Reference input types only from input fields and arguments, and output types only from output fields.\",\n },\n {\n pattern: / within itself through a series of non-null fields: /,\n code: \"PH-DM-INPUT-CYCLE\",\n repair: \"Make one input field on the cycle nullable or a list.\",\n },\n];\n\nconst OTHER_ERROR: ErrorCode = {\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n repair:\n \"Correct the stored schema so graphql-js builds it; codegen and hosts build the same schema.\",\n};\n\n/** A model's schema has no operations, so graphql-js has no Query root to require. */\nconst NO_QUERY_ROOT = \"Query root type must be provided.\";\n\n/**\n * The SDL rules graphql-js applies, minus the directive rules: a stored\n * schema carries directive uses such as `@equals` without declaring them,\n * and codegen and hosts read them as annotations.\n */\nfunction sdlRules(graphql: GraphQLModule) {\n return [\n graphql.LoneSchemaDefinitionRule,\n graphql.UniqueOperationTypesRule,\n graphql.UniqueTypeNamesRule,\n graphql.UniqueEnumValueNamesRule,\n graphql.UniqueFieldDefinitionNamesRule,\n graphql.UniqueArgumentDefinitionNamesRule,\n graphql.UniqueDirectiveNamesRule,\n graphql.KnownTypeNamesRule,\n graphql.PossibleTypeExtensionsRule,\n graphql.UniqueArgumentNamesRule,\n graphql.UniqueInputFieldNamesRule,\n ];\n}\n\nconst NAMED_DEFINITION =\n /^(?:Scalar|Object|Interface|InputObject|Enum|Union)TypeDefinition$/;\n\n/**\n * Hosts keep the first definition of a repeated type name and codegen merges\n * the repeats, so a repeat is not an error here. Catalog and project scalars\n * the document uses without declaring become stub declarations, and a type\n * the document only extends gets an empty base to extend.\n */\nfunction validationDocument(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n): DocumentNode {\n const defined = new Set<string>();\n const definitions: object[] = nodes.filter((node) => {\n if (!NAMED_DEFINITION.test(node.kind) || node.name === undefined) {\n return true;\n }\n if (defined.has(node.name.value)) return false;\n defined.add(node.name.value);\n return true;\n });\n const define = (kind: string, value: string) => {\n if (defined.has(value)) return;\n defined.add(value);\n definitions.push({\n kind,\n name: { kind: \"Name\", value },\n directives: [],\n interfaces: [],\n fields: [],\n values: [],\n types: [],\n });\n };\n for (const name of [\n ...scalarCatalog.map((scalar) => scalar.name),\n ...specification.scalars.map((scalar) => scalar.name),\n ]) {\n define(\"ScalarTypeDefinition\", name);\n }\n for (const node of nodes) {\n if (node.kind.endsWith(\"TypeExtension\") && node.name !== undefined) {\n define(node.kind.replace(/Extension$/, \"Definition\"), node.name.value);\n }\n }\n return { kind: \"Document\", definitions } as unknown as DocumentNode;\n}\n\n/**\n * Maps every object inside each top-level node to that node's owner. A\n * type's first definition points at its structured type; any other node\n * points at its place in the retained document.\n */\nfunction ownersByNode(\n nodes: readonly Node[],\n specification: DocumentModelSpecificationDefinition,\n index: number,\n): ReadonlyMap<object, Owner> {\n const typeIndex = new Map(\n specification.types.map((type, position) => [type.name, position]),\n );\n const firstDefinitions = new Set<string>();\n const owners = new Map<object, Owner>();\n nodes.forEach((node, nodeIndex) => {\n const name = node.name?.value;\n const position = name === undefined ? undefined : typeIndex.get(name);\n const first =\n name !== undefined &&\n NAMED_DEFINITION.test(node.kind) &&\n !firstDefinitions.has(name);\n if (first) firstDefinitions.add(name);\n const owner: Owner = {\n name,\n implements: (node.interfaces ?? []).map((entry) => entry.name.value),\n path:\n first && position !== undefined\n ? [\"specifications\", index, \"types\", position]\n : [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n \"document\",\n \"definitions\",\n nodeIndex,\n ],\n };\n const visit = (value: unknown): void => {\n if (value === null || typeof value !== \"object\") return;\n owners.set(value, owner);\n for (const child of Object.values(value)) visit(child);\n };\n visit(node);\n });\n return owners;\n}\n\n/**\n * The owner of an error's last node, except that an interface error belongs\n * to the type that implements another owner of the error, which graphql-js\n * may list before or after the interface's own nodes.\n */\nfunction ownerOf(\n error: GraphQLError,\n owners: ReadonlyMap<object, Owner>,\n): Owner | undefined {\n const candidates = (error.nodes ?? []).flatMap(\n (node) => owners.get(node) ?? [],\n );\n const names = new Set(candidates.map(({ name }) => name));\n return (\n candidates.findLast((owner) =>\n owner.implements.some((name) => names.has(name)),\n ) ?? candidates.at(-1)\n );\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n const retained = served?.specification.graphQLCompatibility;\n if (served === undefined || retained === undefined || retained === null) {\n return [];\n }\n const { specification, index } = served;\n const graphql = loadGraphQL();\n const nodes = retained.document.definitions as readonly Node[];\n const document = validationDocument(nodes, specification);\n let errors: readonly GraphQLError[] = graphql.validateSDL(\n document,\n undefined,\n sdlRules(graphql),\n );\n if (errors.length === 0) {\n errors = graphql\n .validateSchema(\n graphql.buildASTSchema(document, { assumeValidSDL: true }),\n )\n .filter(({ message }) => message !== NO_QUERY_ROOT);\n }\n const owners = ownersByNode(nodes, specification, index);\n return errors.map((error) => {\n const { code, repair } =\n ERROR_CODES.find(({ pattern }) => pattern.test(error.message)) ??\n OTHER_ERROR;\n return checkDiagnostics.create({\n code,\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: ownerOf(error, owners)?.path ?? [\n \"specifications\",\n index,\n \"graphQLCompatibility\",\n ],\n message: error.message,\n repair,\n });\n });\n}\n\n/**\n * The compiler validates every type it declares. A retained GraphQL document\n * is the schema codegen and hosts build, so graphql-js validates it as they\n * would.\n */\nexport const graphqlSchemaCheck: DefinitionCheck = {\n name: \"graphql-schema\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { documentModelRef } from \"./served-specification.js\";\n\n/**\n * A host registers one module per `documentType@version`. The loader already\n * reports two selected sources that claim one, so a claimant is reported here\n * only when it or the anchor comes from outside the selection.\n */\nexport function logicalCollisionDiagnostics(\n sourceSet: DefinitionSourceSet,\n [anchor, ...claimants]: readonly NormalizedDocumentModelArtifact[],\n): readonly DefinitionDiagnostic[] {\n const selected = new Set(sourceSet.sources.map(({ specifier }) => specifier));\n const isSelected = (artifact: NormalizedDocumentModelArtifact) =>\n selected.has(artifact.source.specifier);\n const key = `${anchor.documentType}@${anchor.version}`;\n return claimants\n .filter((claimant) => !(isSelected(claimant) && isSelected(anchor)))\n .map((claimant) =>\n toolingDiagnostics.create({\n code: \"PH-PKG-LOGICAL-COLLISION\",\n source: claimant.source,\n definition: documentModelRef(claimant),\n path: [],\n message: `Two sources claim ${key}, and a host registers one module per document type and version.`,\n expected: `one source for ${key}`,\n received: `${anchor.source.specifier} and ${claimant.source.specifier}`,\n repair:\n \"Keep one of the two models, or give one of them another document type.\",\n related: [\n {\n source: anchor.source,\n path: [],\n message: `This source also claims ${key}.`,\n },\n ],\n }),\n );\n}\n","import type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport { logicalCollisionDiagnostics } from \"../../report/logical-collisions.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\nexport const logicalCollisionsCheck: DefinitionCheck = {\n name: \"logical-collisions\",\n run: ({ sourceSet, artifacts }) => {\n const groups = new Map<string, NormalizedDocumentModelArtifact[]>();\n for (const artifact of artifacts) {\n const key = `${artifact.documentType}@${artifact.version}`;\n groups.set(key, [...(groups.get(key) ?? []), artifact]);\n }\n return [...groups.values()].flatMap((group) =>\n logicalCollisionDiagnostics(sourceSet, group),\n );\n },\n};\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { canonicalDigest } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport { servedSpecification } from \"../../report/served-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Use = {\n readonly digest: Sha256Digest;\n readonly source: DefinitionSource;\n readonly path: DefinitionPath;\n};\n\n/**\n * A host serves every model of a package and declares each scalar once, so\n * two package scalars that share a name but not a definition collide there.\n * The compiler sees one model at a time and cannot catch this.\n */\nexport const packageScalarNamesCheck: DefinitionCheck = {\n name: \"package-scalar-names\",\n run: ({ artifacts }) => {\n const first = new Map<string, Use>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const artifact of artifacts) {\n const served = servedSpecification(artifact);\n if (served === undefined) continue;\n served.specification.scalars.forEach((scalar, scalarIndex) => {\n if (!(\"definition\" in scalar)) return;\n const use = {\n digest: canonicalDigest(scalar.definition),\n source: artifact.source,\n path: [\"specifications\", served.index, \"scalars\", scalarIndex],\n };\n const known = first.get(scalar.name);\n if (known === undefined) {\n first.set(scalar.name, use);\n return;\n }\n if (known.digest === use.digest) return;\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-PKG-SCALAR-CONFLICT\",\n source: use.source,\n definition: { kind: \"scalar\", key: scalar.name },\n path: use.path,\n message: `Two different package scalars are named ${scalar.name}.`,\n expected: \"one definition per package scalar name\",\n received: scalar.name,\n repair: `Declare ${scalar.name} once with defineScalar in scalars/index.ts and import it everywhere it is used.`,\n related: [\n {\n source: known.source,\n path: known.path,\n message: `The other ${scalar.name} is used here.`,\n },\n ],\n }),\n );\n });\n }\n return diagnostics;\n },\n};\n","import type {\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\n\ntype SegmentOperation = {\n readonly key: string;\n readonly input: InputTypeDefinition | null;\n};\n\ntype StoredSegments = {\n readonly global: readonly NamedGraphQLTypeDefinition[];\n readonly local: readonly NamedGraphQLTypeDefinition[];\n readonly operations: ReadonlyMap<\n string,\n readonly NamedGraphQLTypeDefinition[]\n >;\n};\n\nfunction referencedNames(\n definition: NamedGraphQLTypeDefinition,\n): readonly string[] {\n const names: string[] = [];\n const visit = (reference: TypeReferenceDefinition): void => {\n if (reference.kind === \"list\") {\n visit(reference.item);\n return;\n }\n if (reference.kind === \"named\") names.push(reference.name);\n };\n switch (definition.kind) {\n case \"enum\":\n return names;\n case \"union\":\n return definition.members;\n case \"input\":\n definition.fields.forEach((field) => visit(field.type));\n return names;\n case \"object\":\n case \"interface\":\n names.push(...(definition.implements ?? []));\n for (const field of definition.fields) {\n field.args?.forEach((argument) => visit(argument.type));\n visit(field.type);\n }\n return names;\n }\n}\n\nfunction reachableFrom(\n rootName: string | null,\n index: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): ReadonlySet<string> {\n const reached = new Set<string>();\n if (rootName === null) return reached;\n const queue = [rootName];\n while (queue.length > 0) {\n const name = queue.pop() as string;\n if (reached.has(name)) continue;\n const definition = index.get(name);\n if (definition === undefined) continue;\n reached.add(name);\n queue.push(...referencedNames(definition));\n }\n return reached;\n}\n\nexport function assignStoredSegments(input: {\n readonly types: readonly NamedGraphQLTypeDefinition[];\n readonly globalRoot: string;\n readonly localRoot: string | null;\n readonly operations: readonly SegmentOperation[];\n}): StoredSegments {\n const stateIndex = new Map(\n input.types.map((definition) => [definition.name, definition]),\n );\n const globalReach = reachableFrom(input.globalRoot, stateIndex);\n const localReach = reachableFrom(input.localRoot, stateIndex);\n\n const operationIndex = new Map(stateIndex);\n for (const operation of input.operations) {\n if (operation.input !== null) {\n operationIndex.set(operation.input.name, operation.input);\n }\n }\n\n const claimed = new Set<string>();\n const operations = new Map<string, readonly NamedGraphQLTypeDefinition[]>();\n for (const operation of input.operations) {\n if (operation.input === null) continue;\n claimed.add(operation.input.name);\n const reached = reachableFrom(operation.input.name, operationIndex);\n const supporting = input.types.filter(\n (definition) =>\n definition.kind === \"input\" &&\n reached.has(definition.name) &&\n !claimed.has(definition.name),\n );\n for (const definition of supporting) claimed.add(definition.name);\n operations.set(operation.key, [operation.input, ...supporting]);\n }\n\n const local = input.types.filter(\n (definition) =>\n definition.kind !== \"input\" &&\n localReach.has(definition.name) &&\n !globalReach.has(definition.name),\n );\n const localDeclared = new Set(local.map((definition) => definition.name));\n // An input no operation reaches stays global, because the host re-extracts\n // input definitions from the state schema (create-schema.ts).\n const global = input.types.filter(\n (definition) =>\n !localDeclared.has(definition.name) && !claimed.has(definition.name),\n );\n return { global, local, operations };\n}\n","import type {\n DirectiveUseDefinition,\n EnumValueDefinition,\n FieldDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLFieldDefinitionNode,\n GraphQLInputValueDefinitionNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n InputFieldDefinition,\n JsonValue,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { foldTypeExtensions } from \"../../kernel/graphql-ast.js\";\n\n/** graphql-js's reason for a bare `@deprecated`. */\nconst DEFAULT_DEPRECATION_REASON = \"No longer supported\";\n\nexport type GraphQLDefinitionNode =\n LocationFreeGraphQLDocumentNode[\"definitions\"][number];\n\ntype NamedDefinitionNode = Extract<\n GraphQLDefinitionNode,\n {\n readonly kind:\n | \"ObjectTypeDefinition\"\n | \"InterfaceTypeDefinition\"\n | \"InputObjectTypeDefinition\"\n | \"EnumTypeDefinition\"\n | \"UnionTypeDefinition\";\n }\n>;\n\nconst NAMED_TYPE_NODE =\n /^(?:Object|Interface|InputObject|Enum|Union)Type(?:Definition|Extension)$/;\n\nfunction description(node: GraphQLStringValueNode | undefined): string | null {\n return node === undefined ? null : node.value;\n}\n\nfunction constValue(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 case \"BooleanValue\":\n return node.value;\n case \"NullValue\":\n return null;\n case \"ListValue\":\n return node.values.map(constValue);\n case \"ObjectValue\":\n return Object.fromEntries(\n node.fields.map((field) => [field.name.value, constValue(field.value)]),\n );\n }\n}\n\nfunction typeReference(\n node: GraphQLTypeNode,\n declared: ReadonlySet<string>,\n required = false,\n): TypeReferenceDefinition {\n switch (node.kind) {\n case \"NonNullType\":\n return typeReference(node.type, declared, true);\n case \"ListType\":\n return {\n kind: \"list\",\n required,\n item: typeReference(node.type, declared),\n };\n case \"NamedType\":\n return {\n kind: declared.has(node.name.value) ? \"named\" : \"scalar\",\n name: node.name.value,\n required,\n };\n }\n}\n\nfunction directives(nodes: readonly GraphQLDirectiveNode[]): {\n readonly deprecated: string | null;\n readonly uses?: readonly DirectiveUseDefinition[];\n} {\n const index = nodes.findIndex(\n (node) =>\n node.name.value === \"deprecated\" &&\n node.arguments.every(\n (argument) =>\n argument.name.value === \"reason\" &&\n argument.value.kind === \"StringValue\",\n ),\n );\n const reason = nodes[index]?.arguments[0]?.value as\n | GraphQLStringValueNode\n | undefined;\n const rest = nodes.filter((_, position) => position !== index);\n return {\n deprecated:\n index === -1 ? null : (reason?.value ?? DEFAULT_DEPRECATION_REASON),\n ...(rest.length > 0 && {\n uses: rest.map((node) => ({\n name: node.name.value,\n arguments: node.arguments.map((argument) => ({\n name: argument.name.value,\n value: constValue(argument.value),\n })),\n })),\n }),\n };\n}\n\nfunction inputField(\n node: GraphQLInputValueDefinitionNode,\n declared: ReadonlySet<string>,\n): InputFieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n type: typeReference(node.type, declared),\n ...(node.defaultValue !== undefined && {\n defaultValue: constValue(node.defaultValue),\n }),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction outputField(\n node: GraphQLFieldDefinitionNode,\n declared: ReadonlySet<string>,\n): FieldDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n key: node.name.value,\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(node.arguments.length > 0 && {\n args: node.arguments.map((argument) => inputField(argument, declared)),\n }),\n type: typeReference(node.type, declared),\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction enumValue(\n node: Extract<\n GraphQLDefinitionNode,\n { kind: \"EnumTypeDefinition\" }\n >[\"values\"][number],\n): EnumValueDefinition {\n const { deprecated, uses } = directives(node.directives);\n return {\n name: node.name.value,\n description: description(node.description),\n deprecated,\n ...(uses !== undefined && { directives: uses }),\n };\n}\n\nfunction namedType(\n node: NamedDefinitionNode,\n declared: ReadonlySet<string>,\n): NamedGraphQLTypeDefinition {\n switch (node.kind) {\n case \"ObjectTypeDefinition\":\n case \"InterfaceTypeDefinition\":\n return {\n kind: node.kind === \"ObjectTypeDefinition\" ? \"object\" : \"interface\",\n name: node.name.value,\n description: description(node.description),\n ...(node.interfaces.length > 0 && {\n implements: node.interfaces.map((entry) => entry.name.value),\n }),\n fields: node.fields.map((field) => outputField(field, declared)),\n };\n case \"InputObjectTypeDefinition\":\n return {\n kind: \"input\",\n name: node.name.value,\n description: description(node.description),\n unknownKeys: \"preserve\",\n fields: node.fields.map((field) => inputField(field, declared)),\n };\n case \"EnumTypeDefinition\":\n return {\n kind: \"enum\",\n name: node.name.value,\n description: description(node.description),\n values: node.values.map(enumValue),\n };\n case \"UnionTypeDefinition\":\n return {\n kind: \"union\",\n name: node.name.value,\n description: description(node.description),\n members: node.types.map((member) => member.name.value),\n };\n }\n}\n\n/** Names of the object, interface, input, enum and union types the nodes define or extend. */\nexport function declaredTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): ReadonlySet<string> {\n const declared = new Set<string>();\n for (const node of definitions) {\n if (NAMED_TYPE_NODE.test(node.kind) && \"name\" in node) {\n declared.add(node.name.value);\n }\n }\n return declared;\n}\n\n/**\n * Every object, interface, input, enum and union type the nodes define or\n * extend, with each extension folded into its type: defined types in\n * document order, then types the nodes only extend. A repeated definition or\n * member keeps its first occurrence; graphql-js validation reports the\n * repeat. A reference to a name in `declared` is a named type; any other\n * reference is a scalar.\n */\nexport function structuredTypes(\n definitions: readonly GraphQLDefinitionNode[],\n declared: ReadonlySet<string> = declaredTypeNames(definitions),\n): readonly NamedGraphQLTypeDefinition[] {\n // A folded node is its first definition or extension with the member\n // nodes of every extension appended, under the definition's kind.\n return [...foldTypeExtensions(definitions, []).types.values()].map(\n ({ node }) => namedType(node as unknown as NamedDefinitionNode, declared),\n );\n}\n\nfunction namedTypeName(node: GraphQLTypeNode): string {\n return node.kind === \"NamedType\" ? node.name.value : namedTypeName(node.type);\n}\n\n/**\n * The type name every field and field argument of the nodes refers to,\n * extensions included, in document order and with repeats.\n */\nexport function referencedTypeNames(\n definitions: readonly GraphQLDefinitionNode[],\n): readonly string[] {\n const names: string[] = [];\n for (const node of definitions) {\n if (!(\"fields\" in node)) continue;\n for (const field of node.fields) {\n names.push(namedTypeName(field.type));\n for (const argument of \"arguments\" in field ? field.arguments : []) {\n names.push(namedTypeName(argument.type));\n }\n }\n }\n return names;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n rejectionReceived,\n snapshotArray,\n snapshotRecord,\n} from \"../../kernel/data-properties.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { checkDiagnostics } from \"./diagnostic-codes.js\";\nimport { documentModelRef } from \"../report/served-specification.js\";\n\ntype Scope = \"global\" | \"local\";\n\n/** A stored SDL string, where it sits in the source, and what it describes. */\nexport type StoredSchemaSegment = {\n readonly path: DefinitionPath;\n readonly schema: string;\n readonly of:\n | { readonly scope: Scope }\n | { readonly module: number; readonly operation: number };\n};\n\n/** The stored strings of the specification an artifact serves. */\nexport type ServedStoredSpecification = {\n readonly path: DefinitionPath;\n readonly initialValues: Readonly<Record<Scope, string>>;\n /** In the order the stored model lists them: global, local, then operations. */\n readonly segments: readonly StoredSchemaSegment[];\n};\n\ntype StoredHistory = {\n readonly path: DefinitionPath;\n readonly versions: readonly number[];\n /** Undefined when the stored history has no specification for the served version. */\n readonly served: ServedStoredSpecification | undefined;\n};\n\nexport type StoredModelRead =\n | ({ readonly ok: true } & StoredHistory)\n | { readonly ok: false; readonly diagnostic: DefinitionDiagnostic };\n\ntype Read<T> =\n | { readonly ok: true; readonly value: T }\n | {\n readonly ok: false;\n readonly path: DefinitionPath;\n readonly expected: string;\n readonly received: string;\n };\n\nfunction record(\n value: unknown,\n path: DefinitionPath,\n): Read<{ readonly [key: string]: unknown }> {\n const snapshot = snapshotRecord(value, undefined, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"a plain record\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction array(value: unknown, path: DefinitionPath): Read<readonly unknown[]> {\n const snapshot = snapshotArray(value, path);\n return snapshot.ok\n ? snapshot\n : {\n ok: false,\n path: snapshot.path,\n expected: \"an array\",\n received: rejectionReceived(snapshot),\n };\n}\n\nfunction text(value: unknown, path: DefinitionPath): Read<string> {\n return typeof value === \"string\"\n ? { ok: true, value }\n : {\n ok: false,\n path,\n expected: \"a string\",\n received: describeReceived(value),\n };\n}\n\nfunction readServedStoredSpecification(\n value: unknown,\n path: DefinitionPath,\n): Read<ServedStoredSpecification> {\n const specification = record(value, path);\n if (!specification.ok) return specification;\n const state = record(specification.value.state, [...path, \"state\"]);\n if (!state.ok) return state;\n const initialValues: Partial<Record<Scope, string>> = {};\n const segments: StoredSchemaSegment[] = [];\n for (const scope of [\"global\", \"local\"] as const) {\n const at = [...path, \"state\", scope];\n const stored = record(state.value[scope], at);\n if (!stored.ok) return stored;\n const schema = text(stored.value.schema, [...at, \"schema\"]);\n if (!schema.ok) return schema;\n const initialValue = text(stored.value.initialValue, [\n ...at,\n \"initialValue\",\n ]);\n if (!initialValue.ok) return initialValue;\n initialValues[scope] = initialValue.value;\n segments.push({\n path: [...at, \"schema\"],\n schema: schema.value,\n of: { scope },\n });\n }\n const modules = array(specification.value.modules, [...path, \"modules\"]);\n if (!modules.ok) return modules;\n for (const [moduleIndex, entry] of modules.value.entries()) {\n const at = [...path, \"modules\", moduleIndex];\n const module = record(entry, at);\n if (!module.ok) return module;\n const operations = array(module.value.operations, [...at, \"operations\"]);\n if (!operations.ok) return operations;\n for (const [operationIndex, member] of operations.value.entries()) {\n const operationPath = [...at, \"operations\", operationIndex];\n const operation = record(member, operationPath);\n if (!operation.ok) return operation;\n if (operation.value.schema === null) continue;\n const schema = text(operation.value.schema, [...operationPath, \"schema\"]);\n if (!schema.ok) return schema;\n segments.push({\n path: [...operationPath, \"schema\"],\n schema: schema.value,\n of: { module: moduleIndex, operation: operationIndex },\n });\n }\n }\n return {\n ok: true,\n value: {\n path,\n initialValues: initialValues as Record<Scope, string>,\n segments,\n },\n };\n}\n\nfunction storedHistory(\n artifact: NormalizedDocumentModelArtifact,\n): Read<StoredHistory> {\n const documentModel = record(artifact.documentModel, [\"documentModel\"]);\n const global = documentModel.ok\n ? record(documentModel.value.global, [\"documentModel\", \"global\"])\n : documentModel;\n if (!global.ok) return global;\n const path = [\"documentModel\", \"global\", \"specifications\"];\n const specifications = array(global.value.specifications, path);\n if (!specifications.ok) return specifications;\n const versions: number[] = [];\n let served: unknown;\n let servedIndex = -1;\n for (const [index, entry] of specifications.value.entries()) {\n const specification = record(entry, [...path, index]);\n if (!specification.ok) return specification;\n const { version } = specification.value;\n if (typeof version !== \"number\") {\n return {\n ok: false,\n path: [...path, index, \"version\"],\n expected: \"a version number\",\n received: describeReceived(version),\n };\n }\n versions.push(version);\n if (version === artifact.version && servedIndex === -1) {\n served = entry;\n servedIndex = index;\n }\n }\n if (servedIndex === -1) {\n return { ok: true, value: { path, versions, served: undefined } };\n }\n const specification = readServedStoredSpecification(served, [\n ...path,\n servedIndex,\n ]);\n return specification.ok\n ? { ok: true, value: { path, versions, served: specification.value } }\n : specification;\n}\n\n/**\n * Reads the stored model an artifact serves without trusting its shape: a\n * module assembled by hand can carry anything there. Every check that reads\n * stored strings goes through this, so each reports one malformed member the\n * same way and the report keeps it once.\n */\nexport function readStoredModel(\n artifact: NormalizedDocumentModelArtifact,\n): StoredModelRead {\n const read = storedHistory(artifact);\n if (read.ok) return { ok: true, ...read.value };\n return {\n ok: false,\n diagnostic: checkDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path: read.path,\n message:\n \"The stored document model this source serves is malformed, so hosts and codegen cannot read it.\",\n expected: read.expected,\n received: read.received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; the stored model is not edited by hand.\",\n }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n NamedGraphQLTypeDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { assignStoredSegments } from \"../../../compiler/segments.js\";\nimport {\n canonicalJson,\n compareCodeUnits,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n structuredTypes,\n} from \"../../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../../graphql/parse-schema.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\ntype Segment = {\n readonly path: DefinitionPath;\n readonly stored: string;\n /** What the canonical printer puts in this segment. */\n readonly printed: readonly NamedGraphQLTypeDefinition[];\n};\n\ntype Report = (\n path: DefinitionPath,\n message: string,\n expected: string,\n received: string,\n) => void;\n\n/**\n * SDL cannot spell an input without fields, a field key apart from its name,\n * or a member order that means nothing, so those are not compared.\n */\nfunction comparable(type: NamedGraphQLTypeDefinition): string {\n if (type.kind === \"enum\") return canonicalJson(type);\n if (type.kind === \"union\") {\n return canonicalJson({\n ...type,\n members: [...type.members].sort(compareCodeUnits),\n });\n }\n const fields = type.fields.map((field) => {\n const { key: _key, ...rest } = field;\n return \"args\" in field && field.args !== undefined\n ? {\n ...rest,\n args: field.args.map(({ key: _argKey, ...arg }) => arg),\n }\n : rest;\n });\n const [only] = fields;\n const emptyMarker =\n type.kind === \"input\" &&\n fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return canonicalJson({\n ...type,\n ...(\"implements\" in type &&\n type.implements !== undefined && {\n implements: [...type.implements].sort(compareCodeUnits),\n }),\n fields: emptyMarker ? [] : fields,\n });\n}\n\nfunction differs(\n stored: NamedGraphQLTypeDefinition,\n declared: NamedGraphQLTypeDefinition,\n): boolean {\n return comparable(stored) !== comparable(declared);\n}\n\n/** The canonical printer owns each segment, so every segment holds exactly its printed types. */\nfunction compareCanonical(\n report: Report,\n segment: Segment,\n stored: readonly NamedGraphQLTypeDefinition[],\n): void {\n const expected = segment.printed.map(({ name }) => name);\n const received = stored.map(({ name }) => name);\n const missing = expected.find((name) => !received.includes(name));\n const surplus = received.find((name) => !expected.includes(name));\n if (missing !== undefined || surplus !== undefined) {\n report(\n segment.path,\n missing !== undefined\n ? `The stored schema segment does not declare ${missing}.`\n : `The stored schema segment declares ${surplus}, which the definition places elsewhere or not at all.`,\n expected.join(\", \"),\n received.join(\", \"),\n );\n return;\n }\n for (const declared of segment.printed) {\n const copy = stored.find(({ name }) => name === declared.name);\n if (copy === undefined || !differs(copy, declared)) continue;\n report(\n [...segment.path, declared.name],\n `The stored schema segment describes ${declared.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(copy),\n );\n }\n}\n\ntype ParsedSegment = {\n readonly segment: Segment;\n readonly definitions: readonly GraphQLDefinitionNode[];\n};\n\n/**\n * A schema-first model keeps its own split, and a segment may extend a type\n * another declares, so the union of segments is folded and compared.\n */\nfunction compareExplicit(\n report: Report,\n path: DefinitionPath,\n segments: readonly ParsedSegment[],\n declaration: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n): void {\n const types = structuredTypes(\n segments.flatMap(({ definitions }) => definitions),\n new Set(declaration.keys()),\n );\n const segmentOf = (name: string): DefinitionPath =>\n segments.find(({ definitions }) => declaredTypeNames(definitions).has(name))\n ?.segment.path ?? path;\n const seen = new Set<string>();\n for (const type of types) {\n seen.add(type.name);\n const declared = declaration.get(type.name);\n if (declared === undefined) {\n report(\n segmentOf(type.name),\n `The stored schema segment declares ${type.name}, which the definition does not describe.`,\n [...declaration.keys()].join(\", \"),\n type.name,\n );\n } else if (differs(type, declared)) {\n report(\n [...segmentOf(type.name), type.name],\n `The stored schema segment describes ${type.name} differently than the definition.`,\n canonicalJson(declared),\n canonicalJson(type),\n );\n }\n }\n for (const name of declaration.keys()) {\n if (seen.has(name)) continue;\n report(\n path,\n `No stored schema segment declares ${name}.`,\n name,\n [...seen].join(\", \"),\n );\n }\n}\n\nfunction checkArtifact(\n artifact: NormalizedDocumentModelArtifact,\n): readonly DefinitionDiagnostic[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { specification, index } = served;\n const at: DefinitionPath = [\"specifications\", index];\n const diagnostics: DefinitionDiagnostic[] = [];\n const report: Report = (path, message, expected, received) =>\n diagnostics.push(\n checkDiagnostics.create({\n code: \"PH-DEF-COMPATIBILITY-INVALID\",\n source: artifact.source,\n definition: documentModelRef(artifact),\n path,\n message,\n expected,\n received,\n repair:\n \"Export the module materialize returned, or save the model again from the document model editor; a stored string that describes another structure is a definition error.\",\n }),\n );\n\n const operations = specification.modules.flatMap((module) =>\n module.operations.map((operation) => ({\n key: `${module.key}/${operation.key}`,\n input: operation.input,\n })),\n );\n const printed = assignStoredSegments({\n types: specification.types,\n globalRoot: specification.state.global.root.name,\n localRoot: specification.state.local.root?.name ?? null,\n operations,\n });\n const declaration = new Map<string, NamedGraphQLTypeDefinition>(\n [\n ...specification.types,\n ...operations.flatMap(({ input }) => (input === null ? [] : [input])),\n ].map((type) => [type.name, type]),\n );\n const stored = readStoredModel(artifact);\n if (!stored.ok) diagnostics.push(stored.diagnostic);\n const storedSpecification = stored.ok ? stored.served : undefined;\n const canonical =\n artifact.definition.compatibility.serialization === \"canonical-v1\";\n\n // The materializer writes every operation's segment; a schema-first\n // operation without an input may store none.\n const missing = new Map<string, string>();\n specification.modules.forEach((module, moduleIndex) =>\n module.operations.forEach((operation, operationIndex) => {\n if (canonical || operation.input !== null) {\n missing.set(\n `${moduleIndex}/${operationIndex}`,\n `${module.key}.${operation.key}`,\n );\n }\n }),\n );\n const segments: Segment[] = [];\n for (const { path, schema, of } of storedSpecification?.segments ?? []) {\n if (\"scope\" in of) {\n segments.push({ path, stored: schema, printed: printed[of.scope] });\n continue;\n }\n const module = specification.modules.at(of.module);\n const operation = module?.operations.at(of.operation);\n if (module === undefined || operation === undefined) {\n report(\n path,\n \"The stored schema segment belongs to an operation the definition does not declare.\",\n \"a segment of a declared operation\",\n schema,\n );\n continue;\n }\n missing.delete(`${of.module}/${of.operation}`);\n segments.push({\n path,\n stored: schema,\n printed:\n printed.operations.get(`${module.key}/${operation.key}`) ??\n (operation.input === null ? [] : [operation.input]),\n });\n }\n if (storedSpecification !== undefined) {\n for (const operation of missing.values()) {\n report(\n storedSpecification.path,\n `The stored model has no schema segment for operation ${operation}.`,\n `a schema segment for ${operation}`,\n \"absent\",\n );\n }\n }\n\n const parsed = segments.flatMap((segment): ParsedSegment[] => {\n const result = parseSchema(segment.stored);\n if (result.ok) {\n return [{ segment, definitions: result.document.definitions }];\n }\n report(\n segment.path,\n `The stored schema segment is not GraphQL SDL: ${result.message}`,\n \"GraphQL SDL\",\n segment.stored,\n );\n return [];\n });\n if (canonical) {\n const declared = new Set(declaration.keys());\n for (const { segment, definitions } of parsed) {\n compareCanonical(report, segment, structuredTypes(definitions, declared));\n }\n } else if (\n storedSpecification !== undefined &&\n parsed.length === segments.length\n ) {\n compareExplicit(report, storedSpecification.path, parsed, declaration);\n }\n\n for (const scope of [\"global\", \"local\"] as const) {\n const state = specification.state[scope];\n const text = state.materialized.initialValue;\n if (text.trim() === \"\") continue;\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n value = undefined;\n }\n const received = value === undefined ? text : canonicalJson(value);\n if (received === canonicalJson(state.initialValue)) continue;\n report(\n [...at, \"state\", scope, \"initialValue\"],\n `The stored ${scope} initial value describes a different value than the definition.`,\n canonicalJson(state.initialValue),\n received,\n );\n }\n return diagnostics;\n}\n\n/**\n * Hosts and codegen read the stored SDL strings; the definition carries the\n * structure. Every segment is checked: for a canonical model the strings are\n * the printer's output, so a mismatch is a forged module or a compiler defect.\n */\nexport const retainedSerializationCheck: DefinitionCheck = {\n name: \"retained-serialization\",\n run: ({ artifacts }) => artifacts.flatMap(checkArtifact),\n};\n","import type { DefinitionDiagnostic } from \"@powerhousedao/shared/document-model\";\nimport { canonicalJson } from \"../../../kernel/primitives.js\";\nimport { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { readStoredModel } from \"../stored-specification.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\n/**\n * Hosts read the stored model; consumers of the definition read the\n * structure. A module assembled by hand can make the two disagree.\n */\nexport const storedMaterializationCheck: DefinitionCheck = {\n name: \"stored-materialization\",\n run: ({ artifacts }) =>\n artifacts.flatMap((artifact): DefinitionDiagnostic[] => {\n const stored = readStoredModel(artifact);\n if (!stored.ok) return [stored.diagnostic];\n const storedVersions = canonicalJson(stored.versions);\n const declaredVersions = canonicalJson(\n artifact.definition.specifications.map(({ version }) => version),\n );\n const at = {\n source: artifact.source,\n definition: documentModelRef(artifact),\n };\n if (storedVersions !== declaredVersions) {\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-DECLARATION-INVALID\",\n path: stored.path,\n message:\n \"The stored specification history and the structured definition cover different versions.\",\n expected: declaredVersions,\n received: storedVersions,\n repair:\n \"Export the module materialize returned; do not assemble the stored model or its definition by hand.\",\n }),\n ];\n }\n const served = servedSpecification(artifact);\n if (served === undefined || stored.served === undefined) return [];\n const { path, initialValues } = stored.served;\n return ([\"global\", \"local\"] as const).flatMap((scope) => {\n const expected =\n served.specification.state[scope].materialized.initialValue;\n const received = initialValues[scope];\n if (received === expected) return [];\n return [\n checkDiagnostics.create({\n ...at,\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path: [...path, \"state\", scope, \"initialValue\"],\n message: `The stored ${scope} initial value is not the one the definition materializes.`,\n expected,\n received,\n repair:\n \"Export the module materialize returned; a stored initial value is not an independent setting.\",\n }),\n ];\n });\n }),\n};\n","import { checkDiagnostics } from \"../diagnostic-codes.js\";\nimport type { UnregisteredDefinition } from \"../../report/types.js\";\nimport type { DefinitionCheck } from \"../types.js\";\n\nfunction described({ unit, specifier, reason }: UnregisteredDefinition) {\n const entry = `${unit}index.ts`;\n switch (reason) {\n case \"stored-directory\":\n return {\n message: `${unit} stores a schema-first specification, so discovery reads it as schema-first and leaves out the code-first document model ${specifier} declares.`,\n expected: \"one authoring style per model directory\",\n received: \"a stored specification and a code-first declaration\",\n repair: `Move the code-first model to a directory of its own with an index.ts that exports it, or delete the stored specification in ${unit}.`,\n };\n case \"not-exported\":\n return {\n message: `${unit} declares a code-first document model that an entry module imports but does not export, so the package leaves it out.`,\n expected: `an entry module that exports the model ${specifier} declares`,\n received: \"imported, not exported\",\n repair:\n specifier === entry\n ? `Export the value materialize(...) returned from ${entry}.`\n : `Export from ${entry} the value materialize(...) returned for the model ${specifier} declares.`,\n };\n case \"unreached\":\n return {\n message: `${unit} declares a code-first document model that no model entry module exports, so the package leaves it out.`,\n expected: `${entry} exporting the model ${specifier} declares`,\n received: \"no entry\",\n repair:\n specifier === entry\n ? `Export the value materialize(...) returned from ${entry}.`\n : `Create ${entry} and export from it the value materialize(...) returned for the model ${specifier} declares.`,\n };\n default: {\n const exhaustive: never = reason;\n return exhaustive;\n }\n }\n}\n\n/** Turns each declaration the project scan found unregistered into one diagnostic. */\nexport const unregisteredDefinitionsCheck: DefinitionCheck = {\n name: \"unregistered-definitions\",\n run: ({ unregistered }) => unregisteredDefinitionDiagnostics(unregistered),\n};\n\n/** @experimental Reports declarations that an entry does not publish. */\nexport function unregisteredDefinitionDiagnostics(\n unregistered: readonly UnregisteredDefinition[],\n) {\n return unregistered.map((definition) =>\n checkDiagnostics.create({\n code: \"PH-PKG-DEFINITION-UNREGISTERED\",\n source: { specifier: definition.specifier },\n path: [],\n ...described(definition),\n }),\n );\n}\n","import type {\n DefinitionCheckProfile,\n DefinitionCheckReport,\n DefinitionCheckSkipReason,\n DefinitionDiagnostic,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareDefinitionDiagnostics } from \"../../kernel/diagnostics.js\";\nimport { canonicalJson, compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionSourceSet } from \"../definition-source-types.js\";\n\nexport type DefinitionStatus = DefinitionCheckReport[\"status\"];\n\n/** These phases mean the tool could not read the package, not that a model is wrong. */\nconst FAILURE_PHASES: ReadonlySet<string> = new Set([\n \"configuration\",\n \"import\",\n]);\n\n/** Drops exact repeats and orders the rest independently of input order. */\nexport function sortedUniqueDiagnostics(\n diagnostics: readonly DefinitionDiagnostic[],\n): readonly DefinitionDiagnostic[] {\n const unique = new Map<string, DefinitionDiagnostic>();\n for (const diagnostic of diagnostics) {\n unique.set(canonicalJson(diagnostic), diagnostic);\n }\n return [...unique]\n .sort(\n ([leftKey, left], [rightKey, right]) =>\n compareDefinitionDiagnostics(left, right) ||\n compareCodeUnits(leftKey, rightKey),\n )\n .map(([, diagnostic]) => diagnostic);\n}\n\nexport function definitionStatus(input: {\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly definitions: readonly unknown[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionStatus {\n const errors = input.diagnostics.filter(\n ({ severity }) => severity === \"error\",\n );\n if (errors.some(({ phase }) => FAILURE_PHASES.has(phase))) return \"failed\";\n if (errors.length > 0) return \"invalid\";\n if (\n input.skipReason !== undefined &&\n input.definitions.length === 0 &&\n input.diagnostics.length === 0\n ) {\n return \"skipped\";\n }\n return \"ok\";\n}\n\nexport function compareArtifacts(\n left: NormalizedDocumentModelArtifact,\n right: NormalizedDocumentModelArtifact,\n): number {\n return (\n compareCodeUnits(left.documentType, right.documentType) ||\n left.version - right.version ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n )\n );\n}\n\ntype InventoryEntry = DefinitionCheckReport[\"definitions\"][number];\n\n/** The artifact order, extended to every kind of inventory entry. */\nfunction compareInventoryEntries(\n left: InventoryEntry,\n right: InventoryEntry,\n): number {\n return (\n compareCodeUnits(left.key, right.key) ||\n (left.version ?? 0) - (right.version ?? 0) ||\n compareCodeUnits(left.source.specifier, right.source.specifier) ||\n compareCodeUnits(\n canonicalJson(left.source.exportPath ?? []),\n canonicalJson(right.source.exportPath ?? []),\n ) ||\n compareCodeUnits(left.kind, right.kind)\n );\n}\n\n/** Builds the stored check report. */\nexport function definitionCheckReport(input: {\n readonly profile: DefinitionCheckProfile;\n readonly sourceSet: DefinitionSourceSet;\n readonly skipReason?: DefinitionCheckSkipReason;\n readonly artifacts: readonly NormalizedDocumentModelArtifact[];\n /** Inventory entries besides the artifacts. */\n readonly definitions: readonly InventoryEntry[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}): DefinitionCheckReport {\n const diagnostics = sortedUniqueDiagnostics(input.diagnostics);\n const definitions = [\n ...input.artifacts.map((artifact): InventoryEntry => ({\n kind: \"document-model\",\n key: artifact.documentType,\n version: artifact.version,\n digest: artifact.digest,\n source: artifact.source,\n })),\n ...input.definitions,\n ].sort(compareInventoryEntries);\n const status = definitionStatus({\n ...(input.skipReason !== undefined && { skipReason: input.skipReason }),\n definitions,\n diagnostics,\n });\n const errors = diagnostics.filter(\n ({ severity }) => severity === \"error\",\n ).length;\n const common = {\n kind: \"powerhouse.definition-check\",\n formatVersion: 2,\n profile: input.profile,\n sourceSet: input.sourceSet,\n definitions,\n diagnostics,\n summary: { errors, warnings: diagnostics.length - errors },\n } as const;\n if (status === \"skipped\") {\n // definitionStatus answers skipped only when a skip reason is present.\n return {\n ...common,\n status,\n skipReason: input.skipReason as DefinitionCheckSkipReason,\n };\n }\n return { ...common, status };\n}\n","import type {\n DefinitionCheckProfile,\n DefinitionCheckReport,\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport { duplicateIdentitiesCheck } from \"./checks/duplicate-identities.js\";\nimport { graphqlSchemaCheck } from \"./checks/graphql-schema.js\";\nimport { logicalCollisionsCheck } from \"./checks/logical-collisions.js\";\nimport { packageScalarNamesCheck } from \"./checks/package-scalar-names.js\";\nimport { retainedSerializationCheck } from \"./checks/retained-serialization.js\";\nimport { storedMaterializationCheck } from \"./checks/stored-materialization.js\";\nimport { unregisteredDefinitionsCheck } from \"./checks/unregistered-definitions.js\";\nimport { definitionCheckReport } from \"../report/status.js\";\nimport type {\n DefinitionCheckInput,\n LoadedDefinitionProject,\n} from \"../report/types.js\";\nimport type { DefinitionCheck } from \"./types.js\";\n\n/**\n * @experimental The checks `ph model check` runs on document models. A later\n * layer, such as ph-cli's release profile, adds its own with\n * `[...documentModelChecks, ...theirs]`.\n */\nexport const documentModelChecks: readonly DefinitionCheck[] = Object.freeze([\n storedMaterializationCheck,\n duplicateIdentitiesCheck,\n packageScalarNamesCheck,\n logicalCollisionsCheck,\n graphqlSchemaCheck,\n retainedSerializationCheck,\n unregisteredDefinitionsCheck,\n]);\n\n/** Moves a check's normalized paths to where each source's author edits them. */\nfunction relocated(\n diagnostic: DefinitionDiagnostic,\n relocations: ReadonlyMap<string, DefinitionRelocation>,\n): DefinitionDiagnostic {\n const at = (source: DefinitionSource | undefined, path: DefinitionPath) =>\n (source === undefined ? undefined : relocations.get(source.specifier))?.(\n path,\n ) ?? path;\n return {\n ...diagnostic,\n path: at(diagnostic.source, diagnostic.path),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n path: at(location.source, location.path),\n })),\n }),\n };\n}\n\n/**\n * @experimental Runs every check over a loaded project and builds the stored\n * check report with the project's load diagnostics. `definitions` adds\n * inventory entries a caller checked itself; `profile` (default `edit`) names\n * the check list the caller ran. Experimental while code-first projects are\n * introduced.\n */\nexport async function checkProjectDefinitions<\n TInput extends DefinitionCheckInput = DefinitionCheckInput,\n>(\n project: LoadedDefinitionProject & TInput,\n options: {\n readonly checks?: readonly DefinitionCheck<TInput>[];\n readonly definitions?: DefinitionCheckReport[\"definitions\"];\n readonly profile?: DefinitionCheckProfile;\n } = {},\n): Promise<DefinitionCheckReport> {\n const relocations = project.relocations ?? new Map();\n const diagnostics = [...project.diagnostics];\n for (const check of options.checks ?? documentModelChecks) {\n for (const diagnostic of await check.run(project)) {\n diagnostics.push(relocated(diagnostic, relocations));\n }\n }\n return definitionCheckReport({\n profile: options.profile ?? \"edit\",\n sourceSet: project.sourceSet,\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n artifacts: project.artifacts,\n definitions: options.definitions ?? [],\n diagnostics,\n });\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const releaseDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-REL-HOST-SCALAR-UNBOUND\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A model declares a package scalar the package registers no binding for, so a host serves it without validation\",\n },\n \"PH-REL-HOST-SCALAR-MISMATCH\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A model declares a package scalar whose stored metadata differs from the binding the package registers\",\n },\n \"PH-REL-HOST-SCALAR-UNCOMPARABLE\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A model declares a package scalar whose validator and the registered binding's differ in checks JSON Schema cannot express, so they could not be compared\",\n },\n \"PH-REL-HOST-DEFINITION-INVALID\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A module's definition fails the wire shape, so a host serves the model from its stored SDL\",\n },\n \"PH-REL-HOST-DEFINITION-MISMATCH\": {\n severity: \"error\",\n phase: \"definition\",\n meaning:\n \"A module's definition does not serve that module's document type or version, so a host serves the model from its stored SDL\",\n },\n \"PH-REL-HOST-VALIDATION-INCOMPLETE\": {\n severity: \"error\",\n // Not a defect of the package: the release check could not run, which\n // the report states as failed, not invalid.\n phase: \"import\",\n meaning:\n \"Host validation did not run, so the release check cannot tell whether a host serves the package as declared\",\n },\n },\n toolingDiagnostics,\n);\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n DefinitionRelatedLocation,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../../adapters/types.js\";\nimport type { DefinitionCheck } from \"../../check/types.js\";\nimport {\n documentModelRef,\n servedSpecification,\n} from \"../../report/served-specification.js\";\nimport { releaseDiagnostics } from \"../diagnostic-codes.js\";\nimport type { HostValidationFindingData, ReleaseCheckInput } from \"../types.js\";\n\ntype Site = {\n readonly artifact: NormalizedDocumentModelArtifact;\n readonly path: DefinitionPath;\n};\n\n/**\n * Where an author edits what a finding names. A host finding names a document\n * type, not a version, so it points at every artifact of that type; a scalar\n * finding narrows that to the served specifications that declare the scalar.\n */\nfunction findingSites(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n finding: HostValidationFindingData,\n): readonly Site[] {\n const ofType = artifacts.filter(\n ({ documentType }) => documentType === finding.documentType,\n );\n if (\"scalar\" in finding) {\n const declaring = ofType.flatMap((artifact): Site[] => {\n const served = servedSpecification(artifact);\n const index =\n served?.specification.scalars.findIndex(\n ({ name }) => name === finding.scalar,\n ) ?? -1;\n return served === undefined || index === -1\n ? []\n : [\n {\n artifact,\n path: [\"specifications\", served.index, \"scalars\", index],\n },\n ];\n });\n if (declaring.length > 0) return declaring;\n }\n return ofType.map((artifact) => ({ artifact, path: [] }));\n}\n\n/** The first site carries the diagnostic; the others are related locations. */\nfunction attribution(\n sites: readonly Site[],\n finding: HostValidationFindingData,\n alsoHere: string,\n): {\n readonly source?: DefinitionSource;\n readonly path: DefinitionPath;\n readonly related: readonly DefinitionRelatedLocation[];\n} {\n if (sites.length === 0) return { path: [], related: [] };\n const [first, ...others] = sites;\n return {\n source: first.artifact.source,\n path: first.path,\n related: others.map(({ artifact, path }) => ({\n source: artifact.source,\n path,\n message: alsoHere,\n })),\n };\n}\n\nfunction hostFindingDiagnostic(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n finding: HostValidationFindingData,\n): DefinitionDiagnostic {\n const { documentType } = finding;\n const sites = findingSites(artifacts, finding);\n switch (finding.kind) {\n case \"scalar-unbound\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version also declares ${finding.scalar}.`,\n );\n return releaseDiagnostics.create({\n code: \"PH-REL-HOST-SCALAR-UNBOUND\",\n ...(source !== undefined && { source }),\n definition: { kind: \"scalar\", key: finding.scalar },\n path,\n message: `${documentType} declares package scalar ${finding.scalar}, but the package registers no binding for it, so a host serves ${finding.scalar} values without validating them.`,\n expected: `an export named ${finding.scalar} in the package's scalars entry`,\n received: \"no binding\",\n repair: `Export the defineScalar binding the model uses from scalars/index.ts under the name ${finding.scalar}.`,\n ...(related.length > 0 && { related }),\n });\n }\n case \"scalar-mismatch\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version also declares ${finding.scalar}.`,\n );\n return releaseDiagnostics.create({\n code: \"PH-REL-HOST-SCALAR-MISMATCH\",\n ...(source !== undefined && { source }),\n definition: { kind: \"scalar\", key: finding.scalar },\n path,\n message: `${documentType} declares package scalar ${finding.scalar} differently from the binding package ${finding.packageName} registers, and a host serves the registered binding.`,\n expected: finding.declared,\n received: finding.registered,\n repair: `Use the ${finding.scalar} binding that scalars/index.ts exports in the model, so the model and the package declare one ${finding.scalar}.`,\n ...(related.length > 0 && { related }),\n });\n }\n case \"scalar-uncomparable\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version also declares ${finding.scalar}.`,\n );\n return releaseDiagnostics.create({\n code: \"PH-REL-HOST-SCALAR-UNCOMPARABLE\",\n ...(source !== undefined && { source }),\n definition: { kind: \"scalar\", key: finding.scalar },\n path,\n message: `${documentType} declares package scalar ${finding.scalar} with a validator that differs from the one package ${finding.packageName} registers in checks JSON Schema cannot express (refinements, transforms, custom checks), so the validators could not be compared, and a host serves the registered binding.`,\n expected: finding.declared,\n received: finding.registered,\n repair: `Use the ${finding.scalar} binding that scalars/index.ts exports in the model, so the model and the package declare one ${finding.scalar}.`,\n ...(related.length > 0 && { related }),\n });\n }\n case \"definition-invalid\":\n case \"definition-mismatch\": {\n const { source, path, related } = attribution(\n sites,\n finding,\n `This version of ${documentType} carries the same definition.`,\n );\n const invalid = finding.kind === \"definition-invalid\";\n const repairs = [...new Set(finding.diagnostics.map((d) => d.repair))];\n return releaseDiagnostics.create({\n code: invalid\n ? \"PH-REL-HOST-DEFINITION-INVALID\"\n : \"PH-REL-HOST-DEFINITION-MISMATCH\",\n ...(source !== undefined && { source }),\n definition:\n sites.length === 0\n ? { kind: \"document-model\", key: documentType }\n : documentModelRef(sites[0].artifact),\n path,\n message: invalid\n ? `A host serves ${documentType} from its stored SDL, because the module's definition fails the wire shape.`\n : `A host serves ${documentType} from its stored SDL, because the module's definition declares another document type or version.`,\n repair:\n repairs.length > 0\n ? repairs.join(\" \")\n : \"Materialize the module and its definition from the same declaration, and export the module materialize returned.\",\n related: [\n ...related,\n ...finding.diagnostics.map(({ code, path, message }) => ({\n path,\n message: `${code}: ${message}`,\n })),\n ],\n });\n }\n }\n}\n\n/**\n * Maps the host's verdict on the package's models to diagnostics, so a\n * release check fails on what a host would refuse or serve differently.\n */\nexport const hostValidationCheck: DefinitionCheck<ReleaseCheckInput> = {\n name: \"host-validation\",\n run: ({ artifacts, release: { host } }) => [\n ...(host.completed\n ? []\n : [\n releaseDiagnostics.create({\n code: \"PH-REL-HOST-VALIDATION-INCOMPLETE\",\n path: [],\n message:\n \"Host validation did not run, so this check cannot tell whether a host serves the package's models as declared.\",\n received: host.reason,\n repair:\n \"Fix what stopped host validation, then run the release check again.\",\n }),\n ]),\n ...host.findings.map((finding) =>\n hostFindingDiagnostic(artifacts, finding),\n ),\n ],\n};\n","import type { DefinitionCheck } from \"../check/types.js\";\nimport { hostValidationCheck } from \"./checks/host-validation.js\";\nimport type { ReleaseCheckInput } from \"./types.js\";\n\n/**\n * @experimental The checks the release profile of `ph build --release` and\n * `ph model check --release` adds to `documentModelChecks`. They read the\n * release evidence a caller gathered.\n */\nexport const releaseChecks: readonly DefinitionCheck<ReleaseCheckInput>[] =\n Object.freeze([hostValidationCheck]);\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const inspectDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-INSPECT-SELECTION-UNKNOWN\": {\n severity: \"error\",\n // A mistyped selection is a usage error, not a defect of the package.\n phase: \"configuration\",\n meaning:\n \"The selected document type and version is not served by any model of the package\",\n },\n },\n toolingDiagnostics,\n);\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { servedSpecification } from \"../report/served-specification.js\";\nimport {\n compareArtifacts,\n definitionStatus,\n sortedUniqueDiagnostics,\n} from \"../report/status.js\";\nimport { logicalCollisionDiagnostics } from \"../report/logical-collisions.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport { inspectDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionInspectionReport,\n DefinitionInspectionSelection,\n DocumentModelFamilyInspection,\n DocumentModelInspection,\n} from \"./types.js\";\n\n/** Keeps the capped `expected` text from cutting a key in half. */\nconst MAX_LISTED = 20;\n\nfunction inspection(\n artifact: NormalizedDocumentModelArtifact,\n): DocumentModelInspection | undefined {\n const served = servedSpecification(artifact);\n if (served === undefined) return undefined;\n const { specification } = served;\n return {\n version: artifact.version,\n source: artifact.source,\n scopes: {\n global: specification.state.global.root.name,\n local: specification.state.local.root?.name ?? null,\n },\n modules: specification.modules.map((module) => ({\n key: module.key,\n name: module.name,\n operations: module.operations.map((operation) => ({\n key: operation.key,\n name: operation.name,\n actionType: operation.actionType,\n scope: operation.scope,\n input: operation.input?.name ?? null,\n errors: operation.errors.map(({ key, code }) => ({ key, code })),\n })),\n })),\n scalars: specification.scalars.map(({ name, implementation }) => ({\n name,\n implementation,\n })),\n types: specification.types.map(({ name }) => name),\n };\n}\n\n/** Artifacts that carry one definition, and so one digest, form one family. */\nfunction families(\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): readonly DocumentModelFamilyInspection[] {\n const grouped = new Map<\n Sha256Digest,\n {\n readonly first: NormalizedDocumentModelArtifact;\n readonly versions: DocumentModelInspection[];\n }\n >();\n for (const artifact of artifacts) {\n const version = inspection(artifact);\n if (version === undefined) continue;\n const family = grouped.get(artifact.digest);\n if (family === undefined) {\n grouped.set(artifact.digest, { first: artifact, versions: [version] });\n } else {\n family.versions.push(version);\n }\n }\n return [...grouped.values()].map(({ first, versions }) => ({\n documentType: first.documentType,\n name: first.definition.model.name,\n extension: first.definition.model.extension,\n digest: first.digest,\n compatibility: first.definition.compatibility,\n versions,\n }));\n}\n\nfunction unknownSelection(\n selection: DefinitionInspectionSelection,\n artifacts: readonly NormalizedDocumentModelArtifact[],\n): DefinitionDiagnostic {\n const available = [\n ...new Set(\n artifacts.map(\n ({ documentType, version }) => `${documentType}@${version}`,\n ),\n ),\n ];\n const listed =\n available.length <= MAX_LISTED\n ? available.join(\", \")\n : `${available.slice(0, MAX_LISTED).join(\", \")}, and ${available.length - MAX_LISTED} more`;\n const selected = `${selection.documentType}@${selection.version}`;\n return inspectDiagnostics.create({\n code: \"PH-INSPECT-SELECTION-UNKNOWN\",\n path: [\"selection\"],\n message: `No model of this package serves ${selected}.`,\n expected: available.length === 0 ? \"a package with a model\" : listed,\n received: selected,\n repair:\n available.length === 0\n ? \"Add a document model to the package: a stored <name>/<name>.json, or a code-first <name>/index.ts under the models directory.\"\n : `Inspect one of: ${listed}.`,\n });\n}\n\n/**\n * @experimental Describes the loaded models without running checks. With a\n * selection it answers for that model only, and adds its full definition\n * when exactly one model serves it. Experimental while code-first projects\n * are introduced.\n */\nexport function inspectProjectDefinitions(\n project: LoadedDefinitionProject,\n options: { readonly selection?: DefinitionInspectionSelection } = {},\n): DefinitionInspectionReport {\n const artifacts = [...project.artifacts].sort(compareArtifacts);\n const { selection } = options;\n const selected =\n selection === undefined\n ? artifacts\n : artifacts.filter(\n ({ documentType, version }) =>\n documentType === selection.documentType &&\n version === selection.version,\n );\n const diagnostics = sortedUniqueDiagnostics([\n ...project.diagnostics,\n ...(selection === undefined\n ? []\n : selected.length === 0\n ? [unknownSelection(selection, artifacts)]\n : logicalCollisionDiagnostics(project.sourceSet, selected)),\n ]);\n return {\n kind: \"powerhouse.definition-inspection\",\n formatVersion: 2,\n status: definitionStatus({\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n definitions: artifacts,\n diagnostics,\n }),\n sourceSet: project.sourceSet,\n families: families(selected),\n diagnostics,\n ...(selection !== undefined &&\n selected.length === 1 && { definition: selected[0].definition }),\n };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { DEFINITION_SOURCE_EXTENSION } from \"@powerhousedao/shared/clis/definition-sources\";\nimport { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport { readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { UnregisteredDefinition } from \"../report/types.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { describeThrown } from \"../structured-diagnostics.js\";\n\n/**\n * Finds `defineDocumentModel(Family)` calls under the document models\n * directory that no discovered entry module reaches. Declarations are read from\n * source text, never run, so an unregistered model cannot fail the scan by\n * throwing. What a source reaches is the module graph its import evaluated.\n */\n\ntype Unit = Omit<UnregisteredDefinition, \"reason\"> & {\n /** Real paths. */\n readonly declaring: readonly string[];\n readonly ids: readonly string[];\n};\n\ntype Unreadable = { readonly path: string; readonly error: unknown }[];\n\ntype Entry = {\n readonly name: string;\n /** As spelled under the models directory. */\n readonly path: string;\n readonly real: string;\n readonly isDirectory: boolean;\n};\n\nconst DECLARATION = {\n module: /^document-model(?:\\/|$)/,\n factory: \"defineDocumentModel(?:Family)?\",\n} as const;\n\nconst NAMED_IMPORT = /\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*\"#(\\d+)\"/g;\n\nconst NAMESPACE_IMPORT = /\\bimport\\s*\\*\\s*as\\s+([\\w$]+)\\s*from\\s*\"#(\\d+)\"/g;\n\ntype Lexed = { readonly code: string; readonly strings: readonly string[] };\n\nfunction startsRegExp(code: string): boolean {\n const before = code.slice(-64).trimEnd();\n return (\n before === \"\" ||\n /[(,=:[!&|?{};+\\-*%<>~^}]$/.test(before) ||\n /(?:^|[^\\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(\n before,\n )\n );\n}\n\nfunction lexCodeAndStrings(text: string): Lexed {\n let code = \"\";\n const strings: string[] = [];\n const literal = (contents: string) => {\n code += `\"#${strings.length}\"`;\n strings.push(contents);\n };\n let braces = 0;\n const templates: number[] = [];\n let i = 0;\n const skipQuoted = (end: (index: number) => boolean) => {\n while (i < text.length && !end(i)) i += text[i] === \"\\\\\" ? 2 : 1;\n };\n while (i < text.length) {\n const char = text[i];\n if (char === \"/\" && text[i + 1] === \"/\") {\n i = text.indexOf(\"\\n\", i);\n if (i === -1) i = text.length;\n } else if (char === \"/\" && text[i + 1] === \"*\") {\n const end = text.indexOf(\"*/\", i + 2);\n i = end === -1 ? text.length : end + 2;\n code += \" \";\n } else if (char === \"/\" && startsRegExp(code)) {\n i += 1;\n let inClass = false;\n while (i < text.length && text[i] !== \"\\n\") {\n if (text[i] === \"\\\\\") i += 1;\n else if (text[i] === \"[\") inClass = true;\n else if (text[i] === \"]\") inClass = false;\n else if (text[i] === \"/\" && !inClass) break;\n i += 1;\n }\n i += 1;\n while (/[a-z]/.test(text[i] ?? \"\")) i += 1;\n code += \" \";\n } else if (char === '\"' || char === \"'\") {\n const start = (i += 1);\n skipQuoted((at) => text[at] === char || text[at] === \"\\n\");\n literal(text.slice(start, i));\n i += 1;\n } else if (char === \"`\" || (char === \"}\" && templates.at(-1) === braces)) {\n const whole = char === \"`\";\n if (!whole) templates.pop();\n const start = (i += 1);\n skipQuoted(\n (at) => text[at] === \"`\" || (text[at] === \"$\" && text[at + 1] === \"{\"),\n );\n const closed = text[i] === \"`\";\n literal(whole && closed ? text.slice(start, i) : \"\");\n if (closed) {\n i += 1;\n } else {\n templates.push(braces);\n i += 2;\n }\n } else {\n if (char === \"{\") braces += 1;\n if (char === \"}\") braces -= 1;\n code += char;\n i += 1;\n }\n }\n return { code, strings };\n}\n\n/** `type as e` imports a value named `type`. */\nfunction valueBindings(\n clause: string,\n): { readonly imported: string; readonly local: string }[] {\n return clause\n .split(\",\")\n .map((part) => part.trim())\n .filter((part) => part !== \"\" && !/^type\\s+(?!as\\b)/.test(part))\n .map((part) => {\n const [imported, local = imported] = part.split(/\\s+as\\s+/);\n return { imported, local };\n });\n}\n\nfunction isSourceFile(name: string): boolean {\n return DEFINITION_SOURCE_EXTENSION.test(name) && !/\\.d\\.m?ts$/.test(name);\n}\n\nfunction isTestFile(name: string): boolean {\n return /\\.(?:test|spec)\\.(?:[jt]sx?|m[jt]s)$/.test(name);\n}\n\n/**\n * Sorted, with symlinks followed. An entry whose real path cannot be read, or\n * leaves the package, is not the package's and is skipped; a directory that\n * cannot be listed goes to `unreadable`.\n */\nfunction packageEntries(\n path: string,\n packageRootIdentity: string,\n unreadable: Unreadable,\n): Entry[] {\n let names: string[];\n try {\n names = readdirSync(path);\n } catch (error) {\n unreadable.push({ path, error });\n return [];\n }\n return names\n .filter((name) => name !== \"node_modules\" && !name.startsWith(\".\"))\n .sort(compareCodeUnits)\n .flatMap((name) => {\n const child = join(path, name);\n try {\n const real = realpathSync.native(child);\n if (pathWithin(packageRootIdentity, real) === null) return [];\n const isDirectory = statSync(real).isDirectory();\n return [{ name, path: child, real, isDirectory }];\n } catch {\n return [];\n }\n });\n}\n\n/** `visited` holds real directories, so a symlink cycle ends. */\nfunction sourceFilesUnder(\n directory: Entry,\n packageRootIdentity: string,\n visited: Set<string>,\n unreadable: Unreadable,\n): Entry[] {\n if (visited.has(directory.real)) return [];\n visited.add(directory.real);\n return packageEntries(\n directory.path,\n packageRootIdentity,\n unreadable,\n ).flatMap((entry) => {\n if (entry.isDirectory) {\n return entry.name === \"__tests__\"\n ? []\n : sourceFilesUnder(entry, packageRootIdentity, visited, unreadable);\n }\n return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];\n });\n}\n\n/**\n * The object literal's own `id` when its source spells it as a plain string.\n * A spread can override it and an escape changes its spelling, so either\n * leaves it unknown.\n */\nfunction topLevelId(\n code: string,\n strings: readonly string[],\n open: number,\n): string | undefined {\n let depth = 0;\n let id: string | undefined;\n for (let i = open; i < code.length; i += 1) {\n const char = code[i];\n if (\"{([\".includes(char)) depth += 1;\n else if (\"})]\".includes(char)) {\n depth -= 1;\n if (depth === 0) break;\n } else if (depth === 1 && code.startsWith(\"...\", i)) {\n return undefined;\n } else if (depth === 1 && !/[\\w$]/.test(code[i - 1] ?? \"\")) {\n const rest = code.slice(i, i + 16);\n const quoted = /^\"#(\\d+)\"\\s*:\\s*/.exec(rest);\n const key =\n /^id\\s*:\\s*/.exec(rest) ??\n (quoted !== null && strings[+quoted[1]] === \"id\" ? quoted : null);\n if (key !== null) {\n const value = /^\"#(\\d+)\"/.exec(code.slice(i + key[0].length));\n id = value === null ? undefined : strings[+value[1]];\n }\n }\n }\n return id === undefined || id === \"\" || id.includes(\"\\\\\") ? undefined : id;\n}\n\nfunction declarations(\n code: string,\n strings: readonly string[],\n): { readonly declares: boolean; readonly ids: readonly string[] } {\n const { module, factory } = DECLARATION;\n const isFactory = new RegExp(`^${factory}$`);\n const callees = [\n ...[...code.matchAll(NAMED_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .flatMap(([, clause]) =>\n valueBindings(clause)\n .filter(({ imported }) => isFactory.test(imported))\n .map(({ imported, local }) => ({\n callee: escapeRegExp(local),\n family: imported !== \"defineDocumentModel\",\n })),\n ),\n ...[...code.matchAll(NAMESPACE_IMPORT)]\n .filter(([, , index]) => module.test(strings[Number(index)]))\n .flatMap(([, namespace]) =>\n [false, true].map((family) => ({\n callee: `${escapeRegExp(namespace)}\\\\s*\\\\.\\\\s*defineDocumentModel${family ? \"Family\" : \"\"}`,\n family,\n })),\n ),\n ];\n let declares = false;\n const ids: string[] = [];\n for (const { callee, family } of callees) {\n const calls = new RegExp(\n `(?<![\\\\w$.])${callee}\\\\s*(?:<[^;()]*>\\\\s*)?\\\\((?:\\\\s*\\\\{)?`,\n \"g\",\n );\n for (const call of code.matchAll(calls)) {\n declares = true;\n const id =\n family || !call[0].endsWith(\"{\")\n ? undefined\n : topLevelId(code, strings, call.index + call[0].length - 1);\n if (id !== undefined) ids.push(id);\n }\n }\n return { declares, ids };\n}\n\nfunction escapeRegExp(name: string): string {\n return name.replaceAll(\"$\", \"\\\\$\");\n}\n\nfunction packagePath(root: string, path: string): `./${string}` {\n return `./${relative(root, path).split(sep).join(\"/\")}`;\n}\n\nfunction realPathOrSelf(path: string): string {\n try {\n return realpathSync.native(path);\n } catch {\n return path;\n }\n}\n\n/** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */\nfunction modelUnit(\n packageRoot: string,\n packageRootIdentity: string,\n directory: Entry,\n unreadable: Unreadable,\n): Unit | undefined {\n const declaring: {\n readonly entry: Entry;\n readonly ids: readonly string[];\n }[] = [];\n for (const entry of sourceFilesUnder(\n directory,\n packageRootIdentity,\n new Set(),\n unreadable,\n )) {\n let text: string;\n try {\n text = readFileSync(entry.real, \"utf8\");\n } catch (error) {\n unreadable.push({ path: entry.path, error });\n continue;\n }\n const { code, strings } = lexCodeAndStrings(text);\n const found = declarations(code, strings);\n if (found.declares) declaring.push({ entry, ids: found.ids });\n }\n const index = join(directory.path, \"index.ts\");\n const suggested =\n declaring.find(({ entry }) => entry.path === index) ?? declaring.at(0);\n if (suggested === undefined) return undefined;\n return {\n kind: \"document-model\",\n unit: `${packagePath(packageRoot, directory.path)}/`,\n specifier: packagePath(packageRoot, suggested.entry.path),\n declaring: declaring.map(({ entry }) => entry.real),\n ids: declaring.flatMap(({ ids }) => ids),\n };\n}\n\nfunction unreadableDiagnostic(\n packageRoot: string,\n { path, error }: Unreadable[number],\n): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier: packagePath(packageRoot, path) },\n path: [],\n message:\n \"This path under the document models directory could not be read, so the scan cannot tell whether it declares a code-first model that no model entry exports.\",\n expected: \"a readable file or directory\",\n received: describeThrown(error),\n repair:\n \"Fix the permissions of the path, or move it out of the document models directory.\",\n });\n}\n\n/**\n * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model\n * that no entry module's import reached, or that an entry reached without\n * exporting the model's literal id. An entry that did not import reaches\n * files no one can name, so the scan then reports nothing.\n */\nexport function findUnregisteredDefinitions(request: {\n readonly packageRoot: string;\n /** Absolute, and already checked to stay inside the package root. */\n readonly documentModelsDir: string;\n readonly sources: readonly DefinitionSource[];\n /** Absolute paths of every module the import of `specifier` evaluated, its own included. */\n readonly importedFiles: (specifier: string) => readonly string[];\n readonly loadedDocumentTypes: ReadonlySet<string>;\n /** Units (`./<documentModelsDir>/<name>/`) a stored specification owns. */\n readonly storedUnits?: ReadonlySet<string>;\n}): {\n readonly unregistered: readonly UnregisteredDefinition[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n} {\n const {\n packageRoot,\n documentModelsDir,\n sources,\n importedFiles,\n loadedDocumentTypes,\n storedUnits = new Set<string>(),\n } = request;\n const imported = sources.map(({ specifier }) => importedFiles(specifier));\n if (imported.some((files) => files.length === 0)) {\n return { unregistered: [], diagnostics: [] };\n }\n const reached = new Set(imported.flat().map(realPathOrSelf));\n const packageRootIdentity = realPathOrSelf(packageRoot);\n const unreadable: Unreadable = [];\n const directories = packageEntries(\n documentModelsDir,\n packageRootIdentity,\n [],\n ).filter(({ isDirectory }) => isDirectory);\n const units = directories.flatMap(\n (entry) =>\n modelUnit(packageRoot, packageRootIdentity, entry, unreadable) ?? [],\n );\n const modelDirectories = new Set(directories.map(({ path }) => path));\n const unregistered = units.flatMap(\n ({ kind, unit, specifier, declaring, ids }): UnregisteredDefinition[] => {\n const isReached = declaring.some((file) => reached.has(file));\n if (isReached && ids.every((id) => loadedDocumentTypes.has(id))) {\n return [];\n }\n return [\n {\n kind,\n unit,\n specifier,\n reason: storedUnits.has(unit)\n ? \"stored-directory\"\n : isReached\n ? \"not-exported\"\n : \"unreached\",\n },\n ];\n },\n );\n return {\n unregistered,\n diagnostics: unreadable\n .filter(({ path }) => !modelDirectories.has(path))\n .map((entry) => unreadableDiagnostic(packageRoot, entry)),\n };\n}\n\n/**\n * @experimental The package-relative files under `directory` that declare a\n * code-first document model, read from source text without running them.\n * Codegen refuses to write a stored model over them.\n */\nexport function codeFirstDeclarationFiles(\n packageRoot: string,\n directory: string,\n): readonly `./${string}`[] {\n const packageRootIdentity = realPathOrSelf(packageRoot);\n const real = realPathOrSelf(directory);\n if (pathWithin(packageRootIdentity, real) === null) return [];\n const unit = modelUnit(\n packageRoot,\n packageRootIdentity,\n { name: \"\", path: directory, real, isDirectory: true },\n [],\n );\n return (unit?.declaring ?? []).map((file) =>\n packagePath(packageRootIdentity, file),\n );\n}\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n isScalarDefinition,\n type ScalarDefinition,\n} from \"../../../scalars/types.js\";\nimport { compareCodeUnits } from \"../../kernel/primitives.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\n\n/** Where codegen reads a package's `defineScalar` exports from. */\nconst PROJECT_SCALARS_SPECIFIER = \"./scalars/index.ts\";\n\n/** The scalars `scalars/index.ts` exports, imported like the selected sources. */\nexport async function loadProjectScalars(request: {\n readonly loader: DefinitionSourceLoader;\n readonly packageRoot: string;\n readonly configFile: string;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n}): Promise<{\n readonly definitions: readonly ScalarDefinition[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n}> {\n const { loader, packageRoot, configFile, packageRevision, signal } = request;\n if (!existsSync(join(packageRoot, \"scalars\", \"index.ts\"))) {\n return { definitions: [], diagnostics: [] };\n }\n const imported = await loader.importPackageModule({\n configFile,\n packageRevision,\n ...(signal !== undefined && { signal }),\n specifier: PROJECT_SCALARS_SPECIFIER,\n });\n if (!imported.ok) {\n return { definitions: [], diagnostics: imported.diagnostics };\n }\n // Codegen emits `import { <name> } from \"scalars\"`, so only an export bound\n // under the scalar's own name makes it available.\n const definitions = Object.entries(imported.namespace)\n .flatMap(([exportName, value]) =>\n isScalarDefinition(value) && value.name === exportName ? [value] : [],\n )\n .sort((left, right) => compareCodeUnits(left.name, right.name));\n return { definitions, diagnostics: [] };\n}\n","import type { JsonValue } from \"@powerhousedao/shared/document-model\";\nimport type { AnyTypeDescriptor } from \"../dsl/types.js\";\n\ntype InitialValueResult =\n | {\n readonly ok: true;\n readonly value: JsonValue;\n readonly serialized: string;\n }\n | {\n readonly ok: false;\n readonly reason: \"not-serializable\" | \"rejected\";\n readonly message: string;\n };\n\nexport function serializeAndValidateInitialValue(\n root: AnyTypeDescriptor,\n value: unknown,\n): InitialValueResult {\n let serialized: string | undefined;\n try {\n // The lib signature omits that JSON.stringify returns undefined for\n // undefined, a function, or a symbol.\n serialized = JSON.stringify(value) as string | undefined;\n } catch (error) {\n return {\n ok: false,\n reason: \"not-serializable\",\n message: error instanceof Error ? error.message : String(error),\n };\n }\n if (serialized === undefined) {\n return {\n ok: false,\n reason: \"not-serializable\",\n message: `JSON.stringify returned undefined for a value of type ${typeof value}`,\n };\n }\n const parsed = JSON.parse(serialized) as JsonValue;\n try {\n root.validator.parse(parsed);\n } catch (error) {\n return {\n ok: false,\n reason: \"rejected\",\n message: error instanceof Error ? error.message : String(error),\n };\n }\n return { ok: true, value: parsed, serialized };\n}\n","import type { StoredScalarDefinition } from \"@powerhousedao/shared/document-model\";\nimport type { ScalarDefinition } from \"./types.js\";\n\n/** The metadata a stored definition records for a `defineScalar` binding. */\nexport function storedScalarDefinition(\n definition: ScalarDefinition,\n): StoredScalarDefinition {\n return {\n kind: \"powerhouse.scalar\",\n formatVersion: 1,\n name: definition.name,\n representation: definition.representation ?? \"json\",\n description: definition.description ?? \"\",\n coercion: {\n source: definition.coercion === undefined ? \"derived\" : \"explicit\",\n },\n coercionProfile: \"catalog-v1\",\n };\n}\n","import type {\n DocumentScalarReferenceDefinition,\n InputTypeDefinition,\n NamedGraphQLTypeDefinition,\n PowerhouseScalarName,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelScalars } from \"../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../scalars/types.js\";\nimport { storedScalarDefinition } from \"../../scalars/stored-definition.js\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\n\nexport function scalarReferences(\n catalogScalars: ReadonlySet<string>,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): readonly DocumentScalarReferenceDefinition[] {\n const catalog = documentModelScalars\n .map(({ name }) => name as PowerhouseScalarName)\n .filter((name) => catalogScalars.has(name))\n .map(\n (name) =>\n ({\n name,\n implementation: `powerhouse.catalog#${name}`,\n coercionProfile: \"catalog-v1\",\n }) as DocumentScalarReferenceDefinition,\n );\n const declared = [...packageScalars]\n .sort(([left], [right]) => compareCodeUnits(left, right))\n .map(([name, definition]): DocumentScalarReferenceDefinition => ({\n name,\n implementation: `package#${name}`,\n coercionProfile: \"catalog-v1\",\n definition: storedScalarDefinition(definition),\n }));\n return [...catalog, ...declared];\n}\n\n// The host builds its schema from state SDL and drops scalar declarations from\n// operation SDL, so a scalar only local state or an operation input uses is\n// declared in the global segment too.\nexport function declareProjectScalars(\n segment: string,\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): string {\n return [\n ...[...packageScalars.keys()]\n .sort(compareCodeUnits)\n .map((name) => `scalar ${name}`),\n segment,\n ].join(\"\\n\\n\");\n}\n\nfunction namedTypeOf(type: TypeReferenceDefinition): string {\n return type.kind === \"list\" ? namedTypeOf(type.item) : type.name;\n}\n\nexport function inputReachesProjectScalar(\n input: InputTypeDefinition,\n types: readonly NamedGraphQLTypeDefinition[],\n packageScalars: ReadonlyMap<string, ScalarDefinition>,\n): boolean {\n const visited = new Set<string>();\n const reaches = (candidate: InputTypeDefinition): boolean => {\n if (visited.has(candidate.name)) return false;\n visited.add(candidate.name);\n return candidate.fields.some((field) => {\n const name = namedTypeOf(field.type);\n if (packageScalars.has(name)) return true;\n const target = types.find((type) => type.name === name);\n return target?.kind === \"input\" && reaches(target);\n });\n };\n return reaches(input);\n}\n","export function getGlobalRegistry<T extends object>(\n key: string,\n create: () => T,\n): T {\n const registries = globalThis as { [key: symbol]: T | undefined };\n return (registries[Symbol.for(key)] ??= create());\n}\n","import { getGlobalRegistry } from \"../kernel/global-registry.js\";\nimport type { AnyFieldDescriptor, AnyTypeDescriptor } from \"./types.js\";\n\ntype Registry = {\n readonly fieldDescriptors: WeakSet<object>;\n readonly typeDescriptors: WeakSet<object>;\n readonly scalarFactories: WeakSet<object>;\n readonly referenceResolvers: WeakMap<object, () => AnyTypeDescriptor>;\n};\n\nconst registry = getGlobalRegistry<Registry>(\n \"powerhouse.document-model.descriptors.v1\",\n () => ({\n fieldDescriptors: new WeakSet<object>(),\n typeDescriptors: new WeakSet<object>(),\n scalarFactories: new WeakSet<object>(),\n referenceResolvers: new WeakMap<object, () => AnyTypeDescriptor>(),\n }),\n);\n\nexport function registerFieldDescriptor<T extends AnyFieldDescriptor>(\n descriptor: T,\n): T {\n registry.fieldDescriptors.add(descriptor);\n return descriptor;\n}\n\nexport function registerTypeDescriptor<T extends AnyTypeDescriptor>(\n descriptor: T,\n): T {\n registry.typeDescriptors.add(descriptor);\n return descriptor;\n}\n\nexport function registerScalarFactory<T extends object>(factory: T): T {\n registry.scalarFactories.add(factory);\n return factory;\n}\n\nexport function isFieldDescriptor(value: unknown): value is AnyFieldDescriptor {\n return (\n value !== null &&\n typeof value === \"object\" &&\n registry.fieldDescriptors.has(value)\n );\n}\n\nexport function isTypeDescriptor(value: unknown): value is AnyTypeDescriptor {\n return (\n value !== null &&\n typeof value === \"object\" &&\n registry.typeDescriptors.has(value)\n );\n}\n\nexport function isScalarFactory(value: unknown): boolean {\n return typeof value === \"function\" && registry.scalarFactories.has(value);\n}\n\nexport function registerReference<T extends AnyFieldDescriptor>(\n descriptor: T,\n resolve: () => AnyTypeDescriptor,\n): T {\n registry.referenceResolvers.set(descriptor, resolve);\n return descriptor;\n}\n\nexport function referenceResolver(\n descriptor: object,\n): (() => AnyTypeDescriptor) | undefined {\n return registry.referenceResolvers.get(descriptor);\n}\n","import type {\n DirectiveUseDefinition,\n JsonValue,\n} from \"@powerhousedao/shared/document-model\";\nimport type { z } from \"zod\";\nimport type { ScalarDefinition } from \"../../scalars/types.js\";\n\ntype FieldValidationOptions<TRequired extends boolean = boolean> = {\n readonly required?: TRequired;\n};\n\ntype FieldTextOptions = {\n readonly description?: string;\n readonly deprecated?: string;\n};\n\ntype FieldPresentationOptions = FieldTextOptions & {\n readonly defaultValue?: JsonValue;\n};\n\nexport type FieldOptions<TRequired extends boolean = boolean> =\n FieldValidationOptions<TRequired> & FieldPresentationOptions;\n\ntype EqualsOption = {\n readonly equals?: string;\n};\n\nexport type ScalarFieldOptions<TRequired extends boolean = boolean> =\n FieldOptions<TRequired> & EqualsOption;\n\nexport type JsonLiteral =\n | string\n | number\n | boolean\n | null\n | readonly JsonLiteral[]\n | { readonly [key: string]: JsonLiteral };\n\nexport type FieldBuilderOptions<\n TRequired extends boolean = boolean,\n TDefault extends JsonLiteral | undefined = JsonLiteral | undefined,\n> = FieldValidationOptions<TRequired> &\n FieldTextOptions & {\n readonly defaultValue?:\n | TDefault\n | (TDefault extends undefined ? JsonLiteral : never);\n };\n\nexport type ScalarBuilderOptions<\n TRequired extends boolean = boolean,\n TDefault extends JsonLiteral | undefined = JsonLiteral | undefined,\n> = FieldBuilderOptions<TRequired, TDefault> & EqualsOption;\n\ntype IsLiteral<T> = T extends string\n ? string extends T\n ? false\n : true\n : T extends number\n ? number extends T\n ? false\n : true\n : T extends boolean\n ? boolean extends T\n ? false\n : true\n : T extends null\n ? true\n : T extends readonly unknown[]\n ? number extends T[\"length\"]\n ? false\n : AllLiteral<T[number]>\n : T extends object\n ? string extends keyof T\n ? false\n : Partial<T> extends T\n ? [keyof T] extends [never]\n ? true\n : false\n : AllLiteral<T[keyof T]>\n : false;\n\ntype AllLiteral<T> = [T] extends [never]\n ? true\n : false extends IsLiteral<T>\n ? false\n : true;\n\nexport type DefaultFlag<TDefault> = [TDefault] extends [undefined]\n ? false\n : undefined extends TDefault\n ? boolean\n : IsLiteral<TDefault> extends true\n ? true\n : boolean;\n\nexport type ScalarBuilder<TBase, TInput = TBase> = <\n const TRequired extends boolean = false,\n const TDefault extends JsonLiteral | undefined = undefined,\n>(\n options?: ScalarBuilderOptions<TRequired, TDefault>,\n) => ScalarDescriptor<\n Nullable<TInput, TRequired>,\n Nullable<TBase, TRequired>,\n Nullable<TInput, TRequired>,\n TRequired,\n DefaultFlag<TDefault>\n>;\n\nexport type FieldDefault =\n | { readonly present: false }\n | { readonly present: true; readonly value: JsonValue };\n\nexport type FieldPresentation = {\n readonly description: string | null;\n readonly deprecated: string | null;\n readonly default: FieldDefault;\n readonly directives: readonly DirectiveUseDefinition[];\n};\n\ntype NamedTypeKind = \"enum\" | \"object\" | \"input\" | \"interface\" | \"union\";\ntype FieldUseKind = \"scalar\" | \"list\" | \"ref\";\ntype DescriptorKind = NamedTypeKind | FieldUseKind;\n\ntype ScalarIdentity = {\n readonly kind: \"scalar\";\n readonly name: string;\n readonly required: boolean;\n};\n\ntype ListIdentity = {\n readonly kind: \"list\";\n readonly required: boolean;\n readonly item: GraphQLIdentity;\n};\n\ntype ReferenceIdentity = {\n readonly kind: \"ref\";\n readonly required: boolean;\n};\n\ntype NamedTypeIdentity = {\n readonly kind: NamedTypeKind;\n readonly name: string | null;\n readonly description: string | null;\n};\n\nexport type GraphQLIdentity =\n | ScalarIdentity\n | ListIdentity\n | ReferenceIdentity\n | NamedTypeIdentity;\n\ntype DescriptorNode<TInput, TOutput, TSource = TOutput> = {\n readonly kind: DescriptorKind;\n readonly identity: GraphQLIdentity;\n readonly validator: z.ZodType;\n readonly __types?: {\n readonly input: TInput;\n readonly output: TOutput;\n readonly source: TSource;\n };\n};\n\nexport const FIELD_USE_ROLE = \"field use\" as const;\nexport const NAMED_TYPE_ROLE =\n \"named type; wrap it with ph.ref(Type) to use it as a field\" as const;\n\ntype FieldDescriptor<\n TInput,\n TOutput,\n TSource = TOutput,\n TRequired extends boolean = boolean,\n TDefaulted extends boolean = boolean,\n> = DescriptorNode<TInput, TOutput, TSource> & {\n readonly role: typeof FIELD_USE_ROLE;\n readonly kind: FieldUseKind;\n readonly required: TRequired;\n readonly presentation: FieldPresentation & {\n readonly default: { readonly present: TDefaulted };\n };\n};\n\ntype TypeDescriptor<TInput, TOutput, TSource = TOutput> = DescriptorNode<\n TInput,\n TOutput,\n TSource\n> & {\n readonly role: typeof NAMED_TYPE_ROLE;\n readonly kind: NamedTypeKind;\n readonly name: string | null;\n readonly description: string | null;\n};\n\nexport type AnyFieldDescriptor = FieldDescriptor<any, any, any>;\nexport type AnyTypeDescriptor = TypeDescriptor<any, any, any>;\nexport type AnyDescriptor = AnyFieldDescriptor | AnyTypeDescriptor;\n\nexport type Nullable<T, TRequired extends boolean> = TRequired extends true\n ? T\n : T | null | undefined;\n\nexport type InputOf<T> =\n T extends DescriptorNode<infer TInput, any, any> ? TInput : never;\nexport type OutputOf<T> =\n T extends DescriptorNode<any, infer TOutput, any> ? TOutput : never;\nexport type SourceOf<T> =\n T extends DescriptorNode<any, any, infer TSource> ? TSource : never;\nexport type RequiredOf<T> = T extends { readonly required: infer TRequired }\n ? TRequired\n : never;\nexport type DefaultedOf<T> = T extends {\n readonly presentation: { readonly default: { readonly present: infer P } };\n}\n ? P\n : never;\n\nexport type ObjectFields = Readonly<Record<string, AnyFieldDescriptor>>;\n\ntype RequiredKeys<TFields extends ObjectFields> = {\n [K in keyof TFields]: RequiredOf<TFields[K]> extends true ? K : never;\n}[keyof TFields];\n\n/** A caller may omit a required field that has a default. */\ntype CallerRequiredKeys<TFields extends ObjectFields> = {\n [K in RequiredKeys<TFields>]: DefaultedOf<TFields[K]> extends true\n ? never\n : K;\n}[RequiredKeys<TFields>];\n\n/** @experimental */\nexport type InputObjectOf<TFields extends ObjectFields> = {\n -readonly [K in CallerRequiredKeys<TFields>]: InputOf<TFields[K]>;\n} & {\n -readonly [\n K in Exclude<keyof TFields, CallerRequiredKeys<TFields>>\n ]?: InputOf<TFields[K]>;\n};\n\ntype ResolvedInputObjectOf<TFields extends ObjectFields> = {\n -readonly [K in RequiredKeys<TFields>]: SourceOf<TFields[K]>;\n} & {\n -readonly [K in Exclude<keyof TFields, RequiredKeys<TFields>>]?: SourceOf<\n TFields[K]\n >;\n};\n\n/** @experimental */\nexport type OutputObjectOf<TFields extends ObjectFields> = {\n -readonly [K in keyof TFields]: OutputOf<TFields[K]>;\n};\n\ntype SourceObjectOf<TFields extends ObjectFields> = {\n -readonly [K in keyof TFields]: SourceOf<TFields[K]>;\n};\n\nexport type EnumValueInput =\n | string\n | {\n readonly name: string;\n readonly description?: string;\n readonly deprecated?: string;\n };\n\ntype EnumValueNameOf<TValue extends EnumValueInput> = TValue extends string\n ? TValue\n : TValue extends { readonly name: infer TName extends string }\n ? TName\n : never;\n\nexport type EnumValue = {\n readonly name: string;\n readonly description: string | null;\n readonly deprecated: string | null;\n};\n\n/** @experimental */\nexport type EnumDescriptor<\n TValues extends readonly EnumValueInput[] = readonly EnumValueInput[],\n> = TypeDescriptor<\n EnumValueNameOf<TValues[number]>,\n EnumValueNameOf<TValues[number]>,\n EnumValueNameOf<TValues[number]>\n> & {\n readonly kind: \"enum\";\n readonly name: string;\n readonly values: readonly EnumValue[];\n};\n\n/** @experimental */\nexport type InterfaceDescriptor<\n TFields extends ObjectFields = ObjectFields,\n // `any` breaks what would otherwise be a circular default.\n TImplements extends readonly InterfaceDescriptor<ObjectFields, any>[] =\n readonly InterfaceDescriptor<ObjectFields, any>[],\n> = TypeDescriptor<\n InputObjectOf<TFields>,\n OutputObjectOf<TFields>,\n SourceObjectOf<TFields>\n> & {\n readonly kind: \"interface\";\n readonly name: string;\n readonly fields: TFields;\n readonly implements: TImplements;\n};\n\n/** @experimental */\nexport type ObjectDescriptor<\n TFields extends ObjectFields = ObjectFields,\n TImplements extends readonly InterfaceDescriptor[] =\n readonly InterfaceDescriptor[],\n> = TypeDescriptor<\n InputObjectOf<TFields>,\n OutputObjectOf<TFields>,\n SourceObjectOf<TFields>\n> & {\n readonly kind: \"object\";\n readonly name: string;\n readonly fields: TFields;\n readonly implements: TImplements;\n};\n\n/** @experimental */\nexport type InputDescriptor<TFields extends ObjectFields = ObjectFields> =\n TypeDescriptor<\n InputObjectOf<TFields>,\n InputObjectOf<TFields>,\n ResolvedInputObjectOf<TFields>\n > & {\n readonly kind: \"input\";\n readonly fields: TFields;\n };\n\n/** @experimental */\nexport type UnionDescriptor<\n TMembers extends readonly ObjectDescriptor[] = readonly ObjectDescriptor[],\n> = TypeDescriptor<\n InputOf<TMembers[number]>,\n OutputOf<TMembers[number]>,\n SourceOf<TMembers[number]>\n> & {\n readonly kind: \"union\";\n readonly name: string;\n readonly members: TMembers;\n};\n\ntype RefTarget = AnyTypeDescriptor | (() => AnyTypeDescriptor);\n\n/** @experimental */\nexport type ReferenceDescriptor<\n TInput,\n TOutput,\n TSource = TOutput,\n TRequired extends boolean = boolean,\n TDefaulted extends boolean = boolean,\n> = FieldDescriptor<TInput, TOutput, TSource, TRequired, TDefaulted> & {\n readonly kind: \"ref\";\n readonly target: RefTarget;\n};\n\n/** @experimental */\nexport type ListDescriptor<\n TInput,\n TOutput,\n TSource = TOutput,\n TRequired extends boolean = boolean,\n TDefaulted extends boolean = boolean,\n> = FieldDescriptor<TInput, TOutput, TSource, TRequired, TDefaulted> & {\n readonly kind: \"list\";\n readonly item: AnyFieldDescriptor;\n};\n\n/** @experimental */\nexport type ScalarDescriptor<\n TInput,\n TOutput,\n TSource = TOutput,\n TRequired extends boolean = boolean,\n TDefaulted extends boolean = boolean,\n> = FieldDescriptor<TInput, TOutput, TSource, TRequired, TDefaulted> & {\n readonly kind: \"scalar\";\n readonly scalarName: string;\n readonly baseValidator: z.ZodType;\n readonly definition?: ScalarDefinition;\n};\n","import type { DirectiveUseDefinition } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport { equalsPattern } from \"../kernel/equals-pattern.js\";\nimport { referenceResolver } from \"./descriptor-registry.js\";\nimport {\n compareGeneratedOrder,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../kernel/primitives.js\";\nimport type {\n AnyDescriptor,\n AnyFieldDescriptor,\n AnyTypeDescriptor,\n EnumDescriptor,\n InputDescriptor,\n InterfaceDescriptor,\n ListDescriptor,\n ObjectDescriptor,\n ObjectFields,\n ReferenceDescriptor,\n ScalarDescriptor,\n UnionDescriptor,\n} from \"./types.js\";\n\n/**\n * The generator wraps a nullable field of an object or an input with\n * `.nullish()`, a nullable list item that is itself a list with `.nullish()`,\n * and any other nullable list item with `.nullable()`. So the slot a field use\n * fills decides, and a descriptor's own validator is its field-slot validator.\n */\nfunction itemValidator(item: AnyFieldDescriptor): z.ZodType {\n const base = fieldBase(item);\n if (item.required) return base;\n return item.kind === \"list\" ? base.nullish() : base.nullable();\n}\n\nfunction fieldBase(field: AnyFieldDescriptor): z.ZodType {\n switch (field.kind) {\n case \"scalar\":\n return (field as ScalarDescriptor<any, any, any>).baseValidator;\n case \"list\":\n return z.array(\n itemValidator((field as ListDescriptor<any, any, any>).item),\n );\n case \"ref\": {\n const reference = field as ReferenceDescriptor<any, any, any>;\n return z.lazy(() => resolveReference(reference).validator);\n }\n }\n}\n\n/**\n * The generator maps `@equals(value: v)` to `.regex(/^v$/)` and ignores every\n * other directive.\n */\nfunction applyDirective(\n base: z.ZodType,\n directive: DirectiveUseDefinition,\n): z.ZodType {\n const value = directive.arguments.find(\n (argument) => argument.name === \"value\",\n )?.value;\n if (directive.name !== \"equals\" || typeof value !== \"string\") return base;\n return base.check(z.regex(new RegExp(equalsPattern(value))));\n}\n\nexport function constrainedBase(field: AnyFieldDescriptor): z.ZodType {\n return field.presentation.directives.reduce(applyDirective, fieldBase(field));\n}\n\n/**\n * The generator emits `.default(v)` only on a field that is not a list and\n * whose default is a string, number, boolean, or enum literal. A list, input\n * object, or `null` default leaves the field as required as it was, although\n * the generated types make every defaulted field an optional key.\n */\nfunction withDefault(field: AnyFieldDescriptor, base: z.ZodType): z.ZodType {\n const fallback = field.presentation.default;\n if (!fallback.present || field.kind === \"list\") return base;\n const { value } = fallback;\n return typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ? base.default(value as never)\n : base;\n}\n\n/**\n * Generated schemas list their members in `lexicographicSortSchema` order,\n * after an optional `__typename` literal. Shape order carries no validation meaning, but Zod\n * reports issues in shape order and a failed operation persists that message,\n * so the compiled schemas keep the generated order.\n */\nfunction objectShape(fields: ObjectFields): Record<string, z.ZodType> {\n return Object.fromEntries(\n Object.entries(fields)\n .sort(([left], [right]) => compareGeneratedOrder(left, right))\n .map(([key, field]) => [key, field.validator]),\n );\n}\n\nexport function resolveReference(\n descriptor: ReferenceDescriptor<any, any, any>,\n): AnyTypeDescriptor {\n const resolve = referenceResolver(descriptor);\n if (resolve === undefined) {\n throw new TypeError(\"The reference descriptor was not created by ph.ref.\");\n }\n return resolve();\n}\n\nexport function buildValidator(descriptor: AnyDescriptor): z.ZodType {\n switch (descriptor.kind) {\n case \"scalar\":\n case \"list\":\n case \"ref\": {\n const field = descriptor as AnyFieldDescriptor;\n const base = withDefault(field, constrainedBase(field));\n return field.required ? base : base.nullish();\n }\n case \"enum\": {\n // Generated enums are sorted the same way, and the rejection message\n // lists the options in that order.\n const names = (descriptor as EnumDescriptor).values\n .map((value) => value.name)\n .sort(compareGeneratedOrder);\n return z.enum(names as [string, ...string[]]);\n }\n case \"input\": {\n const shape = objectShape((descriptor as InputDescriptor).fields);\n return z.object(\n Object.keys(shape).length === 0\n ? { [EMPTY_INPUT_FIELD_NAME]: z.boolean().nullish() }\n : shape,\n );\n }\n case \"object\": {\n const object = descriptor as ObjectDescriptor;\n return z.object({\n __typename: z.literal(object.name).optional(),\n ...objectShape(object.fields),\n });\n }\n case \"interface\":\n return z.object(objectShape((descriptor as InterfaceDescriptor).fields));\n case \"union\": {\n const members = [...(descriptor as UnionDescriptor).members]\n .sort((left, right) => compareGeneratedOrder(left.name, right.name))\n .map((member) => member.validator);\n return z.union(members as [z.ZodType, z.ZodType, ...z.ZodType[]]);\n }\n }\n}\n","import { type DslDiagnosticCode, dslDiagnostics } from \"./diagnostic-codes.js\";\nimport type {\n DefinitionPath,\n DirectiveUseDefinition,\n JsonValue,\n} from \"@powerhousedao/shared/document-model\";\nimport type { z } from \"zod\";\nimport type { ScalarDefinition } from \"../../scalars/types.js\";\nimport {\n type DataSnapshotRejection,\n type DataValue,\n rejectionReceived,\n snapshotArray,\n snapshotDataRecord,\n snapshotRecord,\n} from \"../kernel/data-properties.js\";\nimport {\n isFieldDescriptor,\n isScalarFactory,\n isTypeDescriptor,\n registerFieldDescriptor,\n} from \"./descriptor-registry.js\";\nimport { describeReceived } from \"../kernel/diagnostics.js\";\nimport { equalsPatternProblem } from \"../kernel/equals-pattern.js\";\nimport { canonicalJson, isAuthoredSchemaName } from \"../kernel/primitives.js\";\nimport {\n type AnyFieldDescriptor,\n type AnyTypeDescriptor,\n FIELD_USE_ROLE,\n type FieldDefault,\n type FieldPresentation,\n type Nullable,\n type ScalarDescriptor,\n type ScalarBuilderOptions,\n} from \"./types.js\";\nimport { buildValidator } from \"./zod.js\";\n\nconst FIELD_OPTION_KEYS = Object.freeze([\n \"required\",\n \"description\",\n \"deprecated\",\n \"defaultValue\",\n] as const);\n\nconst SCALAR_FIELD_OPTION_KEYS = Object.freeze([\n ...FIELD_OPTION_KEYS,\n \"equals\",\n] as const);\n\nconst LIST_ITEM_METADATA_KEYS = [\"description\", \"deprecated\", \"defaultValue\"];\n\nfunction rejectionPath(rejection: DataSnapshotRejection): DefinitionPath {\n return rejection.path.map((segment) =>\n typeof segment === \"number\" ? segment : String(segment),\n );\n}\n\nconst FOREIGN_ARRAY =\n \"Expected a plain array, not an Array subclass or an array from another realm.\";\n\nfunction optionRejection(\n rejection: DataSnapshotRejection,\n unsupportedKeyCode: DslDiagnosticCode,\n allowedKeys: readonly string[],\n): never {\n if (rejection.reason === \"unknown-key\") {\n return dslDiagnostics.fail({\n code: unsupportedKeyCode,\n path: rejectionPath(rejection),\n message: `Option ${JSON.stringify(rejection.key)} is not supported here.`,\n expected: allowedKeys.join(\", \"),\n received: rejection.key,\n repair: `Remove ${JSON.stringify(rejection.key)}; the supported options are ${allowedKeys.join(\", \")}.`,\n });\n }\n if (\n rejection.reason === \"custom-prototype\" &&\n rejection.expected === \"array\"\n ) {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: rejectionPath(rejection),\n message: FOREIGN_ARRAY,\n received: rejection.received,\n repair: \"Pass an array literal, or copy the array with Array.from(...).\",\n });\n }\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: rejectionPath(rejection),\n message: `The option value could not be snapshotted (${rejection.reason}).`,\n received: rejectionReceived(rejection),\n repair:\n \"Pass a plain object literal with enumerable string-keyed data properties and no accessors, symbols, or class instances.\",\n });\n}\n\nexport function snapshotDataOptions(\n value: unknown,\n allowedKeys: readonly string[],\n path: DefinitionPath,\n unsupportedKeyCode: DslDiagnosticCode = \"PH-DEF-OPTION-INVALID\",\n): { readonly [key: string]: DataValue } {\n const snapshot = snapshotDataRecord(value, allowedKeys, path);\n if (!snapshot.ok)\n return optionRejection(snapshot, unsupportedKeyCode, allowedKeys);\n return snapshot.value;\n}\n\nexport function snapshotDescriptorOptions(\n value: unknown,\n allowedKeys: readonly string[],\n path: DefinitionPath,\n): { readonly [key: string]: unknown } {\n const snapshot = snapshotRecord(value, allowedKeys, path);\n if (!snapshot.ok)\n return optionRejection(snapshot, \"PH-DEF-OPTION-INVALID\", allowedKeys);\n return snapshot.value;\n}\n\nexport function snapshotDescriptorArray(\n value: unknown,\n path: DefinitionPath,\n code: DslDiagnosticCode,\n repair: string,\n): readonly unknown[] {\n const snapshot = snapshotArray(value, path);\n if (snapshot.ok) return snapshot.value;\n if (snapshot.reason === \"not-array\") {\n return dslDiagnostics.fail({\n code,\n path,\n message: \"Expected an array.\",\n received: snapshot.received,\n repair,\n });\n }\n if (snapshot.reason === \"custom-prototype\" && snapshot.expected === \"array\") {\n return dslDiagnostics.fail({\n code,\n path,\n message: FOREIGN_ARRAY,\n received: snapshot.received,\n repair: `${repair} Copy an Array subclass or an array from another realm with Array.from(...).`,\n });\n }\n return optionRejection(snapshot, code, []);\n}\n\nexport function snapshotFieldMap(\n value: unknown,\n path: DefinitionPath,\n): { readonly [key: string]: unknown } {\n const snapshot = snapshotRecord(value, undefined, path);\n if (!snapshot.ok)\n return optionRejection(snapshot, \"PH-DEF-OPTION-INVALID\", []);\n return snapshot.value;\n}\n\nexport function assertAuthoredName(\n value: unknown,\n path: DefinitionPath,\n): string {\n if (!isAuthoredSchemaName(value)) {\n return dslDiagnostics.fail({\n code: \"PH-DEF-NAME-INVALID\",\n path,\n message:\n \"A GraphQL name must match /^[_A-Za-z][_0-9A-Za-z]*$/ and must not start with two underscores.\",\n expected: \"a GraphQL name such as InvoiceLineItem\",\n received: typeof value === \"string\" ? value : describeReceived(value),\n repair:\n \"Use letters, digits, and underscores, start with a letter or one underscore, and avoid the reserved __ prefix.\",\n });\n }\n return value;\n}\n\nexport function assertFieldUse(\n value: unknown,\n path: DefinitionPath,\n): asserts value is AnyFieldDescriptor {\n if (isFieldDescriptor(value)) return;\n if (isScalarFactory(value)) {\n const role = (value as { readonly role: string }).role;\n dslDiagnostics.fail({\n code: \"PH-SCALAR-FACTORY-AS-FIELD\",\n path,\n message: \"A scalar factory was used as a field without being called.\",\n expected: FIELD_USE_ROLE,\n received: role,\n repair: role.slice(role.indexOf(\"call it, as \") + \"call it, as \".length),\n });\n }\n if (isTypeDescriptor(value)) {\n dslDiagnostics.fail({\n code: \"PH-DEF-TYPE-AS-FIELD\",\n path,\n message: `Named type ${JSON.stringify(value.name)} was used directly as a field.`,\n expected: FIELD_USE_ROLE,\n received: value.role,\n repair: `Wrap the type with ph.ref(${value.name ?? \"Type\"}).`,\n });\n }\n dslDiagnostics.fail({\n code: \"PH-DEF-FIELD-INVALID\",\n path,\n message: \"A field position must hold a field use created by ph.\",\n received: describeReceived(value),\n repair:\n \"Use a called scalar factory such as ph.String(), ph.list(...), or ph.ref(Type).\",\n });\n}\n\nexport function assertNamedType(\n value: unknown,\n path: DefinitionPath,\n code: DslDiagnosticCode,\n repair: string,\n): asserts value is AnyTypeDescriptor {\n if (isTypeDescriptor(value)) return;\n const received = isFieldDescriptor(value)\n ? `field use (${value.kind})`\n : isScalarFactory(value)\n ? \"scalar factory\"\n : describeReceived(value);\n dslDiagnostics.fail({\n code,\n path,\n message:\n \"Expected a named type created by ph.enum, ph.object, ph.input, ph.interface, or ph.union.\",\n expected: \"a named type descriptor\",\n received,\n repair,\n });\n}\n\nexport function stringOption(\n options: { readonly [key: string]: unknown },\n key: string,\n path: DefinitionPath,\n): string | null {\n const value = options[key];\n if (value === undefined) return null;\n if (typeof value !== \"string\") {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, key],\n message: `Option ${key} must be a string.`,\n expected: \"string\",\n received: describeReceived(value),\n repair: `Pass a string ${key} or omit it.`,\n });\n }\n return value;\n}\n\nfunction defaultOption(\n options: { readonly [key: string]: DataValue },\n path: DefinitionPath,\n): FieldDefault {\n if (!Object.hasOwn(options, \"defaultValue\")) return { present: false };\n const value = options.defaultValue;\n if (value === undefined) {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"defaultValue\"],\n message: \"defaultValue is present but undefined.\",\n expected: \"a JSON value, or no defaultValue property at all\",\n received: \"undefined\",\n repair:\n \"Delete the defaultValue property to omit the default, or give it a JSON value such as null.\",\n });\n }\n try {\n canonicalJson(value);\n } catch (error) {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"defaultValue\"],\n message: `defaultValue is not JSON: ${error instanceof Error ? error.message : String(error)}`,\n repair: \"Use a JSON value for defaultValue.\",\n });\n }\n return { present: true, value: value as JsonValue };\n}\n\ntype ResolvedFieldOptions<TRequired extends boolean> = {\n readonly required: TRequired;\n readonly presentation: FieldPresentation;\n};\n\nconst NO_DIRECTIVES: readonly DirectiveUseDefinition[] = Object.freeze([]);\n\nfunction equalsDirectives(\n options: { readonly [key: string]: DataValue },\n path: DefinitionPath,\n): readonly DirectiveUseDefinition[] {\n const value = stringOption(options, \"equals\", path);\n if (value === null) return NO_DIRECTIVES;\n const problem = equalsPatternProblem(value);\n if (problem !== undefined) {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"equals\"],\n received: value,\n ...problem,\n });\n }\n return Object.freeze([\n Object.freeze({\n name: \"equals\",\n arguments: Object.freeze([Object.freeze({ name: \"value\", value })]),\n }),\n ]);\n}\n\nexport function resolveFieldOptions<TRequired extends boolean>(\n options: ScalarBuilderOptions<TRequired> | undefined,\n path: DefinitionPath,\n allowedKeys: readonly string[] = FIELD_OPTION_KEYS,\n): ResolvedFieldOptions<TRequired> {\n const config =\n options === undefined\n ? {}\n : snapshotDataOptions(\n options,\n allowedKeys,\n path,\n \"PH-DEF-FIELD-OPTION-UNSUPPORTED\",\n );\n const required = config.required === undefined ? false : config.required;\n if (typeof required !== \"boolean\") {\n return dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"required\"],\n message: \"Option required must be a boolean.\",\n expected: \"boolean\",\n received: describeReceived(required),\n repair: \"Use required: true, required: false, or omit the option.\",\n });\n }\n return {\n required: required as TRequired,\n presentation: Object.freeze({\n description: stringOption(config, \"description\", path),\n deprecated: stringOption(config, \"deprecated\", path),\n default: Object.freeze(defaultOption(config, path)),\n directives: equalsDirectives(config, path),\n }),\n };\n}\n\nexport function assertBareListItem(\n item: AnyFieldDescriptor,\n path: DefinitionPath,\n): void {\n const authored = LIST_ITEM_METADATA_KEYS.filter((key) =>\n key === \"defaultValue\"\n ? item.presentation.default.present\n : item.presentation[key as \"description\" | \"deprecated\"] !== null,\n );\n if (authored.length > 0) {\n dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"options\", authored[0]],\n message: `A list item carries ${authored.join(\", \")}, but GraphQL has no field or argument definition for a list item.`,\n received: authored.join(\", \"),\n repair: `Move ${authored.join(\", \")} to the ph.list(...) options of the outer field use.`,\n });\n }\n if (item.presentation.directives.length > 0) {\n dslDiagnostics.fail({\n code: \"PH-DEF-OPTION-INVALID\",\n path: [...path, \"options\", \"equals\"],\n message:\n \"A list item carries equals, but GraphQL has no field or argument definition for a list item to carry @equals on.\",\n received: \"equals\",\n repair:\n \"Remove equals from the list item; a list cannot constrain its items with @equals.\",\n });\n }\n}\n\nexport function createScalarField<\n TBase,\n TRequired extends boolean,\n TDefaulted extends boolean,\n TInput = TBase,\n>(\n scalarName: string,\n baseValidator: z.ZodType,\n options: ScalarBuilderOptions<TRequired> | undefined,\n definition?: ScalarDefinition,\n): ScalarDescriptor<\n Nullable<TInput, TRequired>,\n Nullable<TBase, TRequired>,\n Nullable<TInput, TRequired>,\n TRequired,\n TDefaulted\n> {\n const { required, presentation } = resolveFieldOptions(\n options,\n [\"options\"],\n SCALAR_FIELD_OPTION_KEYS,\n );\n // The generator appends `.regex(...)` to the scalar's own Zod schema, which\n // only a string schema has; on any other it emits code that throws.\n const carriesPattern =\n typeof (baseValidator as { readonly regex?: unknown }).regex === \"function\";\n if (presentation.directives.length > 0 && !carriesPattern) {\n dslDiagnostics.fail({\n code: \"PH-DEF-FIELD-OPTION-UNSUPPORTED\",\n path: [\"options\", \"equals\"],\n message: `Option equals adds a pattern check, and the validator of ${scalarName} is not a Zod string schema that can carry one.`,\n received: scalarName,\n repair:\n \"Remove equals, or use it on a scalar whose validator is a Zod string schema, such as ph.String() or ph.PHID().\",\n });\n }\n const descriptor = {\n kind: \"scalar\" as const,\n role: FIELD_USE_ROLE,\n identity: Object.freeze({\n kind: \"scalar\" as const,\n name: scalarName,\n required,\n }),\n scalarName,\n baseValidator,\n ...(definition !== undefined && { definition }),\n required,\n presentation,\n validator: undefined as unknown as z.ZodType,\n };\n descriptor.validator = buildValidator(descriptor);\n return registerFieldDescriptor(\n Object.freeze(descriptor) as unknown as ScalarDescriptor<\n Nullable<TInput, TRequired>,\n Nullable<TBase, TRequired>,\n Nullable<TInput, TRequired>,\n TRequired,\n TDefaulted\n >,\n );\n}\n","import { dslDiagnostics } from \"./diagnostic-codes.js\";\nimport type { PowerhouseScalarName } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\nimport {\n type CatalogScalarDefinition,\n documentModelScalars,\n scalarCatalog,\n} from \"../../scalars/catalog.js\";\nimport {\n isScalarDefinition,\n SCALAR_DEFINITION_VERSION,\n type ScalarDefinition,\n scalarDefinitionVersion,\n type ScalarValue,\n} from \"../../scalars/types.js\";\nimport { describeReceived } from \"../kernel/diagnostics.js\";\nimport { registerScalarFactory } from \"./descriptor-registry.js\";\nimport { createScalarField } from \"./field-options.js\";\nimport type {\n DefaultFlag,\n JsonLiteral,\n Nullable,\n ScalarBuilder,\n ScalarBuilderOptions,\n ScalarDescriptor,\n} from \"./types.js\";\n\nconst BUILDER_NAMES = {\n Amount_Money: \"Money\",\n Amount_Percentage: \"Percentage\",\n Amount_Tokens: \"Tokens\",\n Amount_Fiat: \"AmountFiat\",\n Amount_Crypto: \"AmountCrypto\",\n Amount_Currency: \"AmountCurrency\",\n} as const satisfies Partial<Record<PowerhouseScalarName, string>>;\n\ntype BuilderName<TName extends string> =\n TName extends keyof typeof BUILDER_NAMES\n ? (typeof BUILDER_NAMES)[TName]\n : TName;\n\nfunction builderName(name: string): string {\n return Object.hasOwn(BUILDER_NAMES, name)\n ? BUILDER_NAMES[name as keyof typeof BUILDER_NAMES]\n : name;\n}\n\ntype ScalarFactory<TValue, TCall extends string> = ScalarBuilder<TValue> & {\n readonly role: `field-use factory; call it, as ${TCall}({ required: true })`;\n readonly kind: \"scalar-factory\";\n};\n\nfunction scalarFactory<TValue, TCall extends string>(\n call: TCall,\n name: string,\n validator: z.ZodType,\n definition?: ScalarDefinition,\n): ScalarFactory<TValue, TCall> {\n const factory = (options?: ScalarBuilderOptions) =>\n createScalarField(name, validator, options, definition);\n return registerScalarFactory(\n Object.freeze(\n Object.assign(factory, {\n role: `field-use factory; call it, as ${call}({ required: true })` as const,\n kind: \"scalar-factory\" as const,\n }),\n ),\n ) as unknown as ScalarFactory<TValue, TCall>;\n}\n\nexport const builtInScalarFactories = {\n ID: scalarFactory<string, \"ph.ID\">(\"ph.ID\", \"ID\", z.string()),\n String: scalarFactory<string, \"ph.String\">(\"ph.String\", \"String\", z.string()),\n Boolean: scalarFactory<boolean, \"ph.Boolean\">(\n \"ph.Boolean\",\n \"Boolean\",\n z.boolean(),\n ),\n Int: scalarFactory<number, \"ph.Int\">(\"ph.Int\", \"Int\", z.number()),\n Float: scalarFactory<number, \"ph.Float\">(\"ph.Float\", \"Float\", z.number()),\n};\n\ntype CatalogScalarFactories = {\n readonly [\n S in CatalogScalarDefinition as S[\"name\"] extends PowerhouseScalarName\n ? BuilderName<S[\"name\"]>\n : never\n ]: ScalarFactory<ScalarValue<S>, `ph.${BuilderName<S[\"name\"]>}`>;\n};\n\nexport const catalogScalarFactories = Object.fromEntries(\n documentModelScalars.map((definition) => {\n const builder = builderName(definition.name);\n return [\n builder,\n scalarFactory(\n `ph.${builder}`,\n definition.name,\n definition.schema,\n definition,\n ),\n ];\n }),\n) as CatalogScalarFactories;\n\nconst modelScalarNames = new Set(\n documentModelScalars.map((definition) => definition.name),\n);\nconst hostOnlyScalars: ReadonlySet<string> = new Set(\n scalarCatalog\n .map((definition) => definition.name)\n .filter((name) => !modelScalarNames.has(name)),\n);\n\nexport function scalarField<\n TName extends string,\n TValue,\n const TRequired extends boolean = false,\n const TDefault extends JsonLiteral | undefined = undefined,\n>(\n definition: ScalarDefinition<TName, TValue>,\n options?: ScalarBuilderOptions<TRequired, TDefault>,\n): ScalarDescriptor<\n Nullable<TValue, TRequired>,\n Nullable<TValue, TRequired>,\n Nullable<TValue, TRequired>,\n TRequired,\n DefaultFlag<TDefault>\n> {\n if (!isScalarDefinition(definition)) refuseScalarDefinition(definition);\n if (hostOnlyScalars.has(definition.name))\n refuseHostOnlyScalar(definition.name);\n return createScalarField(\n definition.name,\n definition.schema,\n options,\n definition,\n );\n}\n\nfunction refuseHostOnlyScalar(name: string): never {\n return dslDiagnostics.fail({\n code: \"PH-SCALAR-INTERNAL\",\n definition: { kind: \"scalar\", key: name },\n path: [\"definition\"],\n message: `${name} is internal to the reactor host. A document model cannot use it.`,\n received: name,\n repair:\n \"Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one.\",\n });\n}\n\nexport function refuseScalarFactory(name: string): never {\n if (hostOnlyScalars.has(name)) refuseHostOnlyScalar(name);\n return dslDiagnostics.fail({\n code: \"PH-SCALAR-UNKNOWN\",\n path: [name],\n message: `ph.${name} names no catalog scalar.`,\n expected: `a scalar factory: ${[...Object.keys(builtInScalarFactories), ...Object.keys(catalogScalarFactories).sort()].join(\", \")}`,\n received: `ph.${name}`,\n repair:\n \"Correct the factory name, or declare a project scalar with defineScalar and use it as ph.scalar(definition).\",\n });\n}\n\nconst EXPECTED_DEFINITION =\n \"a ScalarDefinition from defineScalar in document-model/scalars\";\n\nfunction refuseScalarDefinition(value: unknown): never {\n const version = scalarDefinitionVersion(value);\n if (version === undefined) {\n return dslDiagnostics.fail({\n code: \"PH-SCALAR-DEFINITION-INVALID\",\n path: [\"definition\"],\n message: \"ph.scalar takes a scalar definition returned by defineScalar.\",\n expected: EXPECTED_DEFINITION,\n received: describeReceived(value),\n repair:\n \"Pass the value defineScalar returned, or use a ph.<Scalar>() factory for a catalog scalar.\",\n });\n }\n const received =\n typeof version === \"number\" ? String(version) : describeReceived(version);\n return dslDiagnostics.fail({\n code: \"PH-SCALAR-DEFINITION-INVALID\",\n path: [\"definition\"],\n message: `The scalar definition has format version ${received}; this release reads version ${SCALAR_DEFINITION_VERSION}.`,\n expected: EXPECTED_DEFINITION,\n received,\n repair:\n \"Install the same document-model release in the package that defines the scalar and the package that uses it.\",\n });\n}\n","import { dslDiagnostics } from \"./diagnostic-codes.js\";\nimport type { z } from \"zod\";\nimport {\n isTypeDescriptor,\n registerFieldDescriptor,\n registerReference,\n registerTypeDescriptor,\n} from \"./descriptor-registry.js\";\nimport {\n assertAuthoredName,\n assertBareListItem,\n assertFieldUse,\n assertNamedType,\n resolveFieldOptions,\n snapshotDataOptions,\n snapshotDescriptorArray,\n snapshotDescriptorOptions,\n snapshotFieldMap,\n stringOption,\n} from \"./field-options.js\";\nimport { isEnumValueName } from \"../kernel/primitives.js\";\nimport {\n type AnyFieldDescriptor,\n type AnyTypeDescriptor,\n type EnumDescriptor,\n type EnumValue,\n type EnumValueInput,\n FIELD_USE_ROLE,\n type InputDescriptor,\n type InputOf,\n type InterfaceDescriptor,\n type ListDescriptor,\n NAMED_TYPE_ROLE,\n type Nullable,\n type ObjectDescriptor,\n type ObjectFields,\n type OutputOf,\n type ReferenceDescriptor,\n type SourceOf,\n type UnionDescriptor,\n type DefaultFlag,\n type FieldBuilderOptions,\n type JsonLiteral,\n} from \"./types.js\";\nimport {\n builtInScalarFactories,\n catalogScalarFactories,\n refuseScalarFactory,\n scalarField,\n} from \"./scalar-fields.js\";\nimport { buildValidator } from \"./zod.js\";\n\ntype NamedOptions = { readonly description?: string };\ntype EnumOptions<TValues extends readonly EnumValueInput[]> = NamedOptions & {\n readonly values: TValues;\n};\ntype FieldsOptions<TFields extends ObjectFields> = NamedOptions & {\n readonly fields: TFields;\n};\ntype ImplementsOptions<TImplements extends readonly InterfaceDescriptor[]> = {\n readonly implements?: TImplements;\n};\ntype ImplementingOptions<\n TFields extends ObjectFields,\n TImplements extends readonly InterfaceDescriptor[],\n> = FieldsOptions<TFields> & ImplementsOptions<TImplements>;\ntype UnionOptions<TMembers extends readonly ObjectDescriptor[]> =\n NamedOptions & {\n readonly members: TMembers;\n };\n\nconst KIND_NOUNS: Readonly<Record<AnyTypeDescriptor[\"kind\"], string>> = {\n enum: \"an enum\",\n object: \"an object\",\n input: \"an input\",\n interface: \"an interface\",\n union: \"a union\",\n};\n\nfunction fieldMap(value: unknown, path: readonly string[]): ObjectFields {\n const members = snapshotFieldMap(value, path);\n for (const [key, member] of Object.entries(members)) {\n assertAuthoredName(key, [...path, key]);\n assertFieldUse(member, [...path, key]);\n }\n return Object.freeze({ ...members }) as ObjectFields;\n}\n\nfunction enumValues(input: unknown): readonly EnumValue[] {\n const entries = snapshotDescriptorArray(\n input,\n [\"options\", \"values\"],\n \"PH-DEF-ENUM-VALUES-INVALID\",\n \"Pass values as a nonempty array of strings or { name, description?, deprecated? } entries.\",\n );\n if (entries.length === 0) {\n dslDiagnostics.fail({\n code: \"PH-DEF-ENUM-VALUES-INVALID\",\n path: [\"options\", \"values\"],\n message: \"An enum must declare at least one value.\",\n repair: \"Add at least one enum value.\",\n });\n }\n const seen = new Set<string>();\n return Object.freeze(\n entries.map((entry, index): EnumValue => {\n const path = [\"options\", \"values\", index];\n const normalized =\n typeof entry === \"string\"\n ? { name: entry }\n : snapshotDataOptions(\n entry,\n [\"name\", \"description\", \"deprecated\"],\n path,\n );\n const name = assertAuthoredName(normalized.name, [...path, \"name\"]);\n if (!isEnumValueName(name)) {\n dslDiagnostics.fail({\n code: \"PH-DEF-ENUM-VALUES-INVALID\",\n path: [...path, \"name\"],\n message: `${JSON.stringify(name)} is a reserved GraphQL literal and cannot be an enum value.`,\n received: name,\n repair: `Rename the value; true, false, and null are GraphQL literals.`,\n });\n }\n if (seen.has(name)) {\n dslDiagnostics.fail({\n code: \"PH-DEF-ENUM-VALUES-INVALID\",\n path: [...path, \"name\"],\n message: `Enum value ${JSON.stringify(name)} is declared twice.`,\n received: name,\n repair: \"Keep one declaration per enum value.\",\n });\n }\n seen.add(name);\n return Object.freeze({\n name,\n description: stringOption(normalized, \"description\", path),\n deprecated: stringOption(normalized, \"deprecated\", path),\n });\n }),\n );\n}\n\nfunction namedType<T extends AnyTypeDescriptor>(\n node: Omit<T, \"validator\" | \"role\" | \"identity\">,\n): T {\n const descriptor = {\n ...node,\n role: NAMED_TYPE_ROLE,\n identity: Object.freeze({\n kind: node.kind,\n name: node.name,\n description: node.description,\n }),\n validator: undefined as unknown as z.ZodType,\n } as unknown as T & { validator: z.ZodType };\n descriptor.validator = buildValidator(descriptor);\n return registerTypeDescriptor(Object.freeze(descriptor));\n}\n\nfunction refTarget(\n candidate: unknown,\n path: readonly string[],\n): AnyTypeDescriptor {\n assertNamedType(\n candidate,\n path,\n \"PH-DEF-REFERENCE-TARGET-INVALID\",\n \"Pass a named type returned by ph.enum, ph.object, ph.input, ph.interface, or ph.union, or a thunk returning one.\",\n );\n if (candidate.name === null) {\n dslDiagnostics.fail({\n code: \"PH-DEF-REFERENCE-TARGET-INVALID\",\n path,\n message: \"An anonymous input cannot be a reference target.\",\n repair: 'Give the input a name: ph.input(\"NameInput\", { fields }).',\n });\n }\n return candidate;\n}\n\nfunction implementedInterfaces(config: {\n readonly [key: string]: unknown;\n}): readonly InterfaceDescriptor[] {\n const implemented =\n config.implements !== undefined\n ? snapshotDescriptorArray(\n config.implements,\n [\"options\", \"implements\"],\n \"PH-DEF-IMPLEMENTS-INVALID\",\n \"Pass implements as an array of descriptors returned by ph.interface.\",\n )\n : [];\n const seen = new Set<string>();\n implemented.forEach((candidate, index) => {\n const path = [\"options\", \"implements\", index];\n assertNamedType(\n candidate,\n path,\n \"PH-DEF-IMPLEMENTS-INVALID\",\n \"Pass a descriptor returned by ph.interface.\",\n );\n if (candidate.kind !== \"interface\") {\n dslDiagnostics.fail({\n code: \"PH-DEF-IMPLEMENTS-INVALID\",\n path,\n message: `${JSON.stringify(candidate.name)} is ${KIND_NOUNS[candidate.kind]}, not an interface.`,\n received: candidate.kind,\n repair: \"Only descriptors returned by ph.interface can be implemented.\",\n });\n }\n const interfaceName = candidate.name as string;\n if (seen.has(interfaceName)) {\n dslDiagnostics.fail({\n code: \"PH-DEF-IMPLEMENTS-INVALID\",\n path,\n message: `Interface ${JSON.stringify(interfaceName)} is implemented twice.`,\n received: interfaceName,\n repair: \"List each implemented interface once.\",\n });\n }\n seen.add(interfaceName);\n });\n return Object.freeze([...implemented]) as readonly InterfaceDescriptor[];\n}\n\n/**\n * The first signature types an object without `implements` as implementing\n * nothing. A single generic signature would infer `TImplements` from the\n * contextual type instead, as for a union member or an inline state root,\n * and widen it to every interface.\n */\nfunction objectType<const TFields extends ObjectFields>(\n name: string,\n options: ImplementingOptions<TFields, readonly []>,\n): ObjectDescriptor<TFields, readonly []>;\nfunction objectType<\n const TFields extends ObjectFields,\n const TImplements extends readonly InterfaceDescriptor[],\n>(\n name: string,\n options: ImplementingOptions<TFields, TImplements>,\n): ObjectDescriptor<TFields, TImplements>;\nfunction objectType(\n name: string,\n options: ImplementingOptions<ObjectFields, readonly InterfaceDescriptor[]>,\n): ObjectDescriptor {\n return namedType<ObjectDescriptor>({\n kind: \"object\",\n ...implementingMembers(name, options),\n });\n}\n\n/** Overloaded like `objectType`, for the same reason. */\nfunction interfaceType<const TFields extends ObjectFields>(\n name: string,\n options: ImplementingOptions<TFields, readonly []>,\n): InterfaceDescriptor<TFields, readonly []>;\nfunction interfaceType<\n const TFields extends ObjectFields,\n const TImplements extends readonly InterfaceDescriptor[],\n>(\n name: string,\n options: ImplementingOptions<TFields, TImplements>,\n): InterfaceDescriptor<TFields, TImplements>;\nfunction interfaceType(\n name: string,\n options: ImplementingOptions<ObjectFields, readonly InterfaceDescriptor[]>,\n): InterfaceDescriptor {\n return namedType<InterfaceDescriptor>({\n kind: \"interface\",\n ...implementingMembers(name, options),\n });\n}\n\nfunction implementingMembers(\n name: string,\n options: ImplementingOptions<ObjectFields, readonly InterfaceDescriptor[]>,\n) {\n const validName = assertAuthoredName(name, [\"name\"]);\n const config = snapshotDescriptorOptions(\n options,\n [\"fields\", \"description\", \"implements\"],\n [\"options\"],\n );\n return {\n name: validName,\n description: stringOption(config, \"description\", [\"options\"]),\n fields: fieldMap(config.fields, [\"options\", \"fields\"]),\n implements: implementedInterfaces(config),\n };\n}\n\nfunction scalarFactoryGuard<T extends object>(builders: T): Readonly<T> {\n return new Proxy(Object.freeze(builders), {\n get(target, key, receiver) {\n if (\n typeof key === \"string\" &&\n /^[A-Z]/.test(key) &&\n !Object.hasOwn(target, key)\n )\n refuseScalarFactory(key);\n return Reflect.get(target, key, receiver) as unknown;\n },\n });\n}\n\n/**\n * @experimental The field and type builders of a code-first document model:\n * scalar factories such as `ph.String()` and `ph.PHID()`, `ph.scalar` for a\n * project scalar, and `list`, `ref`, `enum`, `object`, `interface`, `input`,\n * and `union`.\n */\nexport const ph = scalarFactoryGuard({\n ...builtInScalarFactories,\n ...catalogScalarFactories,\n scalar: scalarField,\n\n list<\n const TItem extends AnyFieldDescriptor,\n const TRequired extends boolean = false,\n const TDefault extends JsonLiteral | undefined = undefined,\n >(\n item: TItem,\n options?: FieldBuilderOptions<TRequired, TDefault>,\n ): ListDescriptor<\n Nullable<readonly InputOf<TItem>[], TRequired>,\n Nullable<readonly OutputOf<TItem>[], TRequired>,\n Nullable<readonly SourceOf<TItem>[], TRequired>,\n TRequired,\n DefaultFlag<TDefault>\n > {\n assertFieldUse(item, [\"item\"]);\n assertBareListItem(item, [\"item\"]);\n const { required, presentation } = resolveFieldOptions(options, [\n \"options\",\n ]);\n const descriptor = {\n kind: \"list\" as const,\n role: FIELD_USE_ROLE,\n identity: Object.freeze({\n kind: \"list\" as const,\n required,\n item: item.identity,\n }),\n item,\n required,\n presentation,\n validator: undefined as unknown as z.ZodType,\n };\n descriptor.validator = buildValidator(descriptor);\n return registerFieldDescriptor(\n Object.freeze(descriptor) as unknown as ListDescriptor<\n any,\n any,\n any,\n TRequired,\n DefaultFlag<TDefault>\n >,\n );\n },\n\n ref<\n const TTarget extends AnyTypeDescriptor,\n const TRequired extends boolean = false,\n const TDefault extends JsonLiteral | undefined = undefined,\n >(\n target: TTarget | (() => TTarget),\n options?: FieldBuilderOptions<TRequired, TDefault>,\n ): ReferenceDescriptor<\n Nullable<InputOf<TTarget>, TRequired>,\n Nullable<OutputOf<TTarget>, TRequired>,\n Nullable<SourceOf<TTarget>, TRequired>,\n TRequired,\n DefaultFlag<TDefault>\n > {\n let resolved: AnyTypeDescriptor | undefined;\n const resolve = (): AnyTypeDescriptor => {\n if (resolved === undefined) {\n const candidate: unknown =\n typeof target === \"function\" && !isTypeDescriptor(target)\n ? target()\n : target;\n resolved = refTarget(candidate, [\"target\"]);\n }\n return resolved;\n };\n if (typeof target !== \"function\") resolve();\n const { required, presentation } = resolveFieldOptions(options, [\n \"options\",\n ]);\n const descriptor = {\n kind: \"ref\" as const,\n role: FIELD_USE_ROLE,\n identity: Object.freeze({ kind: \"ref\" as const, required }),\n target,\n required,\n presentation,\n validator: undefined as unknown as z.ZodType,\n };\n const reference = descriptor as unknown as ReferenceDescriptor<\n any,\n any,\n any,\n TRequired,\n DefaultFlag<TDefault>\n >;\n registerReference(reference, resolve);\n descriptor.validator = buildValidator(reference);\n return registerFieldDescriptor(Object.freeze(reference));\n },\n\n enum<const TValues extends readonly [EnumValueInput, ...EnumValueInput[]]>(\n name: string,\n options: EnumOptions<TValues>,\n ): EnumDescriptor<TValues> {\n const validName = assertAuthoredName(name, [\"name\"]);\n const config = snapshotDescriptorOptions(\n options,\n [\"values\", \"description\"],\n [\"options\"],\n );\n return namedType<EnumDescriptor<TValues>>({\n kind: \"enum\",\n name: validName,\n description: stringOption(config, \"description\", [\"options\"]),\n values: enumValues(config.values),\n });\n },\n\n object: objectType,\n\n interface: interfaceType,\n\n input<const TFields extends ObjectFields>(\n ...args:\n | [name: string, options: FieldsOptions<TFields>]\n | [options: FieldsOptions<TFields>]\n ): InputDescriptor<TFields> {\n const [nameOrOptions, maybeOptions] = args;\n const name =\n typeof nameOrOptions === \"string\"\n ? assertAuthoredName(nameOrOptions, [\"name\"])\n : null;\n const options =\n typeof nameOrOptions === \"string\" ? maybeOptions : nameOrOptions;\n const config = snapshotDescriptorOptions(\n options,\n [\"fields\", \"description\"],\n [\"options\"],\n );\n return namedType<InputDescriptor<TFields>>({\n kind: \"input\",\n name,\n description: stringOption(config, \"description\", [\"options\"]),\n fields: fieldMap(config.fields, [\"options\", \"fields\"]) as TFields,\n });\n },\n\n union<\n const TMembers extends readonly [ObjectDescriptor, ...ObjectDescriptor[]],\n >(name: string, options: UnionOptions<TMembers>): UnionDescriptor<TMembers> {\n const validName = assertAuthoredName(name, [\"name\"]);\n const config = snapshotDescriptorOptions(\n options,\n [\"members\", \"description\"],\n [\"options\"],\n );\n const members = snapshotDescriptorArray(\n config.members,\n [\"options\", \"members\"],\n \"PH-DEF-UNION-MEMBERS-INVALID\",\n \"Pass members as a nonempty array of descriptors returned by ph.object.\",\n );\n if (members.length === 0) {\n dslDiagnostics.fail({\n code: \"PH-DEF-UNION-MEMBERS-INVALID\",\n path: [\"options\", \"members\"],\n message: \"A union must declare at least one object member.\",\n repair: \"Add at least one ph.object descriptor to members.\",\n });\n }\n const seen = new Set<string>();\n members.forEach((member, index) => {\n const path = [\"options\", \"members\", index];\n assertNamedType(\n member,\n path,\n \"PH-DEF-UNION-MEMBERS-INVALID\",\n \"Replace the member with a descriptor returned by ph.object.\",\n );\n if (member.kind !== \"object\") {\n dslDiagnostics.fail({\n code: \"PH-DEF-UNION-MEMBERS-INVALID\",\n path,\n message: `Union member ${JSON.stringify(member.name)} is ${KIND_NOUNS[member.kind]}; GraphQL unions hold object types only.`,\n received: member.kind,\n repair: \"Replace the member with a descriptor returned by ph.object.\",\n });\n }\n const memberName = member.name as string;\n if (seen.has(memberName)) {\n dslDiagnostics.fail({\n code: \"PH-DEF-UNION-MEMBERS-INVALID\",\n path,\n message: `Union member ${JSON.stringify(memberName)} is declared twice.`,\n received: memberName,\n repair: \"List each member object once.\",\n });\n }\n seen.add(memberName);\n });\n return namedType<UnionDescriptor<TMembers>>({\n kind: \"union\",\n name: validName,\n description: stringOption(config, \"description\", [\"options\"]),\n members: Object.freeze([...members]) as unknown as TMembers,\n });\n },\n});\n\n/** @experimental The type of `ph`. */\nexport type Ph = typeof ph;\n","import type {\n FieldDefinition,\n InputFieldDefinition,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { scalarCatalog } from \"../../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { ph } from \"../../dsl/field.js\";\nimport { createScalarField } from \"../../dsl/field-options.js\";\nimport { builtInScalarFactories } from \"../../dsl/scalar-fields.js\";\nimport { definitionEquals } from \"../../kernel/graphql-ast.js\";\nimport type {\n AnyFieldDescriptor,\n AnyTypeDescriptor,\n ObjectDescriptor,\n ObjectFields,\n} from \"../../dsl/types.js\";\n\nexport function storedStateDescriptor(\n typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n root: string,\n scalars: readonly ScalarDefinition[],\n): AnyTypeDescriptor | undefined {\n const scalarsByName = new Map<string, ScalarDefinition>(\n [...scalarCatalog, ...scalars].map((scalar) => [scalar.name, scalar]),\n );\n const built = new Map<string, AnyTypeDescriptor>();\n\n const fieldUse = (\n type: TypeReferenceDefinition,\n field?: FieldDefinition | InputFieldDefinition,\n ): AnyFieldDescriptor => {\n const options = {\n required: type.required,\n ...(field !== undefined &&\n \"defaultValue\" in field &&\n field.defaultValue !== undefined && {\n defaultValue: field.defaultValue,\n }),\n };\n switch (type.kind) {\n case \"list\":\n return ph.list(fieldUse(type.item), options);\n case \"named\":\n return ph.ref(() => named(type.name), options);\n case \"scalar\": {\n const equals = field === undefined ? null : definitionEquals(field);\n const scalarOptions = {\n ...options,\n ...(equals !== null && { equals }),\n };\n if (Object.hasOwn(builtInScalarFactories, type.name)) {\n return builtInScalarFactories[\n type.name as keyof typeof builtInScalarFactories\n ](scalarOptions);\n }\n const definition = scalarsByName.get(type.name);\n if (definition === undefined) {\n throw new TypeError(`Unknown scalar ${type.name}.`);\n }\n return createScalarField(\n definition.name,\n definition.schema,\n scalarOptions,\n definition,\n );\n }\n }\n };\n\n const fields = (\n members: readonly (FieldDefinition | InputFieldDefinition)[],\n ): ObjectFields =>\n Object.fromEntries(\n members.map((member) => [member.name, fieldUse(member.type, member)]),\n );\n\n const named = (name: string): AnyTypeDescriptor => {\n const existing = built.get(name);\n if (existing !== undefined) return existing;\n const type = typesByName.get(name);\n if (type === undefined) throw new TypeError(`Unknown type ${name}.`);\n const descriptor = describe(type);\n built.set(name, descriptor);\n return descriptor;\n };\n\n const describe = (type: NamedGraphQLTypeDefinition): AnyTypeDescriptor => {\n switch (type.kind) {\n case \"enum\":\n return ph.enum(type.name, {\n values: type.values.map(({ name }) => name) as [string, ...string[]],\n });\n case \"object\":\n return ph.object(type.name, { fields: fields(type.fields) });\n case \"interface\":\n return ph.interface(type.name, { fields: fields(type.fields) });\n case \"input\":\n return ph.input(type.name, { fields: fields(type.fields) });\n case \"union\":\n return ph.union(type.name, {\n members: type.members.map(\n (member) => named(member) as ObjectDescriptor,\n ) as [ObjectDescriptor, ...ObjectDescriptor[]],\n });\n }\n };\n\n const reachable = (name: string, seen: Set<string>): void => {\n if (seen.has(name)) return;\n seen.add(name);\n named(name);\n const type = typesByName.get(name);\n const references = (reference: TypeReferenceDefinition): string[] =>\n reference.kind === \"list\"\n ? references(reference.item)\n : reference.kind === \"named\"\n ? [reference.name]\n : [];\n const next =\n type === undefined\n ? []\n : type.kind === \"union\"\n ? type.members\n : type.kind === \"enum\"\n ? []\n : type.fields.flatMap((field) => references(field.type));\n for (const member of next) reachable(member, seen);\n };\n\n try {\n reachable(root, new Set());\n return named(root);\n } catch {\n return undefined;\n }\n}\n","import { DocumentModelGlobalStateSchema } from \"@powerhousedao/shared/document-model\";\nimport type {\n CompiledErrorDefinition,\n DefinitionExample,\n DefinitionPath,\n DefinitionSource,\n DocumentModelDefinition,\n DocumentModelGlobalState,\n DocumentModelModuleDefinition,\n DocumentModelOperationDefinition,\n DocumentModelPHState,\n DocumentModelSpecificationDefinition,\n DocumentSpecification,\n InputTypeDefinition,\n JsonValue,\n NamedGraphQLTypeDefinition,\n OperationSpecification,\n StateDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { scalarCatalog } from \"../../../scalars/catalog.js\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport { serializeAndValidateInitialValue } from \"../../compiler/initial-value.js\";\nimport { scalarReferences } from \"../../compiler/stored-scalar.js\";\nimport {\n deriveDocumentModelNames,\n deriveDocumentModelSymbolNames,\n} from \"../../compiler/naming.js\";\nimport { checkDocumentModelDefinitionShape } from \"../../compiler/wire-shape.js\";\nimport {\n rejectionReceived,\n snapshotRecord,\n snapshotDataRecord,\n} from \"../../kernel/data-properties.js\";\nimport { DefinitionDiagnosticCollector } from \"../../kernel/diagnostic-collector.js\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport {\n canonicalDigest,\n EMPTY_INPUT_FIELD_NAME,\n} from \"../../kernel/primitives.js\";\nimport type { NormalizedDocumentModelResult } from \"../adapters/types.js\";\nimport {\n type ToolingDiagnosticCode,\n toolingDiagnostics,\n} from \"../diagnostic-codes.js\";\nimport {\n declaredTypeNames,\n type GraphQLDefinitionNode,\n referencedTypeNames,\n structuredTypes,\n} from \"../graphql/ast-to-structured.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\nimport { storedStateDescriptor } from \"./state-descriptor.js\";\n\ntype Collector = DefinitionDiagnosticCollector<ToolingDiagnosticCode>;\n\n/** @experimental Options for {@link adaptSchemaFirstDocumentModelModule}. */\nexport type SchemaFirstAdapterOptions = {\n readonly version?: number;\n\n readonly scalars?: readonly ScalarDefinition[];\n};\n\nconst EXAMPLE_KEY_PREFIX = \"schema-first-id:\";\n\nfunction producesRuntimeSymbol(name: unknown): name is string {\n if (typeof name !== \"string\" || name.trim() === \"\") return false;\n const { typeName, memberName, constantName } =\n deriveDocumentModelSymbolNames(name);\n return typeName !== \"\" && memberName !== \"\" && constantName !== \"\";\n}\n\nfunction blocked(\n collector: Collector,\n kind: \"module\" | \"operation\" | \"error\",\n value: unknown,\n path: DefinitionPath,\n): undefined {\n const received =\n typeof value === \"string\" ? JSON.stringify(value) : String(value);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path,\n message: `The stored ${kind} name ${received} never produced a runtime symbol, so there is no generated ${kind} to describe.`,\n expected: \"a name with at least one letter or digit\",\n received,\n repair: `Name the ${kind} in the document model editor and generate again.`,\n });\n return undefined;\n}\n\nfunction examples(\n stored: readonly { readonly id: string; readonly value: string }[],\n): readonly DefinitionExample[] {\n return stored.map(({ id, value }) => ({\n id,\n key: `${EXAMPLE_KEY_PREFIX}${id}`,\n value,\n }));\n}\n\nfunction parseInitialValue(\n collector: Collector,\n stored: string,\n path: DefinitionPath,\n emptyIsObject: boolean,\n): JsonValue | undefined {\n if (emptyIsObject && stored.trim() === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(stored);\n } catch {\n parsed = undefined;\n }\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as JsonValue;\n }\n collector.add({\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path,\n message:\n \"The stored initial value does not parse to a JSON object, so it cannot be the value its state root holds.\",\n expected: \"a JSON object, encoded once\",\n received: stored,\n repair: \"Store the scope's initial value as a JSON object.\",\n });\n return undefined;\n}\n\nfunction emptyInputProjection(input: InputTypeDefinition): InputTypeDefinition {\n const [only] = input.fields;\n const empty =\n input.fields.length === 1 &&\n only.name === EMPTY_INPUT_FIELD_NAME &&\n only.type.kind === \"scalar\" &&\n only.type.name === \"Boolean\" &&\n !only.type.required;\n return empty ? { ...input, fields: [] } : input;\n}\n\nfunction modelScalarReferences(\n definitions: readonly GraphQLDefinitionNode[],\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition[\"scalars\"] {\n const used = new Set(referencedTypeNames(definitions));\n return scalarReferences(\n used,\n new Map(\n scalars\n .filter(({ name }) => used.has(name))\n .map((definition) => [definition.name, definition]),\n ),\n );\n}\n\nfunction normalizeOperation(\n collector: Collector,\n operation: OperationSpecification,\n typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition>,\n path: DefinitionPath,\n): DocumentModelOperationDefinition | undefined {\n if (!producesRuntimeSymbol(operation.name)) {\n return blocked(collector, \"operation\", operation.name, [...path, \"name\"]);\n }\n if (operation.scope !== \"global\" && operation.scope !== \"local\") {\n collector.add({\n code: \"PH-DM-SCOPE-UNSUPPORTED\",\n path: [...path, \"scope\"],\n message: `Operation ${JSON.stringify(operation.name)} is stored in scope ${JSON.stringify(operation.scope)}, which a V1 definition cannot record.`,\n expected: \"global | local\",\n received: String(operation.scope),\n repair: \"Store the operation in the global or local scope.\",\n });\n return undefined;\n }\n const names = deriveDocumentModelSymbolNames(operation.name);\n const inputName = `${names.typeName}Input`;\n const hasSchema = operation.schema !== null && operation.schema.trim() !== \"\";\n const declared = hasSchema ? typesByName.get(inputName) : undefined;\n if (hasSchema && declared?.kind !== \"input\") {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [...path, \"schema\"],\n message: `The stored schema of operation ${JSON.stringify(operation.name)} declares no input type ${inputName}, which codegen and the host read its input from.`,\n expected: `input ${inputName} { ... }`,\n received: declared === undefined ? \"absent\" : declared.kind,\n repair: `Declare input ${inputName} in the operation's schema.`,\n });\n return undefined;\n }\n const errors = operation.errors.map(\n (error, index): CompiledErrorDefinition | undefined =>\n producesRuntimeSymbol(error.name)\n ? {\n id: error.id,\n key: deriveDocumentModelSymbolNames(error.name).typeName,\n code: error.code,\n name: error.name,\n description: error.description,\n template: error.template,\n }\n : blocked(collector, \"error\", error.name, [\n ...path,\n \"errors\",\n index,\n \"name\",\n ]),\n );\n if (errors.includes(undefined)) return undefined;\n return {\n id: operation.id,\n key: names.memberName,\n name: operation.name,\n description: operation.description,\n actionType: names.constantName,\n creatorKey: names.memberName,\n scope: operation.scope,\n input: declared?.kind === \"input\" ? emptyInputProjection(declared) : null,\n errors: errors as readonly CompiledErrorDefinition[],\n examples: examples(operation.examples),\n template: operation.template,\n reducer: operation.reducer,\n };\n}\n\nfunction acceptedByRoot(\n collector: Collector,\n initialValue: JsonValue,\n root: string,\n types: {\n readonly byName: ReadonlyMap<string, NamedGraphQLTypeDefinition>;\n readonly scalars: readonly ScalarDefinition[];\n },\n path: DefinitionPath,\n): boolean {\n const descriptor = storedStateDescriptor(types.byName, root, types.scalars);\n if (descriptor === undefined) return true;\n const checked = serializeAndValidateInitialValue(descriptor, initialValue);\n if (checked.ok) return true;\n collector.add({\n code: \"PH-DM-INITIAL-VALUE-INVALID\",\n path,\n message: `The ${root} schema rejects this initial value.`,\n expected: `a value ${root} accepts`,\n received: checked.message,\n repair:\n \"Correct the stored initial value so the declared state schema accepts it.\",\n });\n return false;\n}\n\nfunction rootState(\n collector: Collector,\n stored: DocumentSpecification[\"state\"][\"global\"],\n root: string | null,\n path: DefinitionPath,\n scope: \"global\" | \"local\",\n types: {\n readonly byName: ReadonlyMap<string, NamedGraphQLTypeDefinition>;\n readonly scalars: readonly ScalarDefinition[];\n },\n): StateDefinition | undefined {\n const initialValuePath = [...path, \"initialValue\"];\n const initialValue = parseInitialValue(\n collector,\n stored.initialValue,\n initialValuePath,\n scope === \"local\",\n );\n if (\n initialValue === undefined ||\n (root !== null &&\n !acceptedByRoot(collector, initialValue, root, types, initialValuePath))\n ) {\n return undefined;\n }\n const materialized = {\n initialValue: stored.initialValue,\n examples: stored.examples.map(({ id, value }) => ({ id, value })),\n };\n return root === null\n ? {\n root: null,\n initialValue: {},\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: \"\" },\n }\n : {\n root: { kind: \"named\", name: root, required: true },\n initialValue,\n examples: examples(stored.examples),\n unknownKeys: \"preserve\",\n materialized: { ...materialized, schema: stored.schema },\n };\n}\n\nconst BUILT_IN_SCALARS: ReadonlySet<string> = new Set([\n \"ID\",\n \"String\",\n \"Boolean\",\n \"Int\",\n \"Float\",\n]);\n\nconst CATALOG_SCALARS: ReadonlySet<string> = new Set(\n scalarCatalog.map(({ name }) => name),\n);\n\n/**\n * Codegen imports every scalar a stored schema declares or uses from\n * scalars/index.ts unless it is built in or in the catalog. A missing export\n * would otherwise surface later as an error that never names it.\n */\nfunction knownScalars(\n collector: Collector,\n segments: readonly {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[],\n declared: ReadonlySet<string>,\n scalars: readonly ScalarDefinition[],\n): boolean {\n const project = new Set(scalars.map(({ name }) => name));\n const reported = new Set<string>();\n for (const segment of segments) {\n const names = [\n ...referencedTypeNames(segment.definitions)\n .filter((name) => !declared.has(name))\n .map((name) => ({ name, verb: \"uses\" })),\n ...segment.definitions.flatMap((node) =>\n node.kind === \"ScalarTypeDefinition\"\n ? [{ name: node.name.value, verb: \"declares\" }]\n : [],\n ),\n ];\n for (const { name, verb } of names) {\n if (\n BUILT_IN_SCALARS.has(name) ||\n CATALOG_SCALARS.has(name) ||\n project.has(name) ||\n reported.has(name)\n ) {\n continue;\n }\n reported.add(name);\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema ${verb} scalar ${name}, which is not a GraphQL built-in, a catalog scalar, or a project scalar exported from scalars/index.ts.`,\n expected: \"a scalar defined with defineScalar in scalars/index.ts\",\n received: name,\n repair: `Export ${name} from scalars/index.ts with defineScalar, or use a catalog scalar.`,\n });\n }\n }\n return reported.size === 0;\n}\n\n/** A specification's stored SDL strings, in the order its retained document concatenates them. */\nexport function storedSchemaSegments(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): readonly { readonly schema: string; readonly path: DefinitionPath }[] {\n return [\n {\n schema: specification.state.global.schema,\n path: [...path, \"state\", \"global\", \"schema\"],\n },\n {\n schema: specification.state.local.schema,\n path: [...path, \"state\", \"local\", \"schema\"],\n },\n ...specification.modules.flatMap((module, moduleIndex) =>\n module.operations.map((operation, operationIndex) => ({\n schema: operation.schema ?? \"\",\n path: [\n ...path,\n \"modules\",\n moduleIndex,\n \"operations\",\n operationIndex,\n \"schema\",\n ],\n })),\n ),\n ];\n}\n\nfunction normalizeSpecification(\n collector: Collector,\n specification: DocumentSpecification,\n roots: { readonly global: string; readonly local: string },\n path: DefinitionPath,\n scalars: readonly ScalarDefinition[],\n): DocumentModelSpecificationDefinition | undefined {\n const segments = storedSchemaSegments(specification, path);\n const parsedSegments: {\n readonly path: DefinitionPath;\n readonly definitions: readonly GraphQLDefinitionNode[];\n }[] = [];\n for (const segment of segments) {\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: segment.path,\n message: `The stored schema is not GraphQL SDL: ${parsed.message}`,\n expected: \"GraphQL SDL\",\n received: segment.schema,\n repair: \"Fix the schema in the document model editor.\",\n });\n return undefined;\n }\n parsedSegments.push({\n path: segment.path,\n definitions: parsed.document.definitions,\n });\n }\n const definitions = parsedSegments.flatMap((segment) => segment.definitions);\n const declared = declaredTypeNames(definitions);\n if (!knownScalars(collector, parsedSegments, declared, scalars)) {\n return undefined;\n }\n const allTypes = structuredTypes(definitions, declared);\n const typesByName: ReadonlyMap<string, NamedGraphQLTypeDefinition> = new Map(\n allTypes.map((type) => [type.name, type]),\n );\n\n const hasLocalRoot = specification.state.local.schema.trim() !== \"\";\n for (const scope of [\"global\", \"local\"] as const) {\n if (scope === \"local\" && !hasLocalRoot) continue;\n if (typesByName.get(roots[scope])?.kind !== \"object\") {\n collector.add({\n code: \"PH-DM-STATE-ROOT-INVALID\",\n path: [...path, \"state\", scope, \"schema\"],\n message: `The stored ${scope} state schema declares no object type named ${roots[scope]}.`,\n expected: `type ${roots[scope]} { ... }`,\n received: [...typesByName.keys()].join(\", \"),\n repair: `Name the ${scope} state root after the model; every consumer resolves it by that name.`,\n });\n return undefined;\n }\n }\n\n const modules: DocumentModelModuleDefinition[] = [];\n for (const [moduleIndex, module] of specification.modules.entries()) {\n const modulePath = [...path, \"modules\", moduleIndex];\n if (!producesRuntimeSymbol(module.name)) {\n return blocked(collector, \"module\", module.name, [...modulePath, \"name\"]);\n }\n const operations = module.operations.map((operation, operationIndex) =>\n normalizeOperation(collector, operation, typesByName, [\n ...modulePath,\n \"operations\",\n operationIndex,\n ]),\n );\n if (operations.includes(undefined)) return undefined;\n modules.push({\n id: module.id,\n key: deriveDocumentModelSymbolNames(module.name).memberName,\n name: module.name,\n description: module.description,\n operations: operations as readonly DocumentModelOperationDefinition[],\n });\n }\n\n const global = rootState(\n collector,\n specification.state.global,\n roots.global,\n [...path, \"state\", \"global\"],\n \"global\",\n { byName: typesByName, scalars },\n );\n const local = rootState(\n collector,\n specification.state.local,\n hasLocalRoot ? roots.local : null,\n [...path, \"state\", \"local\"],\n \"local\",\n { byName: typesByName, scalars },\n );\n if (global === undefined || global.root === null || local === undefined) {\n return undefined;\n }\n\n const inputs = new Set(\n modules.flatMap((module) =>\n module.operations.flatMap((operation) =>\n operation.input === null ? [] : [operation.input.name],\n ),\n ),\n );\n return {\n version: specification.version,\n scalars: modelScalarReferences(definitions, scalars),\n graphQLCompatibility: {\n kind: \"graphql-ast-v1\",\n document: { kind: \"Document\", definitions },\n preserveDefinitionOrder: true,\n },\n types: allTypes.filter((type) => !inputs.has(type.name)),\n state: { global, local },\n modules,\n changeLog: [...specification.changeLog],\n };\n}\n\ntype StoredModel = {\n readonly global: DocumentModelGlobalState;\n readonly documentModel: DocumentModelPHState;\n readonly version: number;\n};\n\nfunction storedModel(\n collector: Collector,\n value: unknown,\n options: SchemaFirstAdapterOptions,\n): StoredModel | undefined {\n const root = snapshotRecord(value, undefined, []);\n const module =\n root.ok && root.value.documentModel !== undefined ? root.value : undefined;\n const documentModel = module === undefined ? value : module.documentModel;\n const path = module === undefined ? [] : [\"documentModel\"];\n const state = snapshotRecord(documentModel, undefined, path);\n const global = state.ok\n ? snapshotDataRecord(state.value.global, undefined, [...path, \"global\"])\n : state;\n if (!global.ok) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: global.path,\n message: `This export is neither a generated document-model module nor its stored state (${global.reason}).`,\n expected: \"a module with documentModel.global, or a DocumentModelPHState\",\n received: rejectionReceived(global),\n repair: \"Pass the module ph generate produced, or its documentModel.\",\n });\n return undefined;\n }\n const parsed = DocumentModelGlobalStateSchema().safeParse(global.value);\n if (!parsed.success) {\n for (const issue of parsed.error.issues) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\n ...path,\n \"global\",\n ...issue.path.map((segment) =>\n typeof segment === \"symbol\" ? String(segment) : segment,\n ),\n ],\n message: issue.message,\n expected: \"a stored document model matching DocumentModelGlobalState\",\n received: \"a malformed stored model\",\n repair:\n \"Pass the module ph generate produced, or its stored documentModel.\",\n });\n }\n return undefined;\n }\n const declared: unknown = options.version ?? module?.version ?? 1;\n if (\n typeof declared !== \"number\" ||\n !Number.isSafeInteger(declared) ||\n declared <= 0\n ) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"version\"],\n message: \"A module's registry version is a positive safe integer.\",\n expected: \"a positive safe integer\",\n received:\n typeof declared === \"number\"\n ? String(declared)\n : describeReceived(declared),\n repair: \"Pass the version this module registers.\",\n });\n return undefined;\n }\n return {\n global: parsed.data,\n documentModel: documentModel as DocumentModelPHState,\n version: declared,\n };\n}\n\n/**\n * @experimental Normalizes one generated schema-first module, or one stored\n * `DocumentModelPHState`, into the V1 wire shape. A model it cannot\n * normalize is reported in `diagnostics`; the stored members it trusts are\n * the ones `ph generate` writes. Experimental: it exists so code-first and\n * schema-first models can be read through one shape while code-first\n * projects are introduced.\n */\nexport function adaptSchemaFirstDocumentModelModule(\n value: unknown,\n source: DefinitionSource,\n options: SchemaFirstAdapterOptions = {},\n): NormalizedDocumentModelResult {\n const probe: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n );\n const stored = storedModel(probe, value, options);\n if (stored === undefined) {\n return {\n artifacts: [],\n upgradeManifest: null,\n diagnostics: probe.diagnostics,\n };\n }\n const { global, version } = stored;\n const collector: Collector = new DefinitionDiagnosticCollector(\n toolingDiagnostics,\n { kind: \"document-model\", key: global.id, version },\n );\n const failed = (): NormalizedDocumentModelResult => ({\n artifacts: [],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n });\n const names = deriveDocumentModelNames({ id: global.id, name: global.name });\n const specifications = global.specifications.map((specification, index) =>\n normalizeSpecification(\n collector,\n specification,\n { global: names.globalStateRootName, local: names.localStateRootName },\n [\"specifications\", index],\n options.scalars ?? [],\n ),\n );\n if (specifications.includes(undefined)) return failed();\n\n const definition: DocumentModelDefinition = {\n kind: \"powerhouse.document-model\",\n formatVersion: 1,\n compatibility: {\n identity: \"explicit-schema-first\",\n scalarCoercion: \"catalog-v1\",\n serialization: \"explicit-schema-first\",\n },\n model: {\n documentType: global.id,\n graphQLName: names.graphQLName,\n name: global.name,\n description: global.description,\n extension: global.extension,\n author: { name: global.author.name, website: global.author.website },\n },\n specifications: specifications as DocumentModelSpecificationDefinition[],\n };\n const shape = checkDocumentModelDefinitionShape(definition);\n collector.merge(shape);\n if (shape.length > 0) return failed();\n if (!definition.specifications.some((entry) => entry.version === version)) {\n collector.add({\n code: \"PH-DM-DECLARATION-INVALID\",\n path: [\"specifications\"],\n message: `The stored history carries no version ${version}, which is the version this module serves.`,\n expected: `a specification for version ${version}`,\n received: definition.specifications\n .map((entry) => String(entry.version))\n .join(\", \"),\n repair:\n \"Pass the version this module registers, or the module that serves a stored version.\",\n });\n return failed();\n }\n return {\n artifacts: [\n {\n kind: \"powerhouse.document-model-artifact\",\n source,\n documentType: global.id,\n version,\n definition,\n digest: canonicalDigest(definition),\n documentModel: stored.documentModel,\n },\n ],\n upgradeManifest: null,\n diagnostics: collector.diagnostics,\n };\n}\n","import type {\n DefinitionPath,\n DocumentSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport type { DefinitionRelocation } from \"../adapters/producer.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport { parseSchema } from \"../graphql/parse-schema.js\";\nimport { storedSchemaSegments } from \"./schema-first-document-model-module-adapter.js\";\n\ntype SegmentDeclarations = {\n /** The segment of each node of the retained document, in document order. */\n readonly nodes: readonly DefinitionPath[];\n /** The first segment that defines each type, else the first that extends it. */\n readonly types: ReadonlyMap<string, DefinitionPath>;\n};\n\nfunction segmentDeclarations(\n specification: DocumentSpecification,\n path: DefinitionPath,\n): SegmentDeclarations {\n const nodes: DefinitionPath[] = [];\n const defined = new Map<string, DefinitionPath>();\n const extended = new Map<string, DefinitionPath>();\n for (const segment of storedSchemaSegments(specification, path)) {\n // The adapter produced an artifact, so every segment parsed.\n const parsed = parseSchema(segment.schema);\n if (!parsed.ok) continue;\n for (const node of parsed.document.definitions) {\n nodes.push(segment.path);\n const name = \"name\" in node ? node.name.value : undefined;\n if (name === undefined) continue;\n const first = node.kind.endsWith(\"Extension\") ? extended : defined;\n if (!first.has(name)) first.set(name, segment.path);\n }\n }\n return { nodes, types: new Map([...extended, ...defined]) };\n}\n\n/**\n * A schema-first author edits the stored file, which is the served global\n * state, and declares types in its SDL segments rather than as structured\n * types. Served paths lose their `documentModel/global` prefix; a type, a\n * scalar or a retained document node points at the segment that declares it.\n * Every result is cut back to the deepest member the stored file has, so no\n * location names a normalized-only member or reaches inside an SDL string.\n */\nexport function storedModelRelocation(\n artifact: NormalizedDocumentModelArtifact,\n): DefinitionRelocation {\n const stored = artifact.documentModel.global.specifications;\n const declarations = new Map<number, SegmentDeclarations>();\n const declared = (index: number): SegmentDeclarations => {\n let found = declarations.get(index);\n if (found === undefined) {\n found = segmentDeclarations(stored[index], [\"specifications\", index]);\n declarations.set(index, found);\n }\n return found;\n };\n const relocate = (path: DefinitionPath): DefinitionPath => {\n if (path[0] === \"documentModel\" && path[1] === \"global\") {\n return path.slice(2);\n }\n const [root, index, member, ...rest] = path;\n if (\n root !== \"specifications\" ||\n typeof index !== \"number\" ||\n stored.at(index) === undefined\n ) {\n return path;\n }\n const specification: DefinitionPath = [\"specifications\", index];\n if (member === \"types\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.types.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"scalars\") {\n const name =\n typeof rest[0] === \"number\"\n ? artifact.definition.specifications.at(index)?.scalars.at(rest[0])\n ?.name\n : undefined;\n return (\n (name === undefined ? undefined : declared(index).types.get(name)) ??\n specification\n );\n }\n if (member === \"graphQLCompatibility\") {\n const [document, definitions, node] = rest;\n return (\n (document === \"document\" &&\n definitions === \"definitions\" &&\n typeof node === \"number\"\n ? declared(index).nodes.at(node)\n : undefined) ?? specification\n );\n }\n return path;\n };\n return (path) => storedPrefix(artifact.documentModel.global, relocate(path));\n}\n\nfunction storedPrefix(stored: unknown, path: DefinitionPath): DefinitionPath {\n let value = stored;\n let depth = 0;\n for (const segment of path) {\n if (typeof value !== \"object\" || value === null) break;\n if (!Object.hasOwn(value, segment)) break;\n value = (value as Readonly<Record<string | number, unknown>>)[segment];\n depth += 1;\n }\n return path.slice(0, depth);\n}\n","import {\n defaultBaseState,\n type DefinitionDiagnostic,\n type DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { pathWithin } from \"@powerhousedao/shared/clis/real-paths\";\nimport { readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport type { ScalarDefinition } from \"../../../scalars/types.js\";\nimport type {\n DefinitionProducer,\n DefinitionRelocation,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\nimport { describeThrown } from \"../structured-diagnostics.js\";\nimport { loadProjectScalars } from \"./project-scalars.js\";\nimport { adaptSchemaFirstDocumentModelModule } from \"./schema-first-document-model-module-adapter.js\";\nimport { storedModelRelocation } from \"./stored-locations.js\";\n\ntype StoredModelFiles = {\n readonly files: readonly string[];\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\nfunction unreadable(\n packageRoot: string,\n path: string,\n what: string,\n error: unknown,\n): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier: packageSpecifier(packageRoot, path) },\n path: [],\n message: `The ${what} could not be read, so the stored models in it are not checked.`,\n expected: `a readable ${what}`,\n received: describeThrown(error),\n repair: \"Fix the permissions of the path.\",\n });\n}\n\nfunction outsidePackage(specifier: `./${string}`): DefinitionDiagnostic {\n return toolingDiagnostics.create({\n code: \"PH-CONFIG-SOURCE-OUTSIDE-PACKAGE\",\n source: { specifier },\n path: [],\n message:\n \"The stored document model resolves through a symlink that leaves the package root, so it is not this package's model.\",\n expected: \"a real path contained by the package root\",\n received: specifier,\n repair:\n \"Replace the symlink with a model file that really lives in this package.\",\n });\n}\n\n/**\n * The stored specifications discovery listed. A symlinked file counts when\n * its real path stays in the package; anything but a readable file is\n * reported, never skipped, because discovery already gave the directory to\n * a schema-first model.\n */\nfunction storedModelFiles(\n packageRoot: string,\n stored: readonly DefinitionSource[],\n): StoredModelFiles {\n let packageRootIdentity: string;\n try {\n packageRootIdentity = realpathSync.native(packageRoot);\n } catch (error) {\n return {\n files: [],\n diagnostics: [\n unreadable(packageRoot, packageRoot, \"package root\", error),\n ],\n };\n }\n const files: string[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const { specifier } of stored) {\n const file = join(packageRoot, ...specifier.slice(2).split(\"/\"));\n let real: string;\n try {\n if (!statSync(file).isFile()) {\n throw new Error(`${specifier} is not a file.`);\n }\n real = realpathSync.native(file);\n } catch (error) {\n diagnostics.push(\n unreadable(packageRoot, file, \"stored document model file\", error),\n );\n continue;\n }\n if (pathWithin(packageRootIdentity, real) !== null) files.push(file);\n else diagnostics.push(outsidePackage(specifier));\n }\n return { files, diagnostics };\n}\n\nfunction packageSpecifier(packageRoot: string, file: string): `./${string}` {\n return `./${relative(packageRoot, file).split(sep).join(\"/\")}`;\n}\n\nfunction storedVersion(value: unknown): number | undefined {\n const specifications = (value as { specifications?: unknown } | null)\n ?.specifications;\n if (!Array.isArray(specifications)) return undefined;\n const version = (specifications.at(-1) as { version?: unknown } | undefined)\n ?.version;\n return typeof version === \"number\" ? version : undefined;\n}\n\nfunction adaptStoredModelFile(\n file: string,\n source: DefinitionSource,\n scalars: readonly ScalarDefinition[],\n): Omit<ProducedDefinitions, \"relocations\"> & {\n readonly relocation?: DefinitionRelocation;\n} {\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source,\n path: [],\n message: \"The stored document model file could not be read.\",\n expected: \"a readable JSON file\",\n received: describeThrown(error),\n repair: \"Fix the file's permissions.\",\n }),\n ],\n };\n }\n let stored: unknown;\n try {\n stored = JSON.parse(text);\n } catch (error) {\n return {\n artifacts: [],\n diagnostics: [\n toolingDiagnostics.create({\n code: \"PH-DM-DECLARATION-INVALID\",\n source,\n path: [],\n message: \"The stored document model is not JSON.\",\n expected: \"the JSON the document model editor saves\",\n received: describeThrown(error),\n repair:\n \"Repair the JSON, or save the model again from the document model editor.\",\n }),\n ],\n };\n }\n const version = storedVersion(stored);\n // Not createState: it fills absent members with defaults, which would hide\n // a malformed file.\n const result = adaptSchemaFirstDocumentModelModule(\n { ...defaultBaseState(), global: stored, local: {} },\n source,\n { scalars, ...(version !== undefined && { version }) },\n );\n const artifact = result.artifacts.at(0);\n return {\n // Every stored version is served, and each carries the whole history.\n artifacts:\n artifact === undefined\n ? []\n : artifact.definition.specifications.map((specification) => ({\n ...artifact,\n version: specification.version,\n })),\n ...(artifact !== undefined && {\n relocation: storedModelRelocation(artifact),\n }),\n // The adapter roots shape errors at the wrapping state's `global`, which\n // is the file itself.\n diagnostics: result.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n source,\n path:\n diagnostic.path[0] === \"global\"\n ? diagnostic.path.slice(1)\n : diagnostic.path,\n })),\n };\n}\n\n/**\n * Normalizes every `<documentModelsDir>/<name>/<name>.json` discovery\n * listed, with the project scalars `scalars/index.ts` exports. A file that\n * cannot be read or adapted is a diagnostic.\n */\nexport const readStoredDocumentModels: DefinitionProducer = async (input) => {\n const { packageRoot, loaded } = input;\n const { files, diagnostics } = storedModelFiles(\n packageRoot,\n loaded.sourceSet.stored,\n );\n if (files.length === 0) {\n return { artifacts: [], diagnostics, relocations: new Map() };\n }\n const scalars = await loadProjectScalars(input);\n const relocations = new Map<string, DefinitionRelocation>();\n const results = files.map((file) => {\n const specifier = packageSpecifier(packageRoot, file);\n const result = adaptStoredModelFile(\n file,\n { specifier },\n scalars.definitions,\n );\n if (result.relocation !== undefined) {\n relocations.set(specifier, result.relocation);\n }\n return result;\n });\n return {\n artifacts: results.flatMap((result) => result.artifacts),\n diagnostics: [\n ...diagnostics,\n ...scalars.diagnostics,\n ...results.flatMap((result) => result.diagnostics),\n ],\n relocations,\n };\n};\n","import type {\n DefinitionDiagnostic,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { adaptCodeFirstDocumentModelSource } from \"../adapters/code-first-document-model-source-adapter.js\";\nimport type {\n DefinitionProducer,\n ProducedDefinitions,\n} from \"../adapters/producer.js\";\nimport { compareArtifacts, sortedUniqueDiagnostics } from \"../report/status.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport type { DefinitionSourceLoader } from \"../definition-source-loader.js\";\nimport { readStoredDocumentModels } from \"../schema-first/stored-models.js\";\nimport { findUnregisteredDefinitions } from \"./unregistered-definitions.js\";\n\n/**\n * @experimental A package's document models, loaded once and read by both\n * `ph model check` and `ph model inspect`. Experimental while code-first\n * projects are introduced.\n */\nexport type ProjectDefinitions = LoadedDefinitionProject & {\n /** Absolute. No report carries it. */\n readonly packageRoot: string;\n};\n\n/** Code-first sources are authored in normalized coordinates, so they need no relocation. */\nconst adaptSelectedModules: DefinitionProducer = ({ loaded }) => {\n const results = loaded.documentModels.map(({ value, source }) => {\n const result = adaptCodeFirstDocumentModelSource(value, source);\n return {\n artifacts: result.artifacts,\n diagnostics: result.diagnostics.map((diagnostic) =>\n diagnostic.source === undefined\n ? { ...diagnostic, source }\n : diagnostic,\n ),\n };\n });\n return {\n artifacts: results.flatMap(({ artifacts }) => artifacts),\n diagnostics: results.flatMap(({ diagnostics }) => diagnostics),\n relocations: new Map(),\n };\n};\n\n/** The readers a project loads with unless a caller passes its own: code-first modules, then stored specifications. */\nexport const defaultDefinitionProducers: readonly DefinitionProducer[] =\n Object.freeze([adaptSelectedModules, readStoredDocumentModels]);\n\n/** Tool and Node messages can quote the machine path a package lives at. */\nfunction packageRelative(\n diagnostics: readonly DefinitionDiagnostic[],\n packageRoot: string,\n): readonly DefinitionDiagnostic[] {\n let real = packageRoot;\n try {\n real = realpathSync.native(packageRoot);\n } catch {\n // An unreadable root keeps its spelled path only.\n }\n const roots = [...new Set([packageRoot, real])]\n .sort((left, right) => right.length - left.length)\n .flatMap((root) => [pathToFileURL(root).href, root]);\n const rewrite = (text: string) =>\n roots.reduce((result, root) => result.replaceAll(root, \".\"), text);\n return diagnostics.map((diagnostic) => ({\n ...diagnostic,\n message: rewrite(diagnostic.message),\n repair: rewrite(diagnostic.repair),\n ...(diagnostic.expected !== undefined && {\n expected: rewrite(diagnostic.expected),\n }),\n ...(diagnostic.received !== undefined && {\n received: rewrite(diagnostic.received),\n }),\n ...(diagnostic.related !== undefined && {\n related: diagnostic.related.map((location) => ({\n ...location,\n message: rewrite(location.message),\n })),\n }),\n }));\n}\n\n/**\n * @experimental Loads the code-first model directories discovery finds and\n * the package's stored schema-first models, and scans for code-first\n * declarations no entry module reaches. Artifacts and diagnostics are\n * sorted and package relative. `producers` replaces the default readers.\n * `importedFiles` names the absolute paths of every module the loader's\n * import of a discovered specifier evaluated, so reach follows whatever the\n * importer resolved. Experimental while code-first projects are introduced.\n */\nexport async function loadProjectDefinitions(request: {\n readonly loader: DefinitionSourceLoader;\n readonly configFile: string;\n readonly allowMissingConfig?: boolean;\n readonly packageRevision: Sha256Digest;\n readonly signal?: AbortSignal;\n readonly producers?: readonly DefinitionProducer[];\n readonly importedFiles: (specifier: string) => readonly string[];\n}): Promise<ProjectDefinitions> {\n const {\n loader,\n producers = defaultDefinitionProducers,\n importedFiles,\n ...load\n } = request;\n const loaded = await loader.normalizeDefinitionSources(load);\n request.signal?.throwIfAborted();\n const { packageRoot } = loaded;\n const modelsDir = loaded.documentModelsDir;\n const input = {\n ...load,\n loader,\n packageRoot,\n loaded,\n ...(modelsDir !== undefined && { documentModelsDir: modelsDir }),\n };\n const produced: ProducedDefinitions[] = [];\n for (const producer of producers) produced.push(await producer(input));\n request.signal?.throwIfAborted();\n const selectionKnown = !loaded.diagnostics.some(\n ({ phase, severity }) => phase === \"configuration\" && severity === \"error\",\n );\n const artifacts = produced\n .flatMap((result) => result.artifacts)\n .sort(compareArtifacts);\n const scan =\n selectionKnown && modelsDir !== undefined\n ? findUnregisteredDefinitions({\n packageRoot,\n documentModelsDir: modelsDir,\n sources: loaded.sourceSet.sources,\n importedFiles,\n storedUnits: new Set(\n loaded.sourceSet.stored.map(({ specifier }) =>\n specifier.replace(/[^/]+$/, \"\"),\n ),\n ),\n loadedDocumentTypes: new Set([\n ...loaded.documentModels.map(\n ({ value }) => value.documentModel.global.id,\n ),\n ...loaded.diagnostics.flatMap(({ definition }) =>\n definition?.kind === \"document-model\" ? [definition.key] : [],\n ),\n ]),\n })\n : { unregistered: [], diagnostics: [] };\n return {\n packageRoot,\n sourceSet: loaded.sourceSet,\n ...(artifacts.length === 0 && {\n skipReason: \"no-document-models\" as const,\n }),\n artifacts,\n relocations: new Map(\n produced.flatMap(({ relocations }) => [...relocations]),\n ),\n diagnostics: sortedUniqueDiagnostics(\n packageRelative(\n [\n ...loaded.diagnostics,\n ...produced.flatMap(({ diagnostics }) => diagnostics),\n ...scan.diagnostics,\n ],\n packageRoot,\n ),\n ),\n unregistered: scan.unregistered,\n };\n}\n","import type {\n DirectiveUseDefinition,\n EnumTypeDefinition,\n FieldDefinition,\n GraphQLConstValueNode,\n GraphQLDirectiveNode,\n GraphQLInputValueDefinitionNode,\n GraphQLNamedTypeNode,\n GraphQLNameNode,\n GraphQLStringValueNode,\n GraphQLTypeNode,\n GraphQLTypeSystemDefinitionNode,\n InputFieldDefinition,\n JsonValue,\n NamedGraphQLTypeDefinition,\n TypeReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { EMPTY_INPUT_FIELD_NAME } from \"../kernel/primitives.js\";\nimport { blockStringable } from \"../kernel/printer.js\";\n\nexport type Inventory = ReadonlyMap<string, NamedGraphQLTypeDefinition>;\n\nexport const nameNode = (value: string): GraphQLNameNode => ({\n kind: \"Name\",\n value,\n});\n\nexport const namedType = (name: string): GraphQLNamedTypeNode => ({\n kind: \"NamedType\",\n name: nameNode(name),\n});\n\nconst stringValue = (value: string, block = false): GraphQLStringValueNode => ({\n kind: \"StringValue\",\n value,\n block,\n});\n\ntype DescriptionForm = \"printed\" | \"argument-inline\";\n\nfunction description(\n value: string | null,\n form: DescriptionForm = \"printed\",\n): { readonly description?: GraphQLStringValueNode } {\n return value === null\n ? {}\n : {\n description: stringValue(\n value,\n form === \"printed\" && blockStringable(value),\n ),\n };\n}\n\nexport function typeNode(type: TypeReferenceDefinition): GraphQLTypeNode {\n const base =\n type.kind === \"list\"\n ? { kind: \"ListType\" as const, type: typeNode(type.item) }\n : namedType(type.name);\n return type.required ? { kind: \"NonNullType\", type: base } : base;\n}\n\nfunction numberValue(value: number): GraphQLConstValueNode {\n if (!Number.isFinite(value)) {\n throw new TypeError(\n `A GraphQL value must be finite, received ${String(value)}.`,\n );\n }\n const printed = JSON.stringify(value);\n return /[.eE]/.test(printed)\n ? { kind: \"FloatValue\", value: printed }\n : { kind: \"IntValue\", value: printed };\n}\n\nfunction literalValue(value: JsonValue): GraphQLConstValueNode {\n if (value === null) return { kind: \"NullValue\" };\n if (typeof value === \"boolean\") return { kind: \"BooleanValue\", value };\n if (typeof value === \"number\") return numberValue(value);\n if (typeof value === \"string\") return stringValue(value);\n if (Array.isArray(value)) {\n return { kind: \"ListValue\", values: value.map(literalValue) };\n }\n return objectValue(value as Readonly<Record<string, JsonValue>>, (member) =>\n literalValue(member),\n );\n}\n\nfunction objectValue(\n value: Readonly<Record<string, JsonValue>>,\n member: (value: JsonValue, key: string) => GraphQLConstValueNode,\n): GraphQLConstValueNode {\n return {\n kind: \"ObjectValue\",\n fields: Object.entries(value).map(([key, entry]) => ({\n kind: \"ObjectField\",\n name: nameNode(key),\n value: member(entry, key),\n })),\n };\n}\n\nfunction enumMember(definition: EnumTypeDefinition, value: string): boolean {\n return definition.values.some((candidate) => candidate.name === value);\n}\n\nexport function typedValue(\n value: JsonValue,\n type: TypeReferenceDefinition,\n inventory: Inventory,\n): GraphQLConstValueNode {\n if (value === null) return { kind: \"NullValue\" };\n if (type.kind === \"list\") {\n return Array.isArray(value)\n ? {\n kind: \"ListValue\",\n values: (value as readonly JsonValue[]).map((item) =>\n typedValue(item, type.item, inventory),\n ),\n }\n : typedValue(value, type.item, inventory);\n }\n if (type.kind === \"scalar\") return literalValue(value);\n const definition = inventory.get(type.name);\n if (definition?.kind === \"enum\") {\n return typeof value === \"string\" && enumMember(definition, value)\n ? { kind: \"EnumValue\", value }\n : literalValue(value);\n }\n if (\n definition?.kind !== \"input\" ||\n typeof value !== \"object\" ||\n Array.isArray(value)\n ) {\n return literalValue(value);\n }\n const fields = new Map(definition.fields.map((field) => [field.name, field]));\n return objectValue(\n value as Readonly<Record<string, JsonValue>>,\n (member, key) => {\n const field = fields.get(key);\n return field === undefined\n ? literalValue(member)\n : typedValue(member, field.type, inventory);\n },\n );\n}\n\nexport function directiveNodes(\n deprecated: string | null,\n directives: readonly DirectiveUseDefinition[] | undefined,\n): readonly GraphQLDirectiveNode[] {\n const used: GraphQLDirectiveNode[] = (directives ?? []).map((directive) => ({\n kind: \"Directive\",\n name: nameNode(directive.name),\n arguments: directive.arguments.map((argument) => ({\n kind: \"Argument\",\n name: nameNode(argument.name),\n value: literalValue(argument.value),\n })),\n }));\n if (deprecated === null) return used;\n return [\n {\n kind: \"Directive\",\n name: nameNode(\"deprecated\"),\n arguments: [\n {\n kind: \"Argument\",\n name: nameNode(\"reason\"),\n value: stringValue(deprecated),\n },\n ],\n },\n ...used,\n ];\n}\n\nexport function inputValueNode(\n field: InputFieldDefinition,\n inventory: Inventory,\n form: DescriptionForm,\n): GraphQLInputValueDefinitionNode {\n return {\n kind: \"InputValueDefinition\",\n ...description(field.description, form),\n name: nameNode(field.name),\n type: typeNode(field.type),\n ...(Object.hasOwn(field, \"defaultValue\") && {\n defaultValue: typedValue(\n field.defaultValue as JsonValue,\n field.type,\n inventory,\n ),\n }),\n directives: directiveNodes(field.deprecated, field.directives),\n };\n}\n\nconst EMPTY_INPUT_FIELD: GraphQLInputValueDefinitionNode = {\n kind: \"InputValueDefinition\",\n name: nameNode(EMPTY_INPUT_FIELD_NAME),\n type: namedType(\"Boolean\"),\n directives: [],\n};\n\nexport function fieldNodes(\n fields: readonly FieldDefinition[],\n inventory: Inventory,\n) {\n return fields.map((field) => ({\n kind: \"FieldDefinition\" as const,\n ...description(field.description),\n name: nameNode(field.name),\n arguments: (field.args ?? []).map((argument) =>\n inputValueNode(argument, inventory, \"argument-inline\"),\n ),\n type: typeNode(field.type),\n directives: directiveNodes(field.deprecated, field.directives),\n }));\n}\n\nexport function definitionNode(\n definition: NamedGraphQLTypeDefinition,\n inventory: Inventory,\n): GraphQLTypeSystemDefinitionNode {\n const named = {\n ...description(definition.description),\n name: nameNode(definition.name),\n directives: [],\n };\n switch (definition.kind) {\n case \"enum\":\n return {\n kind: \"EnumTypeDefinition\",\n ...named,\n values: definition.values.map((value) => ({\n kind: \"EnumValueDefinition\",\n ...description(value.description),\n name: nameNode(value.name),\n directives: directiveNodes(value.deprecated, value.directives),\n })),\n };\n case \"object\":\n case \"interface\":\n return {\n kind:\n definition.kind === \"object\"\n ? \"ObjectTypeDefinition\"\n : \"InterfaceTypeDefinition\",\n ...named,\n interfaces: (definition.implements ?? []).map(namedType),\n fields: fieldNodes(definition.fields, inventory),\n };\n case \"input\":\n return {\n kind: \"InputObjectTypeDefinition\",\n ...named,\n fields:\n definition.fields.length === 0\n ? [EMPTY_INPUT_FIELD]\n : definition.fields.map((field) =>\n inputValueNode(field, inventory, \"printed\"),\n ),\n };\n case \"union\":\n return {\n kind: \"UnionTypeDefinition\",\n ...named,\n types: definition.members.map(namedType),\n };\n }\n}\n","import type {\n DocumentModelDefinition,\n DocumentModelSpecificationDefinition,\n GraphQLTypeSystemDefinitionNode,\n LocationFreeGraphQLDocumentNode,\n NamedGraphQLTypeDefinition,\n PackageScalarReferenceDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { compareCodeUnits } from \"../kernel/primitives.js\";\nimport { definitionNode, type Inventory, nameNode } from \"./graphql-nodes.js\";\nimport { assignStoredSegments } from \"./segments.js\";\n\ntype GraphQLSegment = {\n readonly root: string;\n readonly document: LocationFreeGraphQLDocumentNode;\n};\n\nexport type DocumentModelGraphQLProjection = {\n readonly graphQLName: string;\n readonly global: GraphQLSegment;\n readonly local: GraphQLSegment | null;\n readonly modules: readonly {\n readonly key: string;\n readonly name: string;\n readonly operations: readonly {\n readonly key: string;\n readonly name: string;\n readonly actionType: string;\n readonly creatorKey: string;\n readonly scope: \"global\" | \"local\";\n readonly input: LocationFreeGraphQLDocumentNode | null;\n }[];\n }[];\n readonly packageScalars: readonly PackageScalarReferenceDefinition[];\n};\n\nfunction isPackageScalar(\n scalar: DocumentModelSpecificationDefinition[\"scalars\"][number],\n): scalar is PackageScalarReferenceDefinition {\n return scalar.implementation.startsWith(\"package#\");\n}\n\n/**\n * Projects a specification into the GraphQL documents its stored SDL\n * segments parse to: `print(segment.document)` equals\n * `print(parse(storedSegment))` for the state schemas and each operation's\n * `schema` that `materialize` stores.\n */\nexport function projectDocumentModelGraphQL(\n definition: DocumentModelDefinition,\n specification: DocumentModelSpecificationDefinition,\n): DocumentModelGraphQLProjection {\n const { types } = specification;\n const inventory: Inventory = new Map(types.map((type) => [type.name, type]));\n const document = (\n definitions: readonly NamedGraphQLTypeDefinition[],\n ): LocationFreeGraphQLDocumentNode => ({\n kind: \"Document\",\n definitions: definitions.map((type) => definitionNode(type, inventory)),\n });\n\n const globalRoot = specification.state.global.root.name;\n const localRoot = specification.state.local.root?.name ?? null;\n const operationKey = (moduleKey: string, key: string) =>\n `${moduleKey}/${key}`;\n const segments = assignStoredSegments({\n types,\n globalRoot,\n localRoot,\n operations: specification.modules.flatMap((module) =>\n module.operations.map((operation) => ({\n key: operationKey(module.key, operation.key),\n input: operation.input,\n })),\n ),\n });\n\n const packageScalars = specification.scalars.filter(isPackageScalar);\n const global = document(segments.global);\n return {\n graphQLName: definition.model.graphQLName,\n global: {\n root: globalRoot,\n document: {\n kind: \"Document\",\n definitions: [\n ...packageScalars\n .map(({ name }) => name)\n .sort(compareCodeUnits)\n .map((name): GraphQLTypeSystemDefinitionNode => ({\n kind: \"ScalarTypeDefinition\",\n name: nameNode(name),\n directives: [],\n })),\n ...global.definitions,\n ],\n },\n },\n local:\n localRoot === null\n ? null\n : { root: localRoot, document: document(segments.local) },\n modules: specification.modules.map((module) => ({\n key: module.key,\n name: module.name,\n operations: module.operations.map((operation) => ({\n key: operation.key,\n name: operation.name ?? operation.actionType,\n actionType: operation.actionType,\n creatorKey: operation.creatorKey,\n scope: operation.scope,\n input:\n operation.input === null\n ? null\n : document(\n segments.operations.get(\n operationKey(module.key, operation.key),\n ) ?? [operation.input],\n ),\n })),\n })),\n packageScalars,\n };\n}\n","import type {\n GraphQLTypeSystemDefinitionNode,\n LocationFreeGraphQLDocumentNode,\n ObjectTypeDefinition,\n SubgraphDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n definitionNode,\n type Inventory,\n nameNode,\n} from \"../compiler/graphql-nodes.js\";\n\ntype TypedSubgraphDefinition = SubgraphDefinition & {\n readonly schemaKind: \"typed\";\n};\n\nexport const ROOT_TYPES = {\n query: \"Query\",\n mutation: \"Mutation\",\n subscription: \"Subscription\",\n} as const;\n\nexport function subgraphRootTypes(\n definition: Pick<TypedSubgraphDefinition, \"entries\">,\n): readonly ObjectTypeDefinition[] {\n return ([\"query\", \"mutation\", \"subscription\"] as const).flatMap((kind) => {\n const fields = definition.entries.flatMap((entry) =>\n entry.kind === kind\n ? [\n {\n key: entry.key,\n name: entry.fieldName,\n description: entry.description,\n deprecated: entry.deprecated,\n args: entry.args,\n type: entry.returns,\n },\n ]\n : [],\n );\n return fields.length === 0\n ? []\n : [\n {\n kind: \"object\" as const,\n name: ROOT_TYPES[kind],\n description: null,\n fields,\n },\n ];\n });\n}\n\n/**\n * @experimental The GraphQL document a subgraph definition serves, without\n * locations, in the definition's print order. A typed definition declares\n * the catalog and project scalars it uses as `scalar` definitions.\n */\nexport function projectSubgraphGraphQL(\n definition: SubgraphDefinition,\n): LocationFreeGraphQLDocumentNode {\n if (definition.schemaKind === \"graphql-ast-compat\") {\n return definition.document;\n }\n const roots = subgraphRootTypes(definition);\n const inventory: Inventory = new Map(\n [...definition.types, ...roots].map((type) => [type.name, type]),\n );\n const scalars = new Set(definition.scalars.map(({ name }) => name));\n return {\n kind: \"Document\",\n definitions: definition.definitionOrder.flatMap(\n (name): GraphQLTypeSystemDefinitionNode[] => {\n if (scalars.has(name)) {\n return [\n {\n kind: \"ScalarTypeDefinition\",\n name: nameNode(name),\n directives: [],\n },\n ];\n }\n const type = inventory.get(name);\n if (type === undefined) {\n throw new TypeError(\n `definitionOrder names ${name}, which the subgraph definition does not declare.`,\n );\n }\n return [definitionNode(type, inventory)];\n },\n ),\n };\n}\n","import { canonicalJson, compareCodeUnits } from \"../../kernel/primitives.js\";\n\n/**\n * What a subgraph claims in the supergraph, as the host's ownership rules\n * read it: each root field as `Query.name`, and each other type by name,\n * mapped to a normalized definition. Two subgraphs conflict on a root field\n * they both claim, and on a type they define differently. Scalars claim\n * nothing: the host declares each scalar once.\n */\nexport type SubgraphClaims = ReadonlyMap<string, string>;\n\n/** The parts of a graphql-js or location-free AST that claims read. */\ntype AstNode = { readonly kind: string; readonly [key: string]: unknown };\n\nconst ROOT_TYPES: ReadonlySet<string> = new Set([\n \"Query\",\n \"Mutation\",\n \"Subscription\",\n]);\n\nconst TYPE_NODE =\n /^(?:Object|Interface|Union|Enum|InputObject)Type(?:Definition|Extension)$/;\n\n/** Member lists whose order does not change what a type defines. */\nconst NAMED_MEMBERS: ReadonlySet<string> = new Set([\n \"fields\",\n \"arguments\",\n \"interfaces\",\n \"values\",\n \"types\",\n]);\n\nconst nameOf = (node: unknown): string | undefined => {\n const name = (node as { name?: { value?: unknown } } | null)?.name?.value;\n return typeof name === \"string\" ? name : undefined;\n};\n\n/**\n * Drops locations, descriptions, the block flag of strings and empty\n * members, and sorts named members, so equal definitions compare equal\n * whichever AST printed them.\n */\nfunction normalized(value: unknown, key?: string): unknown {\n if (Array.isArray(value)) {\n const items = value.map((item) => normalized(item));\n return key !== undefined && NAMED_MEMBERS.has(key)\n ? items.sort((left, right) =>\n compareCodeUnits(nameOf(left) ?? \"\", nameOf(right) ?? \"\"),\n )\n : items;\n }\n if (value === null || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(\n ([member, inner]) =>\n member !== \"loc\" &&\n member !== \"description\" &&\n member !== \"block\" &&\n inner !== undefined &&\n !(Array.isArray(inner) && inner.length === 0),\n )\n .map(([member, inner]) => [member, normalized(inner, member)]),\n );\n}\n\nconst normalizedText = (node: unknown) => canonicalJson(normalized(node));\n\nfunction merged(nodes: readonly AstNode[]): AstNode | undefined {\n if (nodes.length === 1) return nodes[0];\n const definitions = nodes.filter(({ kind }) => kind.endsWith(\"Definition\"));\n if (definitions.length !== 1) return undefined;\n const [definition] = definitions;\n const extensionKind = definition.kind.replace(/Definition$/, \"Extension\");\n const result: Record<string, unknown> = { ...definition };\n for (const node of nodes) {\n if (node === definition) continue;\n if (node.kind !== extensionKind) return undefined;\n for (const member of [\n \"fields\",\n \"interfaces\",\n \"values\",\n \"types\",\n \"directives\",\n ]) {\n const extra = node[member];\n if (Array.isArray(extra)) {\n result[member] = [\n ...((result[member] as readonly unknown[] | undefined) ?? []),\n ...(extra as readonly unknown[]),\n ];\n }\n }\n }\n return result as AstNode;\n}\n\nexport function subgraphClaims(document: {\n readonly definitions: readonly object[];\n}): SubgraphClaims {\n const types = new Map<string, AstNode[]>();\n const claims = new Map<string, string>();\n for (const definition of document.definitions as readonly AstNode[]) {\n const name = nameOf(definition);\n if (name === undefined || !TYPE_NODE.test(definition.kind)) continue;\n if (ROOT_TYPES.has(name)) {\n const fields = definition.fields;\n if (!Array.isArray(fields)) continue;\n for (const field of fields as readonly AstNode[]) {\n const claim = `${name}.${nameOf(field)}`;\n const text = normalizedText(field);\n const previous = claims.get(claim);\n claims.set(\n claim,\n previous === undefined ? text : `${previous}\\n${text}`,\n );\n }\n continue;\n }\n types.set(name, [...(types.get(name) ?? []), definition]);\n }\n for (const [name, nodes] of types) {\n const node = merged(nodes);\n claims.set(\n name,\n node === undefined\n ? nodes.map(normalizedText).sort(compareCodeUnits).join(\"\\n\")\n : normalizedText(node),\n );\n }\n return claims;\n}\n\nexport const isRootFieldClaim = (claim: string) => claim.includes(\".\");\n\n/** The claims `later` loses to `earlier`: every shared root field, and every type defined differently. */\nexport function conflictingClaims(\n earlier: SubgraphClaims,\n later: SubgraphClaims,\n): readonly string[] {\n return [...later]\n .filter(([claim, text]) => {\n const owned = earlier.get(claim);\n return owned !== undefined && (isRootFieldClaim(claim) || owned !== text);\n })\n .map(([claim]) => claim);\n}\n","import { defineDiagnosticCatalog } from \"../../kernel/diagnostics.js\";\nimport { toolingDiagnostics } from \"../diagnostic-codes.js\";\n\nexport const subgraphToolingDiagnostics = defineDiagnosticCatalog(\n {\n \"PH-SG-DESCRIBE-FAILED\": {\n severity: \"error\",\n phase: \"import\",\n meaning:\n \"A code-first subgraph class threw from describe() or returned something that is not a description\",\n },\n \"PH-SG-PROTOCOL-UNSUPPORTED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A subgraph class carries a protocol version this release does not read, or a malformed protocol\",\n },\n \"PH-SG-NAME-MISSING\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first subgraph class declares no subgraphName and no other export extends it\",\n },\n \"PH-SG-DUPLICATE-NAME\": {\n severity: \"error\",\n phase: \"package\",\n meaning: \"Two code-first subgraphs of one package share a name\",\n },\n \"PH-SG-TYPE-CONFLICT\": {\n severity: \"error\",\n phase: \"composition\",\n meaning:\n \"Two code-first subgraphs serve one root field, or one type name with different definitions\",\n },\n \"PH-SG-DOCUMENT-MODEL-TYPE-CONFLICT\": {\n severity: \"error\",\n phase: \"composition\",\n meaning:\n \"A code-first subgraph declares a type that a document model of the package generates\",\n },\n \"PH-SG-NAME-RESERVED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first subgraph has the name of a built-in subgraph or of a document model's subgraph, so a host refuses it\",\n },\n \"PH-SG-HOST-TYPE-CONFLICT\": {\n severity: \"error\",\n phase: \"composition\",\n meaning:\n \"A code-first subgraph declares a type or root field that a host's built-in subgraphs or base document models own, so a host refuses it\",\n },\n \"PH-SG-SCALAR-UNREGISTERED\": {\n severity: \"error\",\n phase: \"package\",\n meaning:\n \"A code-first subgraph uses a package scalar that scalars/index.ts does not export under its name\",\n },\n \"PH-SG-SCHEMA-FIRST-CONFLICT\": {\n severity: \"warning\",\n phase: \"composition\",\n meaning:\n \"A code-first subgraph and a schema-first subgraph claim one name, root field or differently defined type\",\n },\n \"PH-SG-SCHEMA-FIRST-UNCHECKED\": {\n severity: \"warning\",\n phase: \"composition\",\n meaning:\n \"The SDL of a schema-first subgraph could not be read from its source text, so its conflicts were not checked\",\n },\n },\n toolingDiagnostics,\n);\n\nexport type SubgraphToolingDiagnosticCode =\n keyof typeof subgraphToolingDiagnostics.codes;\n","import type {\n DefinitionDiagnostic,\n DefinitionSource,\n} from \"@powerhousedao/shared/document-model\";\nimport { loadGraphQL } from \"../../graphql/parse-schema.js\";\nimport { projectSubgraphGraphQL } from \"../../../subgraph/projection.js\";\nimport {\n conflictingClaims,\n isRootFieldClaim,\n type SubgraphClaims,\n subgraphClaims,\n} from \"../claims.js\";\nimport { subgraphToolingDiagnostics } from \"../diagnostic-codes.js\";\nimport type { CodeFirstSubgraph } from \"../read.js\";\n\n/**\n * @experimental The source text of one schema-first subgraph, as ph-cli\n * finds it next to the subgraph's class. Tooling never imports or\n * constructs a schema-first class, so its SDL is read from text.\n */\nexport type SchemaFirstSubgraphSource = {\n /** The subgraph's directory, `./subgraphs/<dir>/`. */\n readonly unit: `./${string}`;\n /** The name the class assigns, when its text shows a literal one. */\n readonly name: string | null;\n /** The file the SDL is read from. */\n readonly source: DefinitionSource;\n /** `graphql` for an SDL file, `typescript` for a module holding gql templates. */\n readonly language: \"graphql\" | \"typescript\";\n /** `null` when the subgraph has no file to read. */\n readonly text: string | null;\n};\n\ntype SchemaFirstSdl =\n | {\n readonly kind: \"read\";\n readonly claims: SubgraphClaims;\n }\n | { readonly kind: \"unchecked\"; readonly reason: string };\n\nconst TEMPLATE = /\\b(?:gql|graphql)\\s*`((?:\\\\[\\s\\S]|[^`\\\\])*)`/g;\nconst RELATIVE_IMPORT = /\\bfrom\\s*[\"']\\.\\.?\\//;\n\nfunction sdlText(\n source: SchemaFirstSubgraphSource,\n): { readonly sdl: string } | { readonly reason: string } {\n if (source.text === null) {\n return {\n reason: \"the subgraph has no schema.graphql, schema.ts or index.ts\",\n };\n }\n if (source.language === \"graphql\") return { sdl: source.text };\n const templates = [...source.text.matchAll(TEMPLATE)].map(\n (match) => match[1],\n );\n if (templates.some((template) => template.includes(\"${\"))) {\n return { reason: \"its gql template interpolates values\" };\n }\n if (templates.length === 0) {\n return {\n reason: RELATIVE_IMPORT.test(source.text)\n ? \"its SDL is imported from another module\"\n : \"it holds no gql template\",\n };\n }\n return { sdl: templates.join(\"\\n\") };\n}\n\nfunction readSchemaFirstSdl(source: SchemaFirstSubgraphSource): SchemaFirstSdl {\n const text = sdlText(source);\n if (\"reason\" in text) return { kind: \"unchecked\", reason: text.reason };\n let graphql: ReturnType<typeof loadGraphQL>;\n try {\n graphql = loadGraphQL();\n } catch (error) {\n return {\n kind: \"unchecked\",\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n try {\n const document = graphql.parse(text.sdl, { noLocation: true });\n return { kind: \"read\", claims: subgraphClaims(document) };\n } catch (error) {\n return {\n kind: \"unchecked\",\n reason: `its SDL does not parse: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\nfunction describeClaim(claim: string): string {\n return isRootFieldClaim(claim) ? `root field ${claim}` : `type ${claim}`;\n}\n\n/**\n * Advisory warnings for a project with code-first and schema-first\n * subgraphs: a shared name, a shared root field, or a type defined\n * differently. The host keeps deciding at runtime; nothing here is an\n * error. SDL that cannot be read from text is reported as not checked.\n */\nexport function schemaFirstSdlConflicts(input: {\n readonly codeFirst: readonly CodeFirstSubgraph[];\n readonly schemaFirst: readonly SchemaFirstSubgraphSource[];\n}): readonly DefinitionDiagnostic[] {\n if (input.codeFirst.length === 0) return [];\n const codeFirst = input.codeFirst.map((subgraph) => ({\n subgraph,\n claims: subgraphClaims(projectSubgraphGraphQL(subgraph.definition)),\n }));\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const schemaFirstSubgraph of input.schemaFirst) {\n const named = codeFirst.find(\n ({ subgraph }) =>\n schemaFirstSubgraph.name !== null &&\n subgraph.name === schemaFirstSubgraph.name,\n );\n if (named !== undefined) {\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-SCHEMA-FIRST-CONFLICT\",\n source: schemaFirstSubgraph.source,\n definition: { kind: \"subgraph\", key: named.subgraph.name },\n path: [],\n message: `The schema-first subgraph in ${schemaFirstSubgraph.unit} and a code-first subgraph are both named ${named.subgraph.name}; a host serves one of them.`,\n expected: \"one subgraph per name\",\n received: named.subgraph.name,\n repair: \"Rename one of the subgraphs.\",\n related: [\n {\n source: named.subgraph.source,\n path: [],\n message: \"The code-first subgraph with this name.\",\n },\n ],\n }),\n );\n }\n const read = readSchemaFirstSdl(schemaFirstSubgraph);\n if (read.kind === \"unchecked\") {\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-SCHEMA-FIRST-UNCHECKED\",\n source: schemaFirstSubgraph.source,\n path: [],\n message: `The schema-first subgraph in ${schemaFirstSubgraph.unit} was not checked against the code-first subgraphs: ${read.reason}.`,\n expected:\n \"SDL in a schema.graphql file or a gql template without interpolation\",\n received: read.reason,\n repair:\n \"Nothing is required. To have its conflicts checked, keep its SDL in one gql template or a schema.graphql file.\",\n }),\n );\n continue;\n }\n for (const { subgraph, claims } of codeFirst) {\n for (const claim of conflictingClaims(read.claims, claims)) {\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-SCHEMA-FIRST-CONFLICT\",\n source: subgraph.source,\n definition: { kind: \"subgraph\", key: subgraph.name },\n path: [],\n message: `Code-first subgraph ${subgraph.name} and the schema-first subgraph in ${schemaFirstSubgraph.unit} both claim ${describeClaim(claim)}; the host serves the claim from one of them only.`,\n expected: isRootFieldClaim(claim)\n ? \"each root field served by one subgraph\"\n : \"one definition per type name\",\n received: claim,\n repair: isRootFieldClaim(claim)\n ? \"Rename the root field in one of the subgraphs.\"\n : \"Rename the type in one subgraph, or define it identically in both.\",\n related: [\n {\n source: schemaFirstSubgraph.source,\n path: [],\n message: `The schema-first subgraph claims ${claim} here.`,\n },\n ],\n }),\n );\n }\n }\n }\n return diagnostics;\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionPath,\n} from \"@powerhousedao/shared/document-model\";\nimport { projectDocumentModelGraphQL } from \"../../compiler/graphql-projection.js\";\nimport { deriveDocumentModelNames } from \"../../compiler/naming.js\";\nimport {\n projectSubgraphGraphQL,\n ROOT_TYPES,\n} from \"../../subgraph/projection.js\";\nimport type { NormalizedDocumentModelArtifact } from \"../adapters/types.js\";\nimport type { DefinitionCheck } from \"../check/types.js\";\nimport { servedSpecification } from \"../report/served-specification.js\";\nimport type { DefinitionCheckInput } from \"../report/types.js\";\nimport {\n conflictingClaims,\n isRootFieldClaim,\n subgraphClaims,\n} from \"./claims.js\";\nimport { subgraphToolingDiagnostics } from \"./diagnostic-codes.js\";\nimport type { SubgraphCheckInput } from \"./input.js\";\nimport type { CodeFirstSubgraph } from \"./read.js\";\nimport { schemaFirstSdlConflicts } from \"./schema-first/sdl-conflicts.js\";\n\n/** @experimental The input of {@link subgraphChecks}. */\nexport type SubgraphChecksInput = DefinitionCheckInput & {\n readonly subgraphs: SubgraphCheckInput;\n};\n\ntype SubgraphCheck = DefinitionCheck<SubgraphChecksInput>;\n\nfunction claimPath(subgraph: CodeFirstSubgraph, claim: string): DefinitionPath {\n const { definition } = subgraph;\n if (isRootFieldClaim(claim)) {\n const index = definition.entries.findIndex(\n (entry) =>\n (entry.kind === \"query\" ||\n entry.kind === \"mutation\" ||\n entry.kind === \"subscription\") &&\n `${ROOT_TYPES[entry.kind]}.${entry.fieldName}` === claim,\n );\n return index === -1 ? [] : [\"entries\", index];\n }\n const index = definition.types.findIndex(({ name }) => name === claim);\n return index === -1 ? [] : [\"types\", index];\n}\n\nconst descriptionsCheck: SubgraphCheck = {\n name: \"subgraph-descriptions\",\n run: ({ subgraphs }) => subgraphs.diagnostics,\n};\n\nconst namesCheck: SubgraphCheck = {\n name: \"subgraph-names\",\n run: ({ subgraphs }) => {\n const first = new Map<string, CodeFirstSubgraph>();\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const subgraph of subgraphs.codeFirst) {\n const known = first.get(subgraph.name);\n if (known === undefined) {\n first.set(subgraph.name, subgraph);\n continue;\n }\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-DUPLICATE-NAME\",\n source: subgraph.source,\n definition: { kind: \"subgraph\", key: subgraph.name },\n path: [\"name\"],\n message: `Two code-first subgraphs are named ${subgraph.name}; a host serves only one of them.`,\n expected: \"one subgraph per name\",\n received: subgraph.name,\n repair: \"Give each subgraph class its own subgraphName.\",\n related: [\n {\n source: known.source,\n path: [\"name\"],\n message: `The other subgraph named ${subgraph.name}.`,\n },\n ],\n }),\n );\n }\n return diagnostics;\n },\n};\n\nconst typeConflictsCheck: SubgraphCheck = {\n name: \"subgraph-type-conflicts\",\n run: ({ subgraphs }) => {\n const claimed = subgraphs.codeFirst.map((subgraph) => ({\n subgraph,\n claims: subgraphClaims(projectSubgraphGraphQL(subgraph.definition)),\n }));\n const diagnostics: DefinitionDiagnostic[] = [];\n claimed.forEach(({ subgraph, claims }, index) => {\n for (const earlier of claimed.slice(0, index)) {\n for (const claim of conflictingClaims(earlier.claims, claims)) {\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-TYPE-CONFLICT\",\n source: subgraph.source,\n definition: { kind: \"subgraph\", key: subgraph.name },\n path: claimPath(subgraph, claim),\n message: isRootFieldClaim(claim)\n ? `Code-first subgraphs ${earlier.subgraph.name} and ${subgraph.name} both serve root field ${claim}.`\n : `Code-first subgraphs ${earlier.subgraph.name} and ${subgraph.name} define type ${claim} differently.`,\n expected: isRootFieldClaim(claim)\n ? \"each root field served by one subgraph\"\n : \"one definition per type name\",\n received: claim,\n repair: isRootFieldClaim(claim)\n ? \"Rename the root field in one of the subgraphs.\"\n : \"Share one ph descriptor for the type between both subgraphs, or rename one of them.\",\n related: [\n {\n source: earlier.subgraph.source,\n path: claimPath(earlier.subgraph, claim),\n message: `${earlier.subgraph.name} claims ${claim} here.`,\n },\n ],\n }),\n );\n }\n }\n });\n return diagnostics;\n },\n};\n\n/**\n * The names a host generates for a model's GraphQL types: the document type\n * under the model's PascalCase name, and each state output type under\n * `<Name>_<Type>`. Mirrors reactor-api's generated schema.\n */\nfunction generatedTypeNames(\n artifact: NormalizedDocumentModelArtifact,\n): readonly string[] {\n const served = servedSpecification(artifact);\n if (served === undefined) return [];\n const { model } = artifact.definition;\n // The host names a model's types after its name, not its graphQLName.\n const prefix = deriveDocumentModelNames({\n id: model.documentType,\n name: model.name.replaceAll(\"/\", \" \"),\n }).graphQLName;\n let projection: ReturnType<typeof projectDocumentModelGraphQL>;\n try {\n projection = projectDocumentModelGraphQL(\n artifact.definition,\n served.specification,\n );\n } catch {\n // A model the compiler cannot project fails its own checks.\n return [prefix];\n }\n const stateTypes = [\n ...projection.global.document.definitions,\n ...(projection.local?.document.definitions ?? []),\n ].flatMap((node) =>\n node.kind === \"ObjectTypeDefinition\" ||\n node.kind === \"InterfaceTypeDefinition\" ||\n node.kind === \"UnionTypeDefinition\" ||\n node.kind === \"EnumTypeDefinition\"\n ? [`${prefix}_${node.name.value}`]\n : [],\n );\n return [prefix, ...stateTypes];\n}\n\nconst documentModelTypesCheck: SubgraphCheck = {\n name: \"subgraph-document-model-types\",\n run: ({ subgraphs, artifacts }) => {\n if (subgraphs.codeFirst.length === 0) return [];\n const owners = new Map<string, NormalizedDocumentModelArtifact>();\n for (const artifact of artifacts) {\n for (const name of generatedTypeNames(artifact)) {\n if (!owners.has(name)) owners.set(name, artifact);\n }\n }\n return subgraphs.codeFirst.flatMap((subgraph) =>\n subgraph.definition.types.flatMap((type, index) => {\n const owner = owners.get(type.name);\n if (owner === undefined) return [];\n return [\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-DOCUMENT-MODEL-TYPE-CONFLICT\",\n source: subgraph.source,\n definition: { kind: \"subgraph\", key: subgraph.name },\n path: [\"types\", index],\n message: `Code-first subgraph ${subgraph.name} declares type ${type.name}, which document model ${owner.documentType} generates; a host refuses the subgraph.`,\n expected: \"a type name no document model of the package generates\",\n received: type.name,\n repair: `Rename the subgraph's ${type.name}.`,\n related: [\n {\n source: owner.source,\n path: [],\n message: `${owner.documentType} generates ${type.name}.`,\n },\n ],\n }),\n ];\n }),\n );\n },\n};\n\nconst packageScalarsCheck: SubgraphCheck = {\n name: \"subgraph-package-scalars\",\n run: ({ subgraphs }) => {\n const exported = subgraphs.packageScalars;\n if (exported === undefined) return [];\n return subgraphs.codeFirst.flatMap((subgraph) =>\n subgraph.definition.scalars.flatMap((scalar, index) =>\n scalar.implementation.startsWith(\"package#\") &&\n !exported.includes(scalar.name)\n ? [\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-SCALAR-UNREGISTERED\",\n source: subgraph.source,\n definition: { kind: \"subgraph\", key: subgraph.name },\n path: [\"scalars\", index],\n message: `Code-first subgraph ${subgraph.name} uses package scalar ${scalar.name}, which scalars/index.ts does not export; a host cannot register it.`,\n expected:\n exported.length === 0\n ? \"a scalars/index.ts export of the scalar\"\n : exported.join(\", \"),\n received: scalar.name,\n repair: `Export ${scalar.name} from scalars/index.ts under its own name: export const ${scalar.name} = defineScalar({ name: \"${scalar.name}\", ... }).`,\n }),\n ]\n : [],\n ),\n );\n },\n};\n\nconst NAME_HOLDER = {\n core: \"a built-in subgraph\",\n \"document model\": \"a document model's subgraph\",\n} as const;\n\nconst hostAdmissionCheck: SubgraphCheck = {\n name: \"subgraph-host-admission\",\n run: ({ subgraphs, artifacts }) => {\n if (subgraphs.hostConflicts.length === 0) return [];\n // PH-SG-DOCUMENT-MODEL-TYPE-CONFLICT already names these.\n const generated = new Set(artifacts.flatMap(generatedTypeNames));\n return subgraphs.codeFirst.flatMap((subgraph) => {\n const conflict = subgraphs.hostConflicts.find(\n (candidate) => candidate.subgraph === subgraph.name,\n );\n if (conflict === undefined) return [];\n const definition = { kind: \"subgraph\", key: subgraph.name } as const;\n return [\n ...(conflict.nameHeldBy === undefined\n ? []\n : [\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-NAME-RESERVED\",\n source: subgraph.source,\n definition,\n path: [],\n message: `Code-first subgraph ${subgraph.name} has the name of ${NAME_HOLDER[conflict.nameHeldBy]}; a host refuses the subgraph.`,\n expected:\n \"a subgraph name no built-in or document-model subgraph uses\",\n received: subgraph.name,\n repair: `Rename the subgraph's static subgraphName, for example to \"${subgraph.name}-api\".`,\n }),\n ]),\n ...conflict.claims\n .filter(({ claim }) => !generated.has(claim))\n .map(({ claim, owner }) =>\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-HOST-TYPE-CONFLICT\",\n source: subgraph.source,\n definition,\n path: claimPath(subgraph, claim),\n message: `Code-first subgraph ${subgraph.name} declares ${claim}, which the host's ${owner} subgraph owns; a host leaves the subgraph out.`,\n expected: `a name the host's ${owner} subgraph does not own`,\n received: claim,\n repair: `Rename ${claim} in the subgraph's schema.`,\n }),\n ),\n ];\n });\n },\n};\n\nconst schemaFirstSdlCheck: SubgraphCheck = {\n name: \"subgraph-schema-first-sdl\",\n run: ({ subgraphs }) => schemaFirstSdlConflicts(subgraphs),\n};\n\n/**\n * @experimental The checks `ph model check` adds when a project has a\n * code-first subgraph. A caller registers them with\n * `[...documentModelChecks, ...subgraphChecks]` and a\n * {@link SubgraphChecksInput}.\n */\nexport const subgraphChecks: readonly SubgraphCheck[] = Object.freeze([\n descriptionsCheck,\n namesCheck,\n typeConflictsCheck,\n documentModelTypesCheck,\n packageScalarsCheck,\n hostAdmissionCheck,\n schemaFirstSdlCheck,\n]);\n","import type {\n DefinitionCheckReport,\n DefinitionDiagnostic,\n} from \"@powerhousedao/shared/document-model\";\nimport { isScalarDefinition } from \"../../../scalars/types.js\";\nimport { canonicalDigest, compareCodeUnits } from \"../../kernel/primitives.js\";\nimport { subgraphToolingDiagnostics } from \"./diagnostic-codes.js\";\nimport type { CodeFirstSubgraph, SubgraphDefinitions } from \"./read.js\";\nimport type { SchemaFirstSubgraphSource } from \"./schema-first/sdl-conflicts.js\";\n\n/**\n * @experimental Everything the subgraph checks read: the code-first\n * subgraphs as their classes describe them, the text of the schema-first\n * ones, and the scalars the package exports.\n */\nexport type SubgraphCheckInput = {\n readonly codeFirst: readonly CodeFirstSubgraph[];\n readonly schemaFirst: readonly SchemaFirstSubgraphSource[];\n /**\n * The scalar names `scalars/index.ts` exports under their own name, sorted.\n * `undefined` when it was not read, which skips the scalar check.\n */\n readonly packageScalars: readonly string[] | undefined;\n /** Import, protocol and describe problems, and each description's own diagnostics. */\n readonly diagnostics: readonly DefinitionDiagnostic[];\n /** What a host's admission does with each code-first subgraph, as the caller replayed it; empty when it did not. */\n readonly hostConflicts: readonly SubgraphHostConflict[];\n};\n\n/**\n * @experimental A code-first subgraph a host would refuse or leave out, from\n * a replay of the host's admission: `nameHeldBy` when a built-in subgraph or\n * a document model's subgraph holds its name, and `claims` for the types and\n * root fields other subgraphs own, with their owners.\n */\nexport type SubgraphHostConflict = {\n readonly subgraph: string;\n readonly nameHeldBy?: \"core\" | \"document model\";\n readonly claims: readonly {\n readonly claim: string;\n readonly owner: string;\n }[];\n};\n\n/** @experimental A code-first subgraph's entry in the check report. */\nexport type SubgraphInventoryEntry =\n DefinitionCheckReport[\"definitions\"][number];\n\n/** A host registers a package scalar by the export bound under the scalar's own name. */\nfunction exportedScalarNames(scalars: object): readonly string[] {\n return Object.entries(scalars)\n .flatMap(([exportName, value]) =>\n isScalarDefinition(value) && value.name === exportName\n ? [exportName]\n : [],\n )\n .sort(compareCodeUnits);\n}\n\n/** @experimental A package module the caller could not import, and why, in package-relative words. */\nexport type SubgraphImportFailure = {\n readonly specifier: `./${string}`;\n readonly reason: string;\n};\n\nfunction importFailed({\n specifier,\n reason,\n}: SubgraphImportFailure): DefinitionDiagnostic {\n return subgraphToolingDiagnostics.create({\n code: \"PH-IMPORT-FAILED\",\n source: { specifier },\n path: [],\n message: `${specifier} could not be imported, so the subgraph checks that read it did not run.`,\n expected: \"an importable TypeScript module\",\n received: reason,\n repair: \"Fix this module or one of its imports, then check again.\",\n });\n}\n\n/**\n * @experimental Builds the subgraph check input and the inventory entries\n * once, for the check, inspection and release callers to share. `scalars`\n * is the namespace of `scalars/index.ts`: `null` when the package has none,\n * absent when the caller did not read it. `importFailures` names the\n * modules the caller could not import. `hostConflicts` is the caller's replay\n * of a host's admission of the code-first subgraphs.\n */\nexport function subgraphCheckInput(request: {\n readonly definitions: SubgraphDefinitions;\n readonly schemaFirst?: readonly SchemaFirstSubgraphSource[];\n readonly scalars?: object | null;\n readonly importFailures?: readonly SubgraphImportFailure[];\n readonly hostConflicts?: readonly SubgraphHostConflict[];\n}): {\n readonly input: SubgraphCheckInput;\n readonly inventory: readonly SubgraphInventoryEntry[];\n} {\n const { definitions, scalars } = request;\n return {\n input: {\n codeFirst: definitions.subgraphs,\n schemaFirst: request.schemaFirst ?? [],\n packageScalars:\n scalars === undefined\n ? undefined\n : scalars === null\n ? []\n : exportedScalarNames(scalars),\n diagnostics: [\n ...(request.importFailures ?? []).map(importFailed),\n ...definitions.diagnostics,\n ],\n hostConflicts: request.hostConflicts ?? [],\n },\n inventory: definitions.subgraphs.map(({ name, source, definition }) => ({\n kind: \"subgraph\",\n key: name,\n digest: canonicalDigest(definition),\n source,\n })),\n };\n}\n","import type {\n DefinitionSource,\n Sha256Digest,\n} from \"@powerhousedao/shared/document-model\";\nimport { canonicalDigest } from \"../../kernel/primitives.js\";\nimport { ROOT_TYPES } from \"../../subgraph/projection.js\";\nimport type { DefinitionInspectionReport } from \"../inspect/types.js\";\nimport { definitionStatus, sortedUniqueDiagnostics } from \"../report/status.js\";\nimport type { LoadedDefinitionProject } from \"../report/types.js\";\nimport type { SubgraphCheckInput } from \"./input.js\";\n\n/** @experimental One subgraph, as `ph model inspect` prints it. */\nexport type SubgraphInspection =\n | {\n readonly style: \"code-first\";\n readonly name: string;\n readonly source: DefinitionSource;\n readonly digest: Sha256Digest;\n readonly hasSubscriptions: boolean;\n /** Schema coordinates of the entries, in entry order: `Query.x`, `Type.field`, or the abstract type a resolveType serves. */\n readonly entries: readonly string[];\n readonly types: readonly string[];\n readonly scalars: readonly {\n readonly name: string;\n readonly implementation: string;\n }[];\n }\n | {\n readonly style: \"schema-first\";\n readonly name: string | null;\n readonly source: DefinitionSource;\n };\n\n/** @experimental An inspection report with the project's subgraphs. */\nexport type SubgraphInspectionReport = DefinitionInspectionReport & {\n readonly subgraphs: readonly SubgraphInspection[];\n};\n\nfunction coordinates(\n entries: SubgraphCheckInput[\"codeFirst\"][number][\"definition\"][\"entries\"],\n): readonly string[] {\n return entries.map((entry) => {\n switch (entry.kind) {\n case \"query\":\n case \"mutation\":\n case \"subscription\":\n return `${ROOT_TYPES[entry.kind]}.${entry.fieldName}`;\n case \"computed-field\":\n return `${entry.typeName}.${entry.fieldName}`;\n case \"resolve-type\":\n case \"is-type-of\":\n return entry.typeName;\n }\n });\n}\n\n/**\n * @experimental Adds the project's subgraphs to an inspection report: a\n * `subgraphs` section, the subgraph diagnostics, and a status that counts\n * them. A project whose only definitions are subgraphs is not skipped.\n */\nexport function withSubgraphInspection(\n project: LoadedDefinitionProject,\n report: DefinitionInspectionReport,\n subgraphs: SubgraphCheckInput,\n): SubgraphInspectionReport {\n const diagnostics = sortedUniqueDiagnostics([\n ...report.diagnostics,\n ...subgraphs.diagnostics,\n ]);\n return {\n ...report,\n status: definitionStatus({\n ...(project.skipReason !== undefined && {\n skipReason: project.skipReason,\n }),\n definitions: [...project.artifacts, ...subgraphs.codeFirst],\n diagnostics,\n }),\n diagnostics,\n subgraphs: [\n ...subgraphs.codeFirst.map(\n ({ name, source, definition }): SubgraphInspection => ({\n style: \"code-first\",\n name,\n source,\n digest: canonicalDigest(definition),\n hasSubscriptions: definition.hasSubscriptions,\n entries: coordinates(definition.entries),\n types: definition.types.map((type) => type.name),\n scalars: definition.scalars.map(({ name, implementation }) => ({\n name,\n implementation,\n })),\n }),\n ),\n ...subgraphs.schemaFirst.map(({ name, source }): SubgraphInspection => ({\n style: \"schema-first\",\n name,\n source,\n })),\n ],\n };\n}\n","import type {\n DefinitionDiagnostic,\n SubgraphDefinition,\n} from \"@powerhousedao/shared/document-model\";\n\n/**\n * @experimental The static member that marks a code-first subgraph class.\n * `Symbol.for` makes it the same key in every copy of the package; the\n * protocol's `version` says which contract the class speaks.\n */\nexport const SUBGRAPH_PROTOCOL: unique symbol = Symbol.for(\n \"powerhouse.subgraph.protocol\",\n);\n\n/**\n * @experimental A code-first class's description. `name` is absent on a\n * base class that declares no `subgraphName`.\n */\nexport type SubgraphDescription = {\n readonly name?: string;\n readonly definition?: SubgraphDefinition;\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\n/**\n * @experimental The contract a code-first subgraph class exposes under\n * `SUBGRAPH_PROTOCOL`. Both methods run in the copy that defined the class.\n */\nexport type SubgraphProtocol = {\n readonly version: 1;\n describe(): SubgraphDescription;\n validate(\n instance: unknown,\n ): { readonly ok: true } | { readonly ok: false; readonly message: string };\n};\n\n/**\n * @experimental How a host treats a subgraph export. `unsupported` covers a\n * protocol of another version and a malformed one, and carries the version\n * it read.\n */\nexport type SubgraphProtocolRead =\n | { readonly kind: \"schema-first\" }\n | { readonly kind: \"code-first\"; readonly protocol: SubgraphProtocol }\n | { readonly kind: \"unsupported\"; readonly version: unknown };\n\n/**\n * @experimental Reads the protocol of a subgraph export. It reads only the\n * static `SUBGRAPH_PROTOCOL` member of a function: it never constructs the\n * class or calls the protocol.\n */\nexport function readSubgraphProtocol(value: unknown): SubgraphProtocolRead {\n if (typeof value !== \"function\") return { kind: \"schema-first\" };\n const protocol: unknown = (value as { [SUBGRAPH_PROTOCOL]?: unknown })[\n SUBGRAPH_PROTOCOL\n ];\n if (protocol === undefined) return { kind: \"schema-first\" };\n if (protocol === null || typeof protocol !== \"object\") {\n return { kind: \"unsupported\", version: undefined };\n }\n const candidate = protocol as Partial<\n Record<keyof SubgraphProtocol, unknown>\n >;\n if (\n candidate.version === 1 &&\n typeof candidate.describe === \"function\" &&\n typeof candidate.validate === \"function\"\n ) {\n return { kind: \"code-first\", protocol: protocol as SubgraphProtocol };\n }\n return { kind: \"unsupported\", version: candidate.version };\n}\n","import type {\n DefinitionDiagnostic,\n DefinitionSource,\n SubgraphDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport { describeReceived } from \"../../kernel/diagnostics.js\";\nimport {\n readSubgraphProtocol,\n type SubgraphDescription,\n type SubgraphProtocol,\n type SubgraphProtocolRead,\n} from \"../../subgraph/protocol.js\";\nimport { subgraphToolingDiagnostics } from \"./diagnostic-codes.js\";\n\n/** @experimental The definition a code-first class's `describe()` compiled. */\nexport type TypedSubgraphDefinition = Extract<\n SubgraphDefinition,\n { readonly schemaKind: \"typed\" }\n>;\n\n/** @experimental A code-first subgraph whose description compiled. */\nexport type CodeFirstSubgraph = {\n readonly name: string;\n readonly source: DefinitionSource;\n readonly definition: TypedSubgraphDefinition;\n};\n\n/** @experimental What {@link readSubgraphDefinitions} found in a module. */\nexport type SubgraphDefinitions = {\n /** In export order: the module's own order, or name order for an ES module namespace. */\n readonly subgraphs: readonly CodeFirstSubgraph[];\n /** Protocol, describe and name problems, and each description's own diagnostics. */\n readonly diagnostics: readonly DefinitionDiagnostic[];\n};\n\nconst DEFAULT_SPECIFIER = \"./subgraphs/index.ts\";\n\ntype Candidate = {\n readonly value: (...args: never[]) => unknown;\n readonly exportPath: readonly string[];\n};\n\n/** An ES module namespace lists its exports by name; Vite's runner lists them in statement order. */\nfunction entriesByName(\n record: object,\n): readonly (readonly [string, unknown])[] {\n const keys = Object.keys(record);\n if (Object.prototype.toString.call(record) === \"[object Module]\") {\n keys.sort();\n }\n return keys.map((key) => [key, (record as Record<string, unknown>)[key]]);\n}\n\n/**\n * Every function a module exports, directly or as a value of an exported\n * object, as the host's subgraph extraction reaches them. A value reached\n * twice keeps its first path.\n */\nfunction candidatesOf(exports: object): readonly Candidate[] {\n const found = new Map<unknown, Candidate>();\n const add = (value: unknown, exportPath: readonly string[]) => {\n if (typeof value !== \"function\" || found.has(value)) return;\n found.set(value, {\n value: value as Candidate[\"value\"],\n exportPath,\n });\n };\n for (const [key, value] of entriesByName(exports)) {\n add(value, [key]);\n if (value !== null && typeof value === \"object\") {\n for (const [innerKey, inner] of entriesByName(value)) {\n add(inner, [key, innerKey]);\n }\n }\n }\n return [...found.values()];\n}\n\nfunction extendsClass(derived: unknown, base: unknown): boolean {\n for (\n let current: unknown = Object.getPrototypeOf(derived);\n current !== null && current !== undefined;\n current = Object.getPrototypeOf(current)\n ) {\n if (current === base) return true;\n }\n return false;\n}\n\nconst errorMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\n/** A description from another copy of document-model, checked before use. */\nfunction isDescription(value: unknown): value is SubgraphDescription {\n if (value === null || typeof value !== \"object\") return false;\n const description = value as Record<string, unknown>;\n return (\n Array.isArray(description.diagnostics) &&\n (description.name === undefined || typeof description.name === \"string\") &&\n (description.definition === undefined ||\n (description.definition !== null &&\n typeof description.definition === \"object\"))\n );\n}\n\ntype Described =\n | { readonly kind: \"described\"; readonly description: SubgraphDescription }\n | { readonly kind: \"failed\"; readonly diagnostic: DefinitionDiagnostic };\n\nfunction describeFailed(\n source: DefinitionSource,\n received: string,\n message: string,\n): DefinitionDiagnostic {\n return subgraphToolingDiagnostics.create({\n code: \"PH-SG-DESCRIBE-FAILED\",\n source,\n path: [],\n message,\n expected: \"a description with diagnostics, and a name and definition\",\n received,\n repair:\n \"Keep the subgraph's static members free of side effects: describe() compiles getSchema() and must not throw.\",\n });\n}\n\nfunction describe(\n protocol: SubgraphProtocol,\n source: DefinitionSource,\n label: string,\n): Described {\n let description: unknown;\n try {\n description = protocol.describe();\n } catch (error) {\n return {\n kind: \"failed\",\n diagnostic: describeFailed(\n source,\n \"a thrown error\",\n `describe() of ${label} threw: ${errorMessage(error)}`,\n ),\n };\n }\n if (!isDescription(description)) {\n return {\n kind: \"failed\",\n diagnostic: describeFailed(\n source,\n describeReceived(description),\n `describe() of ${label} returned no subgraph description.`,\n ),\n };\n }\n return { kind: \"described\", description };\n}\n\n/**\n * @experimental Reads the code-first subgraph classes a module exports, as\n * the host's extraction reaches them: each export, and each value of an\n * exported object. It calls each class's protocol `describe()` and never\n * constructs a class, so a constructor that needs a database or environment\n * does not run. Schema-first classes and other values are left out. A\n * code-first class without a name is a base: it is skipped when another\n * export extends it, and reported when none does.\n */\nexport function readSubgraphDefinitions(\n exports: object,\n options: { readonly specifier?: `./${string}` } = {},\n): SubgraphDefinitions {\n const specifier = options.specifier ?? DEFAULT_SPECIFIER;\n const codeFirst: (Candidate & { readonly protocol: SubgraphProtocol })[] = [];\n const diagnostics: DefinitionDiagnostic[] = [];\n for (const candidate of candidatesOf(exports)) {\n const source = { specifier, exportPath: candidate.exportPath };\n const label = candidate.exportPath.join(\".\");\n let read: SubgraphProtocolRead;\n try {\n read = readSubgraphProtocol(candidate.value);\n } catch (error) {\n diagnostics.push(\n describeFailed(\n source,\n \"a thrown error\",\n `Reading the subgraph protocol of ${label} threw: ${errorMessage(error)}`,\n ),\n );\n continue;\n }\n if (read.kind === \"code-first\") {\n codeFirst.push({ ...candidate, protocol: read.protocol });\n } else if (read.kind === \"unsupported\") {\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-PROTOCOL-UNSUPPORTED\",\n source,\n path: [],\n message: `${label} carries subgraph protocol version ${String(read.version)}, and this release reads version 1.`,\n expected: \"protocol version 1\",\n received: String(read.version),\n repair:\n \"Build the package against the @powerhousedao/reactor-api release this ph-cli belongs to, or update ph-cli.\",\n }),\n );\n }\n }\n const subgraphs: CodeFirstSubgraph[] = [];\n for (const candidate of codeFirst) {\n const source = { specifier, exportPath: candidate.exportPath };\n const label = candidate.exportPath.join(\".\");\n const described = describe(candidate.protocol, source, label);\n if (described.kind === \"failed\") {\n diagnostics.push(described.diagnostic);\n continue;\n }\n const { name, definition } = described.description;\n if (name === undefined) {\n if (codeFirst.some(({ value }) => extendsClass(value, candidate.value))) {\n continue;\n }\n diagnostics.push(\n subgraphToolingDiagnostics.create({\n code: \"PH-SG-NAME-MISSING\",\n source,\n path: [],\n message: `${label} has no static subgraphName, and no other export extends it.`,\n expected: \"a static subgraphName, or a subclass that declares one\",\n received: \"no subgraphName\",\n repair:\n \"Declare static readonly subgraphName on the class, or export only the subclasses that extend it.\",\n }),\n );\n continue;\n }\n for (const diagnostic of described.description.diagnostics) {\n diagnostics.push(\n diagnostic.source === undefined\n ? { ...diagnostic, source }\n : diagnostic,\n );\n }\n if (definition?.schemaKind === \"typed\") {\n subgraphs.push({ name, source, definition });\n }\n }\n return { subgraphs, diagnostics };\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;EAC5B;EAAY;EAAY;EAAY;EAAY;EAAY;EAC5D;EAAY;CACd,CAAC;CACD,MAAM,wBAAQ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