document-model 6.2.3-dev.93 → 6.2.3-dev.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as getCatalogScalar, o as isScalarDefinition, r as scalarCatalog, s as scalarDefinitionVersion, t as documentModelScalars } from "./catalog-6zzASEUv.js";
1
+ import { c as scalarDefinitionVersion, i as scalarCatalog, n as documentModelScalars, r as getCatalogScalar, s as isScalarDefinition, t as storedScalarDefinition } from "./stored-definition-BKTzlNCC.js";
2
2
  import { BaseDocumentHeaderSchema, BaseDocumentStateSchema, actions, assertIsDocumentModelDocument, assertIsDocumentModelState, baseActions, baseCreateDocument, baseLoadFromInputVersioned, baseSaveToFileHandle, createAction, createBaseState, createReducer, createState, defaultBaseState, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelReducer, documentModelSaveToFileHandle, isDocumentAction, isDocumentModelDocument, isDocumentModelState, normalizeDocumentModelVersion } from "@powerhousedao/shared/document-model";
3
3
  import { z } from "zod";
4
4
  import { camelCase, constantCase, pascalCase } from "change-case";
@@ -492,6 +492,460 @@ function isNFC(value) {
492
492
  return value.normalize("NFC") === value;
493
493
  }
494
494
  //#endregion
495
+ //#region src/definition/kernel/printer.ts
496
+ const INDENT = " ";
497
+ const LINE = "\n";
498
+ function namedTypeInventory(definitions) {
499
+ const inventory = /* @__PURE__ */ new Map();
500
+ for (const definition of definitions) inventory.set(definition.name, definition);
501
+ return inventory;
502
+ }
503
+ const ESCAPES = {
504
+ "\"": "\\\"",
505
+ "\\": "\\\\",
506
+ "\b": "\\b",
507
+ "\f": "\\f",
508
+ "\n": "\\n",
509
+ "\r": "\\r",
510
+ " ": "\\t"
511
+ };
512
+ function isControlCodePoint(code) {
513
+ return code < 32 || code === 127;
514
+ }
515
+ function stringLiteral(value) {
516
+ let printed = "\"";
517
+ for (const point of value) {
518
+ const escape = ESCAPES[point];
519
+ if (escape !== void 0) {
520
+ printed += escape;
521
+ continue;
522
+ }
523
+ const code = point.codePointAt(0) ?? 0;
524
+ printed += isControlCodePoint(code) ? `\\u${code.toString(16).toUpperCase().padStart(4, "0")}` : point;
525
+ }
526
+ return `${printed}"`;
527
+ }
528
+ function hasControlCodePoint(value) {
529
+ for (const point of value) if (isControlCodePoint(point.codePointAt(0) ?? 0)) return true;
530
+ return false;
531
+ }
532
+ /**
533
+ * A block string survives the lexer's dedent only when every line is nonempty
534
+ * and carries no leading or trailing whitespace of its own, and the value ends
535
+ * in neither a quote nor a backslash. Every other description prints as an
536
+ * escaped single-line string, which always round-trips.
537
+ */
538
+ function blockStringable(value) {
539
+ if (!value.includes(LINE)) return false;
540
+ if (value.includes("\"\"\"")) return false;
541
+ if (value.endsWith("\"") || value.endsWith("\\")) return false;
542
+ return value.split(LINE).every((line) => line.length > 0 && line.trim() === line && !hasControlCodePoint(line) && !line.includes("\r"));
543
+ }
544
+ function descriptionLiteral(value, indent) {
545
+ if (!blockStringable(value)) return stringLiteral(value);
546
+ return [
547
+ "\"\"\"",
548
+ ...value.split(LINE).map((line) => `${indent}${line}`),
549
+ `${indent}"""`
550
+ ].join(LINE);
551
+ }
552
+ function descriptionLine(description, indent = "") {
553
+ if (description === null) return "";
554
+ return `${indent}${descriptionLiteral(description, indent)}${LINE}`;
555
+ }
556
+ function inlineDescription(description) {
557
+ return description === null ? "" : `${stringLiteral(description)} `;
558
+ }
559
+ function printNumber(value) {
560
+ if (!Number.isFinite(value)) throw new TypeError(`A GraphQL value must be finite, received ${String(value)}.`);
561
+ return JSON.stringify(value);
562
+ }
563
+ function printGraphQLLiteral(value) {
564
+ if (value === null) return "null";
565
+ if (typeof value === "boolean") return String(value);
566
+ if (typeof value === "number") return printNumber(value);
567
+ if (typeof value === "string") return stringLiteral(value);
568
+ if (Array.isArray(value)) return `[${value.map(printGraphQLLiteral).join(", ")}]`;
569
+ return `{${Object.entries(value).map(([key, member]) => `${key}: ${printGraphQLLiteral(member)}`).join(", ")}}`;
570
+ }
571
+ function enumValueNames(definition) {
572
+ return new Set(definition.values.map((value) => value.name));
573
+ }
574
+ function printTypedValue(value, type, inventory) {
575
+ if (value === null) return "null";
576
+ if (type.kind === "list") {
577
+ if (!Array.isArray(value)) return printTypedValue(value, type.item, inventory);
578
+ return `[${value.map((item) => printTypedValue(item, type.item, inventory)).join(", ")}]`;
579
+ }
580
+ if (type.kind === "scalar") return printGraphQLLiteral(value);
581
+ const definition = inventory.get(type.name);
582
+ if (definition === void 0) return printGraphQLLiteral(value);
583
+ if (definition.kind === "enum") return typeof value === "string" && enumValueNames(definition).has(value) ? value : printGraphQLLiteral(value);
584
+ if (definition.kind !== "input" || typeof value !== "object" || Array.isArray(value)) return printGraphQLLiteral(value);
585
+ const fields = new Map(definition.fields.map((field) => [field.name, field]));
586
+ return `{${Object.entries(value).map(([key, member]) => {
587
+ const field = fields.get(key);
588
+ return `${key}: ${field === void 0 ? printGraphQLLiteral(member) : printTypedValue(member, field.type, inventory)}`;
589
+ }).join(", ")}}`;
590
+ }
591
+ function printTypeReference(type) {
592
+ const base = type.kind === "list" ? `[${printTypeReference(type.item)}]` : type.name;
593
+ return type.required ? `${base}!` : base;
594
+ }
595
+ function printDeprecated(deprecated) {
596
+ return deprecated === null ? "" : ` @deprecated(reason: ${stringLiteral(deprecated)})`;
597
+ }
598
+ function printDirectives(directives) {
599
+ if (directives === void 0 || directives.length === 0) return "";
600
+ return directives.map((directive) => {
601
+ if (directive.arguments.length === 0) return ` @${directive.name}`;
602
+ const args = directive.arguments.map((argument) => `${argument.name}: ${printGraphQLLiteral(argument.value)}`).join(", ");
603
+ return ` @${directive.name}(${args})`;
604
+ }).join("");
605
+ }
606
+ function printInputValue(field, inventory) {
607
+ const defaultValue = Object.hasOwn(field, "defaultValue") ? ` = ${printTypedValue(field.defaultValue, field.type, inventory)}` : "";
608
+ return `${field.name}: ${printTypeReference(field.type)}${defaultValue}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
609
+ }
610
+ function printInputField(field, inventory) {
611
+ return `${descriptionLine(field.description, INDENT)}${INDENT}${printInputValue(field, inventory)}`;
612
+ }
613
+ function printArguments(args, inventory) {
614
+ if (args === void 0 || args.length === 0) return "";
615
+ return `(${args.map((argument) => `${inlineDescription(argument.description)}${printInputValue(argument, inventory)}`).join(", ")})`;
616
+ }
617
+ function printField(field, inventory) {
618
+ return `${descriptionLine(field.description, INDENT)}${INDENT}${field.name}${printArguments(field.args, inventory)}: ${printTypeReference(field.type)}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
619
+ }
620
+ function printImplements(implemented) {
621
+ return implemented === void 0 || implemented.length === 0 ? "" : ` implements ${implemented.join(" & ")}`;
622
+ }
623
+ function printBlock(members) {
624
+ return members.length === 0 ? "" : ` {${LINE}${members.join(LINE)}${LINE}}`;
625
+ }
626
+ function printNamedDefinition(definition, inventory = namedTypeInventory([definition])) {
627
+ const description = descriptionLine(definition.description);
628
+ switch (definition.kind) {
629
+ case "enum": {
630
+ const values = definition.values.map((value) => `${descriptionLine(value.description, INDENT)}${INDENT}${value.name}${printDeprecated(value.deprecated)}${printDirectives(value.directives)}`);
631
+ return `${description}enum ${definition.name}${printBlock(values)}`;
632
+ }
633
+ case "object": {
634
+ const fields = definition.fields.map((field) => printField(field, inventory));
635
+ return `${description}type ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
636
+ }
637
+ case "interface": {
638
+ const fields = definition.fields.map((field) => printField(field, inventory));
639
+ return `${description}interface ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
640
+ }
641
+ case "input": {
642
+ const fields = definition.fields.length === 0 ? [`${INDENT}${EMPTY_INPUT_FIELD_NAME}: Boolean`] : definition.fields.map((field) => printInputField(field, inventory));
643
+ return `${description}input ${definition.name}${printBlock(fields)}`;
644
+ }
645
+ case "union": return `${description}union ${definition.name} = ${definition.members.join(" | ")}`;
646
+ }
647
+ }
648
+ function printSchemaSegment(definitions, known = definitions) {
649
+ if (definitions.length === 0) return "";
650
+ const inventory = namedTypeInventory(known);
651
+ return `${definitions.map((definition) => printNamedDefinition(definition, inventory)).join(`${LINE}${LINE}`)}${LINE}`;
652
+ }
653
+ //#endregion
654
+ //#region src/definition/compiler/segments.ts
655
+ function referencedNames(definition) {
656
+ const names = [];
657
+ const visit = (reference) => {
658
+ if (reference.kind === "list") {
659
+ visit(reference.item);
660
+ return;
661
+ }
662
+ if (reference.kind === "named") names.push(reference.name);
663
+ };
664
+ switch (definition.kind) {
665
+ case "enum": return names;
666
+ case "union": return definition.members;
667
+ case "input":
668
+ definition.fields.forEach((field) => visit(field.type));
669
+ return names;
670
+ case "object":
671
+ case "interface":
672
+ names.push(...definition.implements ?? []);
673
+ for (const field of definition.fields) {
674
+ field.args?.forEach((argument) => visit(argument.type));
675
+ visit(field.type);
676
+ }
677
+ return names;
678
+ }
679
+ }
680
+ function reachableFrom(rootName, index) {
681
+ const reached = /* @__PURE__ */ new Set();
682
+ if (rootName === null) return reached;
683
+ const queue = [rootName];
684
+ while (queue.length > 0) {
685
+ const name = queue.pop();
686
+ if (reached.has(name)) continue;
687
+ const definition = index.get(name);
688
+ if (definition === void 0) continue;
689
+ reached.add(name);
690
+ queue.push(...referencedNames(definition));
691
+ }
692
+ return reached;
693
+ }
694
+ function assignStoredSegments(input) {
695
+ const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
696
+ const globalReach = reachableFrom(input.globalRoot, stateIndex);
697
+ const localReach = reachableFrom(input.localRoot, stateIndex);
698
+ const operationIndex = new Map(stateIndex);
699
+ for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
700
+ const claimed = /* @__PURE__ */ new Set();
701
+ const operations = /* @__PURE__ */ new Map();
702
+ for (const operation of input.operations) {
703
+ if (operation.input === null) continue;
704
+ claimed.add(operation.input.name);
705
+ const reached = reachableFrom(operation.input.name, operationIndex);
706
+ const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
707
+ for (const definition of supporting) claimed.add(definition.name);
708
+ operations.set(operation.key, [operation.input, ...supporting]);
709
+ }
710
+ const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
711
+ const localDeclared = new Set(local.map((definition) => definition.name));
712
+ return {
713
+ global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
714
+ local,
715
+ operations
716
+ };
717
+ }
718
+ //#endregion
719
+ //#region src/definition/compiler/graphql-projection.ts
720
+ const nameNode = (value) => ({
721
+ kind: "Name",
722
+ value
723
+ });
724
+ const namedType$2 = (name) => ({
725
+ kind: "NamedType",
726
+ name: nameNode(name)
727
+ });
728
+ const stringValue = (value, block = false) => ({
729
+ kind: "StringValue",
730
+ value,
731
+ block
732
+ });
733
+ function description(value, form = "printed") {
734
+ return value === null ? {} : { description: stringValue(value, form === "printed" && blockStringable(value)) };
735
+ }
736
+ function typeNode(type) {
737
+ const base = type.kind === "list" ? {
738
+ kind: "ListType",
739
+ type: typeNode(type.item)
740
+ } : namedType$2(type.name);
741
+ return type.required ? {
742
+ kind: "NonNullType",
743
+ type: base
744
+ } : base;
745
+ }
746
+ function numberValue(value) {
747
+ if (!Number.isFinite(value)) throw new TypeError(`A GraphQL value must be finite, received ${String(value)}.`);
748
+ const printed = JSON.stringify(value);
749
+ return /[.eE]/.test(printed) ? {
750
+ kind: "FloatValue",
751
+ value: printed
752
+ } : {
753
+ kind: "IntValue",
754
+ value: printed
755
+ };
756
+ }
757
+ function literalValue(value) {
758
+ if (value === null) return { kind: "NullValue" };
759
+ if (typeof value === "boolean") return {
760
+ kind: "BooleanValue",
761
+ value
762
+ };
763
+ if (typeof value === "number") return numberValue(value);
764
+ if (typeof value === "string") return stringValue(value);
765
+ if (Array.isArray(value)) return {
766
+ kind: "ListValue",
767
+ values: value.map(literalValue)
768
+ };
769
+ return objectValue(value, (member) => literalValue(member));
770
+ }
771
+ function objectValue(value, member) {
772
+ return {
773
+ kind: "ObjectValue",
774
+ fields: Object.entries(value).map(([key, entry]) => ({
775
+ kind: "ObjectField",
776
+ name: nameNode(key),
777
+ value: member(entry, key)
778
+ }))
779
+ };
780
+ }
781
+ function enumMember(definition, value) {
782
+ return definition.values.some((candidate) => candidate.name === value);
783
+ }
784
+ function typedValue(value, type, inventory) {
785
+ if (value === null) return { kind: "NullValue" };
786
+ if (type.kind === "list") return Array.isArray(value) ? {
787
+ kind: "ListValue",
788
+ values: value.map((item) => typedValue(item, type.item, inventory))
789
+ } : typedValue(value, type.item, inventory);
790
+ if (type.kind === "scalar") return literalValue(value);
791
+ const definition = inventory.get(type.name);
792
+ if (definition?.kind === "enum") return typeof value === "string" && enumMember(definition, value) ? {
793
+ kind: "EnumValue",
794
+ value
795
+ } : literalValue(value);
796
+ if (definition?.kind !== "input" || typeof value !== "object" || Array.isArray(value)) return literalValue(value);
797
+ const fields = new Map(definition.fields.map((field) => [field.name, field]));
798
+ return objectValue(value, (member, key) => {
799
+ const field = fields.get(key);
800
+ return field === void 0 ? literalValue(member) : typedValue(member, field.type, inventory);
801
+ });
802
+ }
803
+ function directiveNodes(deprecated, directives) {
804
+ const used = (directives ?? []).map((directive) => ({
805
+ kind: "Directive",
806
+ name: nameNode(directive.name),
807
+ arguments: directive.arguments.map((argument) => ({
808
+ kind: "Argument",
809
+ name: nameNode(argument.name),
810
+ value: literalValue(argument.value)
811
+ }))
812
+ }));
813
+ if (deprecated === null) return used;
814
+ return [{
815
+ kind: "Directive",
816
+ name: nameNode("deprecated"),
817
+ arguments: [{
818
+ kind: "Argument",
819
+ name: nameNode("reason"),
820
+ value: stringValue(deprecated)
821
+ }]
822
+ }, ...used];
823
+ }
824
+ function inputValueNode(field, inventory, form) {
825
+ return {
826
+ kind: "InputValueDefinition",
827
+ ...description(field.description, form),
828
+ name: nameNode(field.name),
829
+ type: typeNode(field.type),
830
+ ...Object.hasOwn(field, "defaultValue") && { defaultValue: typedValue(field.defaultValue, field.type, inventory) },
831
+ directives: directiveNodes(field.deprecated, field.directives)
832
+ };
833
+ }
834
+ const EMPTY_INPUT_FIELD = {
835
+ kind: "InputValueDefinition",
836
+ name: nameNode(EMPTY_INPUT_FIELD_NAME),
837
+ type: namedType$2("Boolean"),
838
+ directives: []
839
+ };
840
+ function fieldNodes(fields, inventory) {
841
+ return fields.map((field) => ({
842
+ kind: "FieldDefinition",
843
+ ...description(field.description),
844
+ name: nameNode(field.name),
845
+ arguments: (field.args ?? []).map((argument) => inputValueNode(argument, inventory, "argument-inline")),
846
+ type: typeNode(field.type),
847
+ directives: directiveNodes(field.deprecated, field.directives)
848
+ }));
849
+ }
850
+ function definitionNode(definition, inventory) {
851
+ const named = {
852
+ ...description(definition.description),
853
+ name: nameNode(definition.name),
854
+ directives: []
855
+ };
856
+ switch (definition.kind) {
857
+ case "enum": return {
858
+ kind: "EnumTypeDefinition",
859
+ ...named,
860
+ values: definition.values.map((value) => ({
861
+ kind: "EnumValueDefinition",
862
+ ...description(value.description),
863
+ name: nameNode(value.name),
864
+ directives: directiveNodes(value.deprecated, value.directives)
865
+ }))
866
+ };
867
+ case "object":
868
+ case "interface": return {
869
+ kind: definition.kind === "object" ? "ObjectTypeDefinition" : "InterfaceTypeDefinition",
870
+ ...named,
871
+ interfaces: (definition.implements ?? []).map(namedType$2),
872
+ fields: fieldNodes(definition.fields, inventory)
873
+ };
874
+ case "input": return {
875
+ kind: "InputObjectTypeDefinition",
876
+ ...named,
877
+ fields: definition.fields.length === 0 ? [EMPTY_INPUT_FIELD] : definition.fields.map((field) => inputValueNode(field, inventory, "printed"))
878
+ };
879
+ case "union": return {
880
+ kind: "UnionTypeDefinition",
881
+ ...named,
882
+ types: definition.members.map(namedType$2)
883
+ };
884
+ }
885
+ }
886
+ function isPackageScalar(scalar) {
887
+ return scalar.implementation.startsWith("package#");
888
+ }
889
+ /**
890
+ * Projects a specification into the GraphQL documents its stored SDL
891
+ * segments parse to: `print(segment.document)` equals
892
+ * `print(parse(storedSegment))` for the state schemas and each operation's
893
+ * `schema` that `materialize` stores.
894
+ */
895
+ function projectDocumentModelGraphQL(definition, specification) {
896
+ const { types } = specification;
897
+ const inventory = new Map(types.map((type) => [type.name, type]));
898
+ const document = (definitions) => ({
899
+ kind: "Document",
900
+ definitions: definitions.map((type) => definitionNode(type, inventory))
901
+ });
902
+ const globalRoot = specification.state.global.root.name;
903
+ const localRoot = specification.state.local.root?.name ?? null;
904
+ const operationKey = (moduleKey, key) => `${moduleKey}/${key}`;
905
+ const segments = assignStoredSegments({
906
+ types,
907
+ globalRoot,
908
+ localRoot,
909
+ operations: specification.modules.flatMap((module) => module.operations.map((operation) => ({
910
+ key: operationKey(module.key, operation.key),
911
+ input: operation.input
912
+ })))
913
+ });
914
+ const packageScalars = specification.scalars.filter(isPackageScalar);
915
+ const global = document(segments.global);
916
+ return {
917
+ graphQLName: definition.model.graphQLName,
918
+ global: {
919
+ root: globalRoot,
920
+ document: {
921
+ kind: "Document",
922
+ definitions: [...packageScalars.map(({ name }) => name).sort(compareCodeUnits).map((name) => ({
923
+ kind: "ScalarTypeDefinition",
924
+ name: nameNode(name),
925
+ directives: []
926
+ })), ...global.definitions]
927
+ }
928
+ },
929
+ local: localRoot === null ? null : {
930
+ root: localRoot,
931
+ document: document(segments.local)
932
+ },
933
+ modules: specification.modules.map((module) => ({
934
+ key: module.key,
935
+ name: module.name,
936
+ operations: module.operations.map((operation) => ({
937
+ key: operation.key,
938
+ name: operation.name ?? operation.actionType,
939
+ actionType: operation.actionType,
940
+ creatorKey: operation.creatorKey,
941
+ scope: operation.scope,
942
+ input: operation.input === null ? null : document(segments.operations.get(operationKey(module.key, operation.key)) ?? [operation.input])
943
+ }))
944
+ })),
945
+ packageScalars
946
+ };
947
+ }
948
+ //#endregion
495
949
  //#region src/definition/kernel/diagnostics.ts
496
950
  const MAX_SUMMARY_CODE_POINTS = 512;
497
951
  function capCodePoints(value, max = MAX_SUMMARY_CODE_POINTS) {
@@ -651,6 +1105,20 @@ var DefinitionError = class extends Error {
651
1105
  }
652
1106
  };
653
1107
  //#endregion
1108
+ //#region src/definition/kernel/diagnostic-codes.ts
1109
+ const kernelDiagnostics = defineDiagnosticCatalog({
1110
+ "PH-DEF-OPTION-INVALID": {
1111
+ severity: "error",
1112
+ phase: "definition",
1113
+ meaning: "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"
1114
+ },
1115
+ "PH-DEF-COMPATIBILITY-INVALID": {
1116
+ severity: "error",
1117
+ phase: "definition",
1118
+ meaning: "A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies"
1119
+ }
1120
+ });
1121
+ //#endregion
654
1122
  //#region src/definition/dsl/diagnostic-codes.ts
655
1123
  const dslDiagnostics = defineDiagnosticCatalog({
656
1124
  "PH-DEF-FIELD-OPTION-UNSUPPORTED": {
@@ -698,28 +1166,17 @@ const dslDiagnostics = defineDiagnosticCatalog({
698
1166
  phase: "definition",
699
1167
  meaning: "A scalar field-use factory is used as a field without being called"
700
1168
  },
701
- "PH-SCALAR-INTERNAL": {
702
- severity: "error",
703
- phase: "definition",
704
- meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
705
- },
706
- "PH-SCALAR-DEFINITION-INVALID": {
707
- severity: "error",
708
- phase: "definition",
709
- meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
710
- }
711
- }, defineDiagnosticCatalog({
712
- "PH-DEF-OPTION-INVALID": {
1169
+ "PH-SCALAR-INTERNAL": {
713
1170
  severity: "error",
714
1171
  phase: "definition",
715
- meaning: "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"
1172
+ meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
716
1173
  },
717
- "PH-DEF-COMPATIBILITY-INVALID": {
1174
+ "PH-SCALAR-DEFINITION-INVALID": {
718
1175
  severity: "error",
719
1176
  phase: "definition",
720
- meaning: "A location-free GraphQL compatibility AST is malformed or disagrees with the stored definitions it accompanies"
1177
+ meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
721
1178
  }
722
- }));
1179
+ }, kernelDiagnostics);
723
1180
  //#endregion
724
1181
  //#region src/definition/kernel/global-registry.ts
725
1182
  function getGlobalRegistry(key, create) {
@@ -1573,7 +2030,7 @@ function enumValues(input) {
1573
2030
  });
1574
2031
  }));
1575
2032
  }
1576
- function namedType(node) {
2033
+ function namedType$1(node) {
1577
2034
  const descriptor = {
1578
2035
  ...node,
1579
2036
  role: NAMED_TYPE_ROLE,
@@ -1627,13 +2084,13 @@ function implementedInterfaces(config) {
1627
2084
  return Object.freeze([...implemented]);
1628
2085
  }
1629
2086
  function objectType(name, options) {
1630
- return namedType({
2087
+ return namedType$1({
1631
2088
  kind: "object",
1632
2089
  ...implementingMembers(name, options)
1633
2090
  });
1634
2091
  }
1635
2092
  function interfaceType(name, options) {
1636
- return namedType({
2093
+ return namedType$1({
1637
2094
  kind: "interface",
1638
2095
  ...implementingMembers(name, options)
1639
2096
  });
@@ -1710,7 +2167,7 @@ const ph = Object.freeze({
1710
2167
  enum(name, options) {
1711
2168
  const validName = assertAuthoredName(name, ["name"]);
1712
2169
  const config = snapshotDescriptorOptions(options, ["values", "description"], ["options"]);
1713
- return namedType({
2170
+ return namedType$1({
1714
2171
  kind: "enum",
1715
2172
  name: validName,
1716
2173
  description: stringOption(config, "description", ["options"]),
@@ -1723,7 +2180,7 @@ const ph = Object.freeze({
1723
2180
  const [nameOrOptions, maybeOptions] = args;
1724
2181
  const name = typeof nameOrOptions === "string" ? assertAuthoredName(nameOrOptions, ["name"]) : null;
1725
2182
  const config = snapshotDescriptorOptions(typeof nameOrOptions === "string" ? maybeOptions : nameOrOptions, ["fields", "description"], ["options"]);
1726
- return namedType({
2183
+ return namedType$1({
1727
2184
  kind: "input",
1728
2185
  name,
1729
2186
  description: stringOption(config, "description", ["options"]),
@@ -1765,7 +2222,7 @@ const ph = Object.freeze({
1765
2222
  });
1766
2223
  seen.add(memberName);
1767
2224
  });
1768
- return namedType({
2225
+ return namedType$1({
1769
2226
  kind: "union",
1770
2227
  name: validName,
1771
2228
  description: stringOption(config, "description", ["options"]),
@@ -1813,165 +2270,6 @@ var DefinitionDiagnosticCollector = class {
1813
2270
  }
1814
2271
  };
1815
2272
  //#endregion
1816
- //#region src/definition/kernel/printer.ts
1817
- const INDENT = " ";
1818
- const LINE = "\n";
1819
- function namedTypeInventory(definitions) {
1820
- const inventory = /* @__PURE__ */ new Map();
1821
- for (const definition of definitions) inventory.set(definition.name, definition);
1822
- return inventory;
1823
- }
1824
- const ESCAPES = {
1825
- "\"": "\\\"",
1826
- "\\": "\\\\",
1827
- "\b": "\\b",
1828
- "\f": "\\f",
1829
- "\n": "\\n",
1830
- "\r": "\\r",
1831
- " ": "\\t"
1832
- };
1833
- function isControlCodePoint(code) {
1834
- return code < 32 || code === 127;
1835
- }
1836
- function stringLiteral(value) {
1837
- let printed = "\"";
1838
- for (const point of value) {
1839
- const escape = ESCAPES[point];
1840
- if (escape !== void 0) {
1841
- printed += escape;
1842
- continue;
1843
- }
1844
- const code = point.codePointAt(0) ?? 0;
1845
- printed += isControlCodePoint(code) ? `\\u${code.toString(16).toUpperCase().padStart(4, "0")}` : point;
1846
- }
1847
- return `${printed}"`;
1848
- }
1849
- function hasControlCodePoint(value) {
1850
- for (const point of value) if (isControlCodePoint(point.codePointAt(0) ?? 0)) return true;
1851
- return false;
1852
- }
1853
- /**
1854
- * A block string survives the lexer's dedent only when every line is nonempty
1855
- * and carries no leading or trailing whitespace of its own, and the value ends
1856
- * in neither a quote nor a backslash. Every other description prints as an
1857
- * escaped single-line string, which always round-trips.
1858
- */
1859
- function blockStringable(value) {
1860
- if (!value.includes(LINE)) return false;
1861
- if (value.includes("\"\"\"")) return false;
1862
- if (value.endsWith("\"") || value.endsWith("\\")) return false;
1863
- return value.split(LINE).every((line) => line.length > 0 && line.trim() === line && !hasControlCodePoint(line) && !line.includes("\r"));
1864
- }
1865
- function descriptionLiteral(value, indent) {
1866
- if (!blockStringable(value)) return stringLiteral(value);
1867
- return [
1868
- "\"\"\"",
1869
- ...value.split(LINE).map((line) => `${indent}${line}`),
1870
- `${indent}"""`
1871
- ].join(LINE);
1872
- }
1873
- function descriptionLine(description, indent = "") {
1874
- if (description === null) return "";
1875
- return `${indent}${descriptionLiteral(description, indent)}${LINE}`;
1876
- }
1877
- function inlineDescription(description) {
1878
- return description === null ? "" : `${stringLiteral(description)} `;
1879
- }
1880
- function printNumber(value) {
1881
- if (!Number.isFinite(value)) throw new TypeError(`A GraphQL value must be finite, received ${String(value)}.`);
1882
- return JSON.stringify(value);
1883
- }
1884
- function printGraphQLLiteral(value) {
1885
- if (value === null) return "null";
1886
- if (typeof value === "boolean") return String(value);
1887
- if (typeof value === "number") return printNumber(value);
1888
- if (typeof value === "string") return stringLiteral(value);
1889
- if (Array.isArray(value)) return `[${value.map(printGraphQLLiteral).join(", ")}]`;
1890
- return `{${Object.entries(value).map(([key, member]) => `${key}: ${printGraphQLLiteral(member)}`).join(", ")}}`;
1891
- }
1892
- function enumValueNames(definition) {
1893
- return new Set(definition.values.map((value) => value.name));
1894
- }
1895
- function printTypedValue(value, type, inventory) {
1896
- if (value === null) return "null";
1897
- if (type.kind === "list") {
1898
- if (!Array.isArray(value)) return printTypedValue(value, type.item, inventory);
1899
- return `[${value.map((item) => printTypedValue(item, type.item, inventory)).join(", ")}]`;
1900
- }
1901
- if (type.kind === "scalar") return printGraphQLLiteral(value);
1902
- const definition = inventory.get(type.name);
1903
- if (definition === void 0) return printGraphQLLiteral(value);
1904
- if (definition.kind === "enum") return typeof value === "string" && enumValueNames(definition).has(value) ? value : printGraphQLLiteral(value);
1905
- if (definition.kind !== "input" || typeof value !== "object" || Array.isArray(value)) return printGraphQLLiteral(value);
1906
- const fields = new Map(definition.fields.map((field) => [field.name, field]));
1907
- return `{${Object.entries(value).map(([key, member]) => {
1908
- const field = fields.get(key);
1909
- return `${key}: ${field === void 0 ? printGraphQLLiteral(member) : printTypedValue(member, field.type, inventory)}`;
1910
- }).join(", ")}}`;
1911
- }
1912
- function printTypeReference(type) {
1913
- const base = type.kind === "list" ? `[${printTypeReference(type.item)}]` : type.name;
1914
- return type.required ? `${base}!` : base;
1915
- }
1916
- function printDeprecated(deprecated) {
1917
- return deprecated === null ? "" : ` @deprecated(reason: ${stringLiteral(deprecated)})`;
1918
- }
1919
- function printDirectives(directives) {
1920
- if (directives === void 0 || directives.length === 0) return "";
1921
- return directives.map((directive) => {
1922
- if (directive.arguments.length === 0) return ` @${directive.name}`;
1923
- const args = directive.arguments.map((argument) => `${argument.name}: ${printGraphQLLiteral(argument.value)}`).join(", ");
1924
- return ` @${directive.name}(${args})`;
1925
- }).join("");
1926
- }
1927
- function printInputValue(field, inventory) {
1928
- const defaultValue = Object.hasOwn(field, "defaultValue") ? ` = ${printTypedValue(field.defaultValue, field.type, inventory)}` : "";
1929
- return `${field.name}: ${printTypeReference(field.type)}${defaultValue}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
1930
- }
1931
- function printInputField(field, inventory) {
1932
- return `${descriptionLine(field.description, INDENT)}${INDENT}${printInputValue(field, inventory)}`;
1933
- }
1934
- function printArguments(args, inventory) {
1935
- if (args === void 0 || args.length === 0) return "";
1936
- return `(${args.map((argument) => `${inlineDescription(argument.description)}${printInputValue(argument, inventory)}`).join(", ")})`;
1937
- }
1938
- function printField(field, inventory) {
1939
- return `${descriptionLine(field.description, INDENT)}${INDENT}${field.name}${printArguments(field.args, inventory)}: ${printTypeReference(field.type)}${printDeprecated(field.deprecated)}${printDirectives(field.directives)}`;
1940
- }
1941
- function printImplements(implemented) {
1942
- return implemented === void 0 || implemented.length === 0 ? "" : ` implements ${implemented.join(" & ")}`;
1943
- }
1944
- function printBlock(members) {
1945
- return members.length === 0 ? "" : ` {${LINE}${members.join(LINE)}${LINE}}`;
1946
- }
1947
- function printNamedDefinition(definition, inventory = namedTypeInventory([definition])) {
1948
- const description = descriptionLine(definition.description);
1949
- switch (definition.kind) {
1950
- case "enum": {
1951
- const values = definition.values.map((value) => `${descriptionLine(value.description, INDENT)}${INDENT}${value.name}${printDeprecated(value.deprecated)}${printDirectives(value.directives)}`);
1952
- return `${description}enum ${definition.name}${printBlock(values)}`;
1953
- }
1954
- case "object": {
1955
- const fields = definition.fields.map((field) => printField(field, inventory));
1956
- return `${description}type ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
1957
- }
1958
- case "interface": {
1959
- const fields = definition.fields.map((field) => printField(field, inventory));
1960
- return `${description}interface ${definition.name}${printImplements(definition.implements)}${printBlock(fields)}`;
1961
- }
1962
- case "input": {
1963
- const fields = definition.fields.length === 0 ? [`${INDENT}${EMPTY_INPUT_FIELD_NAME}: Boolean`] : definition.fields.map((field) => printInputField(field, inventory));
1964
- return `${description}input ${definition.name}${printBlock(fields)}`;
1965
- }
1966
- case "union": return `${description}union ${definition.name} = ${definition.members.join(" | ")}`;
1967
- }
1968
- }
1969
- function printSchemaSegment(definitions, known = definitions) {
1970
- if (definitions.length === 0) return "";
1971
- const inventory = namedTypeInventory(known);
1972
- return `${definitions.map((definition) => printNamedDefinition(definition, inventory)).join(`${LINE}${LINE}`)}${LINE}`;
1973
- }
1974
- //#endregion
1975
2273
  //#region src/definition/compiler/anonymous-input.ts
1976
2274
  function nameAnonymousInput(descriptor, name) {
1977
2275
  assertNamedType(descriptor, ["descriptor"], "PH-DEF-REFERENCE-TARGET-INVALID", "Pass a descriptor returned by ph.input.");
@@ -2939,117 +3237,41 @@ function collisionDiagnostic(claimant, collision) {
2939
3237
  code: collision.actionType ? "PH-DM-DUPLICATE-ACTION" : "PH-DM-DUPLICATE-NAME",
2940
3238
  path: claimant.path,
2941
3239
  message: `${claimant.label} derives ${list}, already derived by ${collision.first.label}.`,
2942
- expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,
2943
- received: list,
2944
- repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,
2945
- related: [{
2946
- path: collision.first.path,
2947
- message: `${collision.first.label} derives the same ${collision.names.length === 1 ? "name" : "names"}.`
2948
- }]
2949
- });
2950
- }
2951
- function checkDerivedNameCollisions(modules) {
2952
- const claims = /* @__PURE__ */ new Map();
2953
- const diagnostics = [];
2954
- for (const module of modules) {
2955
- const moduleClaim = {
2956
- path: ["modules", module.key],
2957
- label: `module ${JSON.stringify(module.key)}`
2958
- };
2959
- for (const collision of claim(claims, moduleClaim, moduleNameClaims(module.names))) diagnostics.push(collisionDiagnostic(moduleClaim, collision));
2960
- for (const operation of module.operations) {
2961
- const operationClaim = {
2962
- path: [
2963
- "modules",
2964
- module.key,
2965
- "operations",
2966
- operation.key
2967
- ],
2968
- label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`
2969
- };
2970
- for (const collision of claim(claims, operationClaim, operationNameClaims(module.key, operation.names))) diagnostics.push(collisionDiagnostic(operationClaim, collision));
2971
- }
2972
- }
2973
- return diagnostics;
2974
- }
2975
- //#endregion
2976
- //#region src/definition/compiler/segments.ts
2977
- function referencedNames(definition) {
2978
- const names = [];
2979
- const visit = (reference) => {
2980
- if (reference.kind === "list") {
2981
- visit(reference.item);
2982
- return;
2983
- }
2984
- if (reference.kind === "named") names.push(reference.name);
2985
- };
2986
- switch (definition.kind) {
2987
- case "enum": return names;
2988
- case "union": return definition.members;
2989
- case "input":
2990
- definition.fields.forEach((field) => visit(field.type));
2991
- return names;
2992
- case "object":
2993
- case "interface":
2994
- names.push(...definition.implements ?? []);
2995
- for (const field of definition.fields) {
2996
- field.args?.forEach((argument) => visit(argument.type));
2997
- visit(field.type);
2998
- }
2999
- return names;
3000
- }
3001
- }
3002
- function reachableFrom(rootName, index) {
3003
- const reached = /* @__PURE__ */ new Set();
3004
- if (rootName === null) return reached;
3005
- const queue = [rootName];
3006
- while (queue.length > 0) {
3007
- const name = queue.pop();
3008
- if (reached.has(name)) continue;
3009
- const definition = index.get(name);
3010
- if (definition === void 0) continue;
3011
- reached.add(name);
3012
- queue.push(...referencedNames(definition));
3013
- }
3014
- return reached;
3015
- }
3016
- function assignStoredSegments(input) {
3017
- const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
3018
- const globalReach = reachableFrom(input.globalRoot, stateIndex);
3019
- const localReach = reachableFrom(input.localRoot, stateIndex);
3020
- const operationIndex = new Map(stateIndex);
3021
- for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
3022
- const claimed = /* @__PURE__ */ new Set();
3023
- const operations = /* @__PURE__ */ new Map();
3024
- for (const operation of input.operations) {
3025
- if (operation.input === null) continue;
3026
- claimed.add(operation.input.name);
3027
- const reached = reachableFrom(operation.input.name, operationIndex);
3028
- const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
3029
- for (const definition of supporting) claimed.add(definition.name);
3030
- operations.set(operation.key, [operation.input, ...supporting]);
3240
+ expected: `distinct derived names for ${claimant.label} and ${collision.first.label}`,
3241
+ received: list,
3242
+ repair: `Rename ${claimant.label} or ${collision.first.label} so their derived names differ.`,
3243
+ related: [{
3244
+ path: collision.first.path,
3245
+ message: `${collision.first.label} derives the same ${collision.names.length === 1 ? "name" : "names"}.`
3246
+ }]
3247
+ });
3248
+ }
3249
+ function checkDerivedNameCollisions(modules) {
3250
+ const claims = /* @__PURE__ */ new Map();
3251
+ const diagnostics = [];
3252
+ for (const module of modules) {
3253
+ const moduleClaim = {
3254
+ path: ["modules", module.key],
3255
+ label: `module ${JSON.stringify(module.key)}`
3256
+ };
3257
+ for (const collision of claim(claims, moduleClaim, moduleNameClaims(module.names))) diagnostics.push(collisionDiagnostic(moduleClaim, collision));
3258
+ for (const operation of module.operations) {
3259
+ const operationClaim = {
3260
+ path: [
3261
+ "modules",
3262
+ module.key,
3263
+ "operations",
3264
+ operation.key
3265
+ ],
3266
+ label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`
3267
+ };
3268
+ for (const collision of claim(claims, operationClaim, operationNameClaims(module.key, operation.names))) diagnostics.push(collisionDiagnostic(operationClaim, collision));
3269
+ }
3031
3270
  }
3032
- const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
3033
- const localDeclared = new Set(local.map((definition) => definition.name));
3034
- return {
3035
- global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
3036
- local,
3037
- operations
3038
- };
3271
+ return diagnostics;
3039
3272
  }
3040
3273
  //#endregion
3041
3274
  //#region src/definition/compiler/stored-scalar.ts
3042
- function storedScalarDefinition(definition) {
3043
- return {
3044
- kind: "powerhouse.scalar",
3045
- formatVersion: 1,
3046
- name: definition.name,
3047
- representation: definition.representation ?? "json",
3048
- description: definition.description ?? "",
3049
- coercion: { source: definition.coercion === void 0 ? "derived" : "explicit" },
3050
- coercionProfile: "catalog-v1"
3051
- };
3052
- }
3053
3275
  function scalarReferences(catalogScalars, packageScalars) {
3054
3276
  const catalog = documentModelScalars.map(({ name }) => name).filter((name) => catalogScalars.has(name)).map((name) => ({
3055
3277
  name,
@@ -3876,7 +4098,7 @@ function normalizeConfig(collector, input) {
3876
4098
  scopes
3877
4099
  };
3878
4100
  }
3879
- const OPERATION_KEYS = [
4101
+ const OPERATION_KEYS$1 = [
3880
4102
  "description",
3881
4103
  "input",
3882
4104
  "errors",
@@ -3885,7 +4107,7 @@ const OPERATION_KEYS = [
3885
4107
  "reducerTemplate",
3886
4108
  "reduce"
3887
4109
  ];
3888
- const ERROR_KEYS = [
4110
+ const ERROR_KEYS$1 = [
3889
4111
  "code",
3890
4112
  "name",
3891
4113
  "description",
@@ -3921,11 +4143,11 @@ function normalizeErrors(collector, value, path) {
3921
4143
  });
3922
4144
  continue;
3923
4145
  }
3924
- const metadata = take(collector, snapshotDataRecord(declaration, ERROR_KEYS, errorPath), ERROR_KEYS);
4146
+ const metadata = take(collector, snapshotDataRecord(declaration, ERROR_KEYS$1, errorPath), ERROR_KEYS$1);
3925
4147
  if (metadata === void 0) continue;
3926
4148
  const entry = {};
3927
4149
  let valid = true;
3928
- for (const member of ERROR_KEYS) {
4150
+ for (const member of ERROR_KEYS$1) {
3929
4151
  if (!Object.hasOwn(metadata, member)) continue;
3930
4152
  const text = optionalString(collector, metadata[member], [...errorPath, member]);
3931
4153
  if (text === void 0) valid = false;
@@ -3945,7 +4167,7 @@ function operationBuilder(collector, stage, scope) {
3945
4167
  return token;
3946
4168
  };
3947
4169
  const path = ["operations"];
3948
- const config = take(collector, snapshotRecord(input, OPERATION_KEYS, path), OPERATION_KEYS);
4170
+ const config = take(collector, snapshotRecord(input, OPERATION_KEYS$1, path), OPERATION_KEYS$1);
3949
4171
  if (config === void 0) return reject();
3950
4172
  const descriptor = config.input;
3951
4173
  if (!isTypeDescriptor(descriptor) || descriptor.kind !== "input") {
@@ -4399,6 +4621,776 @@ function defineDocumentModelFamily(config) {
4399
4621
  return token;
4400
4622
  }
4401
4623
  //#endregion
4624
+ //#region src/definition/compiler/module-definition.ts
4625
+ /**
4626
+ * Why `definition` cannot serve the module it is attached to: another
4627
+ * document type, or no specification for the module's version.
4628
+ */
4629
+ function definitionModuleMismatch(definition, module, path) {
4630
+ if (definition.model.documentType !== module.documentType) return {
4631
+ code: "PH-DM-DECLARATION-INVALID",
4632
+ path: [
4633
+ ...path,
4634
+ "model",
4635
+ "documentType"
4636
+ ],
4637
+ message: "The structured definition and the stored model describe different document types.",
4638
+ expected: module.documentType,
4639
+ received: definition.model.documentType,
4640
+ repair: "Materialize the module and its definition from the same declaration."
4641
+ };
4642
+ const { version } = module;
4643
+ if (version !== void 0 && !definition.specifications.some((entry) => entry.version === version)) return {
4644
+ code: "PH-DM-DECLARATION-INVALID",
4645
+ path: [...path, "specifications"],
4646
+ message: `The specification history carries no version ${version}, which is the version this module serves.`,
4647
+ expected: `a specification for version ${version}`,
4648
+ received: definition.specifications.map((entry) => String(entry.version)).join(", "),
4649
+ repair: "Compose the versions with defineDocumentModelFamily so every module carries the complete history."
4650
+ };
4651
+ }
4652
+ //#endregion
4653
+ //#region src/definition/kernel/graphql-ast.ts
4654
+ function compatibilityDiagnostic(path, message, detail = {}) {
4655
+ return kernelDiagnostics.create({
4656
+ code: "PH-DEF-COMPATIBILITY-INVALID",
4657
+ path,
4658
+ message,
4659
+ ...detail.expected !== void 0 && { expected: detail.expected },
4660
+ ...detail.received !== void 0 && { received: detail.received },
4661
+ ...detail.related !== void 0 && { related: detail.related },
4662
+ repair: detail.repair ?? "Regenerate the compatibility AST from the schema this declaration replaces, or change the descriptors to agree with it."
4663
+ });
4664
+ }
4665
+ const ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/;
4666
+ function validateLocationFreeDocument(value, path) {
4667
+ const diagnostics = [];
4668
+ const refuse = (at, message, received) => diagnostics.push(compatibilityDiagnostic(at, message, {
4669
+ expected: "JSON data",
4670
+ received,
4671
+ repair: "Keep only JSON data in the AST: strings, finite numbers, booleans, null, plain arrays and plain objects with data properties."
4672
+ }));
4673
+ const ancestors = /* @__PURE__ */ new Set();
4674
+ const visitProperty = (owner, key, at) => {
4675
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
4676
+ if (descriptor === void 0) refuse(at, "A compatibility AST array must not have holes.", "hole");
4677
+ else if (!("value" in descriptor)) refuse(at, "A compatibility AST must hold data properties, not accessors.", "accessor");
4678
+ else visit(descriptor.value, at);
4679
+ };
4680
+ const visit = (node, at) => {
4681
+ if (node === null || typeof node === "string" || typeof node === "boolean") return;
4682
+ if (typeof node === "number") {
4683
+ if (!Number.isFinite(node)) refuse(at, "A compatibility AST number must be finite.", String(node));
4684
+ return;
4685
+ }
4686
+ if (typeof node !== "object") {
4687
+ refuse(at, `A compatibility AST must contain JSON data only, received ${typeof node}.`, typeof node);
4688
+ return;
4689
+ }
4690
+ if (ancestors.has(node)) {
4691
+ refuse(at, "A compatibility AST must not contain a cycle.", "cycle");
4692
+ return;
4693
+ }
4694
+ const prototype = Object.getPrototypeOf(node);
4695
+ const isArray = Array.isArray(node);
4696
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
4697
+ refuse(at, "A compatibility AST must hold plain arrays and plain objects only.", describeReceived(node));
4698
+ return;
4699
+ }
4700
+ ancestors.add(node);
4701
+ for (const key of Reflect.ownKeys(node)) if (typeof key === "symbol") refuse(at, "A compatibility AST must not have symbol keys.", "symbol");
4702
+ else if (isArray) {
4703
+ if (key !== "length" && !ARRAY_INDEX.test(key)) refuse([...at, key], "A compatibility AST array must hold only its items.", key);
4704
+ } else if (key === "loc") diagnostics.push(compatibilityDiagnostic([...at, key], "A compatibility AST must be location free.", {
4705
+ expected: "no loc property",
4706
+ received: "loc",
4707
+ repair: "Strip every loc property from the AST."
4708
+ }));
4709
+ else visitProperty(node, key, [...at, key]);
4710
+ if (isArray) for (let index = 0; index < node.length; index += 1) visitProperty(node, index, [...at, index]);
4711
+ ancestors.delete(node);
4712
+ };
4713
+ visit(value, path);
4714
+ return diagnostics;
4715
+ }
4716
+ //#endregion
4717
+ //#region src/definition/compiler/wire-shape.ts
4718
+ const BUILT_IN_SCALARS = [
4719
+ "ID",
4720
+ "String",
4721
+ "Boolean",
4722
+ "Int",
4723
+ "Float"
4724
+ ];
4725
+ const CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);
4726
+ const MODEL_SCALARS = /* @__PURE__ */ new Set([...BUILT_IN_SCALARS, ...CATALOG_SCALARS]);
4727
+ const HOST_ONLY_SCALARS = new Set(scalarCatalog.map(({ name }) => name).filter((name) => !MODEL_SCALARS.has(name)));
4728
+ const SCALAR_REPRESENTATIONS = [
4729
+ "string",
4730
+ "number",
4731
+ "boolean",
4732
+ "json-object",
4733
+ "json",
4734
+ "opaque"
4735
+ ];
4736
+ var ShapeChecker = class {
4737
+ collector = new DefinitionDiagnosticCollector(compilerDiagnostics);
4738
+ packageScalars = /* @__PURE__ */ new Set();
4739
+ fail(path, message, expected, received) {
4740
+ this.collector.add({
4741
+ code: "PH-DM-DECLARATION-INVALID",
4742
+ path,
4743
+ message,
4744
+ expected,
4745
+ received: typeof received === "string" ? received : typeof received === "number" || typeof received === "boolean" ? String(received) : describeReceived(received),
4746
+ repair: "Produce the definition with materialize or a document-model/tooling adapter; a hand-edited wire definition is not accepted."
4747
+ });
4748
+ }
4749
+ record(value, keys, path) {
4750
+ const snapshot = snapshotRecord(value, keys, path);
4751
+ if (snapshot.ok) return snapshot.value;
4752
+ return this.fail(snapshot.path, `This node is not a plain object with the V1 members (${snapshot.reason}).`, keys.join(", "), rejectionReceived(snapshot));
4753
+ }
4754
+ array(value, path) {
4755
+ const snapshot = snapshotArray(value, path);
4756
+ if (snapshot.ok) return snapshot.value;
4757
+ return this.fail(snapshot.path, "This node must be an array.", "an array", rejectionReceived(snapshot));
4758
+ }
4759
+ string(value, path) {
4760
+ if (typeof value === "string") return value;
4761
+ return this.fail(path, "This member must be a string.", "string", value);
4762
+ }
4763
+ nullableString(value, path) {
4764
+ if (value === null || typeof value === "string") return;
4765
+ this.fail(path, "This member must be a string or null.", "string | null", value);
4766
+ }
4767
+ literal(value, expected, path) {
4768
+ if (value === expected) return;
4769
+ this.fail(path, "This member has a fixed value.", String(expected), value);
4770
+ }
4771
+ oneOf(value, allowed, path) {
4772
+ if (allowed.includes(value)) return value;
4773
+ return this.fail(path, "This member is outside its closed set.", allowed.join(" | "), value);
4774
+ }
4775
+ json(value, path) {
4776
+ try {
4777
+ canonicalJson(value);
4778
+ } catch (error) {
4779
+ return this.fail(path, `This member must be a JSON value: ${error instanceof Error ? error.message : String(error)}`, "a JSON value", value);
4780
+ }
4781
+ return value;
4782
+ }
4783
+ graphQLName(value, path) {
4784
+ if (isGraphQLName(value)) return value;
4785
+ return this.fail(path, "This member must be a GraphQL name.", "a GraphQL name", value);
4786
+ }
4787
+ rejectHostOnlyScalar(value, path) {
4788
+ if (typeof value !== "string" || !HOST_ONLY_SCALARS.has(value)) return false;
4789
+ this.collector.add({
4790
+ code: "PH-SCALAR-INTERNAL",
4791
+ definition: {
4792
+ kind: "scalar",
4793
+ key: value
4794
+ },
4795
+ path,
4796
+ message: `${value} is internal to the reactor host. A document model cannot use it.`,
4797
+ received: value,
4798
+ repair: "Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one."
4799
+ });
4800
+ return true;
4801
+ }
4802
+ };
4803
+ function typeReference(check, value, path) {
4804
+ const kind = value?.kind;
4805
+ const node = kind === "list" ? check.record(value, [
4806
+ "kind",
4807
+ "required",
4808
+ "item"
4809
+ ], path) : check.record(value, [
4810
+ "kind",
4811
+ "name",
4812
+ "required"
4813
+ ], path);
4814
+ if (node === void 0) return;
4815
+ if (typeof node.required !== "boolean") check.fail([...path, "required"], "A type reference records nullability.", "boolean", node.required);
4816
+ if (kind === "list") typeReference(check, node.item, [...path, "item"]);
4817
+ else if (kind === "scalar") {
4818
+ if (check.rejectHostOnlyScalar(node.name, [...path, "name"])) return;
4819
+ if (typeof node.name !== "string" || !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))) check.fail([...path, "name"], "A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.", [...MODEL_SCALARS, ...check.packageScalars].join(" | "), node.name);
4820
+ } else if (kind === "named") check.graphQLName(node.name, [...path, "name"]);
4821
+ else check.fail([...path, "kind"], "A type reference has three kinds.", "scalar | named | list", kind);
4822
+ }
4823
+ function directiveUses(check, value, path) {
4824
+ check.array(value, path)?.forEach((use, index) => {
4825
+ const node = check.record(use, ["name", "arguments"], [...path, index]);
4826
+ if (node === void 0) return;
4827
+ check.graphQLName(node.name, [
4828
+ ...path,
4829
+ index,
4830
+ "name"
4831
+ ]);
4832
+ check.array(node.arguments, [
4833
+ ...path,
4834
+ index,
4835
+ "arguments"
4836
+ ])?.forEach((argument, argumentIndex) => {
4837
+ const at = [
4838
+ ...path,
4839
+ index,
4840
+ "arguments",
4841
+ argumentIndex
4842
+ ];
4843
+ const entry = check.record(argument, ["name", "value"], at);
4844
+ if (entry === void 0) return;
4845
+ check.graphQLName(entry.name, [...at, "name"]);
4846
+ check.json(entry.value, [...at, "value"]);
4847
+ });
4848
+ });
4849
+ }
4850
+ const FIELD_KEYS = [
4851
+ "key",
4852
+ "name",
4853
+ "description",
4854
+ "deprecated",
4855
+ "type"
4856
+ ];
4857
+ function field(check, value, path, input) {
4858
+ const node = check.record(value, [
4859
+ ...FIELD_KEYS,
4860
+ "directives",
4861
+ input ? "defaultValue" : "args"
4862
+ ], path);
4863
+ if (node === void 0) return;
4864
+ check.string(node.key, [...path, "key"]);
4865
+ check.graphQLName(node.name, [...path, "name"]);
4866
+ check.nullableString(node.description, [...path, "description"]);
4867
+ check.nullableString(node.deprecated, [...path, "deprecated"]);
4868
+ typeReference(check, node.type, [...path, "type"]);
4869
+ if (node.directives !== void 0) directiveUses(check, node.directives, [...path, "directives"]);
4870
+ if (input) {
4871
+ if (Object.hasOwn(node, "defaultValue")) check.json(node.defaultValue, [...path, "defaultValue"]);
4872
+ } else if (node.args !== void 0) check.array(node.args, [...path, "args"])?.forEach((argument, index) => field(check, argument, [
4873
+ ...path,
4874
+ "args",
4875
+ index
4876
+ ], true));
4877
+ }
4878
+ function fields(check, value, path, input) {
4879
+ check.array(value, path)?.forEach((entry, index) => field(check, entry, [...path, index], input));
4880
+ }
4881
+ function enumValue(check, value, path) {
4882
+ const node = check.record(value, [
4883
+ "name",
4884
+ "description",
4885
+ "deprecated",
4886
+ "directives"
4887
+ ], path);
4888
+ if (node === void 0) return;
4889
+ check.graphQLName(node.name, [...path, "name"]);
4890
+ check.nullableString(node.description, [...path, "description"]);
4891
+ check.nullableString(node.deprecated, [...path, "deprecated"]);
4892
+ if (node.directives !== void 0) directiveUses(check, node.directives, [...path, "directives"]);
4893
+ }
4894
+ const NAMED_TYPE_MEMBERS = {
4895
+ enum: "values",
4896
+ object: "fields",
4897
+ interface: "fields",
4898
+ input: "fields",
4899
+ union: "members"
4900
+ };
4901
+ function namedType(check, value, path) {
4902
+ const kind = value?.kind;
4903
+ if (typeof kind !== "string" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) return check.fail([...path, "kind"], "A named type has five kinds.", Object.keys(NAMED_TYPE_MEMBERS).join(" | "), kind);
4904
+ const typed = kind;
4905
+ const member = NAMED_TYPE_MEMBERS[typed];
4906
+ const extra = typed === "object" || typed === "interface" ? ["implements"] : typed === "input" ? ["unknownKeys"] : [];
4907
+ const node = check.record(value, [
4908
+ "kind",
4909
+ "name",
4910
+ "description",
4911
+ ...extra,
4912
+ member
4913
+ ], path);
4914
+ if (node === void 0) return void 0;
4915
+ check.nullableString(node.description, [...path, "description"]);
4916
+ const members = check.array(node[member], [...path, member]);
4917
+ switch (typed) {
4918
+ case "enum":
4919
+ members?.forEach((entry, index) => enumValue(check, entry, [
4920
+ ...path,
4921
+ "values",
4922
+ index
4923
+ ]));
4924
+ break;
4925
+ case "union":
4926
+ members?.forEach((entry, index) => check.graphQLName(entry, [
4927
+ ...path,
4928
+ "members",
4929
+ index
4930
+ ]));
4931
+ break;
4932
+ case "input":
4933
+ check.oneOf(node.unknownKeys, ["preserve", "reject"], [...path, "unknownKeys"]);
4934
+ fields(check, node.fields, [...path, "fields"], true);
4935
+ break;
4936
+ default:
4937
+ if (node.implements !== void 0) check.array(node.implements, [...path, "implements"])?.forEach((entry, index) => check.graphQLName(entry, [
4938
+ ...path,
4939
+ "implements",
4940
+ index
4941
+ ]));
4942
+ fields(check, node.fields, [...path, "fields"], false);
4943
+ }
4944
+ return check.graphQLName(node.name, [...path, "name"]);
4945
+ }
4946
+ function examples(check, value, path, keys) {
4947
+ check.array(value, path)?.forEach((entry, index) => {
4948
+ const node = check.record(entry, keys, [...path, index]);
4949
+ if (node === void 0) return;
4950
+ for (const key of keys) check.string(node[key], [
4951
+ ...path,
4952
+ index,
4953
+ key
4954
+ ]);
4955
+ });
4956
+ }
4957
+ function state(check, value, path, scope) {
4958
+ const node = check.record(value, [
4959
+ "root",
4960
+ "initialValue",
4961
+ "examples",
4962
+ "unknownKeys",
4963
+ "materialized"
4964
+ ], path);
4965
+ if (node === void 0) return;
4966
+ if (node.root === null) {
4967
+ if (scope === "global") check.fail([...path, "root"], "A global state always has a root.", "a named type reference", null);
4968
+ if (check.json(node.initialValue, [...path, "initialValue"]) !== void 0) {
4969
+ if (canonicalJson(node.initialValue) !== "{}") check.fail([...path, "initialValue"], "An empty local state carries an exact empty object.", "{}", node.initialValue);
4970
+ }
4971
+ } else {
4972
+ typeReference(check, node.root, [...path, "root"]);
4973
+ check.json(node.initialValue, [...path, "initialValue"]);
4974
+ }
4975
+ check.literal(node.unknownKeys, "preserve", [...path, "unknownKeys"]);
4976
+ examples(check, node.examples, [...path, "examples"], [
4977
+ "id",
4978
+ "key",
4979
+ "value"
4980
+ ]);
4981
+ const materializedPath = [...path, "materialized"];
4982
+ const materialized = check.record(node.materialized, [
4983
+ "schema",
4984
+ "initialValue",
4985
+ "examples"
4986
+ ], materializedPath);
4987
+ if (materialized === void 0) return;
4988
+ const schema = check.string(materialized.schema, [...materializedPath, "schema"]);
4989
+ if (node.root === null && schema !== void 0 && schema !== "") check.fail([...materializedPath, "schema"], "An empty local state materializes an empty schema.", "\"\"", schema);
4990
+ check.string(materialized.initialValue, [...materializedPath, "initialValue"]);
4991
+ examples(check, materialized.examples, [...materializedPath, "examples"], ["id", "value"]);
4992
+ }
4993
+ const OPERATION_KEYS = [
4994
+ "id",
4995
+ "key",
4996
+ "name",
4997
+ "description",
4998
+ "actionType",
4999
+ "creatorKey",
5000
+ "scope",
5001
+ "input",
5002
+ "errors",
5003
+ "examples",
5004
+ "template",
5005
+ "reducer"
5006
+ ];
5007
+ const ERROR_KEYS = [
5008
+ "id",
5009
+ "key",
5010
+ "code",
5011
+ "name",
5012
+ "description",
5013
+ "template"
5014
+ ];
5015
+ function operation(check, value, path) {
5016
+ const node = check.record(value, OPERATION_KEYS, path);
5017
+ if (node === void 0) return;
5018
+ for (const key of [
5019
+ "id",
5020
+ "key",
5021
+ "actionType",
5022
+ "creatorKey"
5023
+ ]) check.string(node[key], [...path, key]);
5024
+ for (const key of [
5025
+ "name",
5026
+ "description",
5027
+ "template",
5028
+ "reducer"
5029
+ ]) check.nullableString(node[key], [...path, key]);
5030
+ check.oneOf(node.scope, ["global", "local"], [...path, "scope"]);
5031
+ if (node.input !== null) {
5032
+ const kind = node.input?.kind;
5033
+ if (kind !== "input") check.fail([
5034
+ ...path,
5035
+ "input",
5036
+ "kind"
5037
+ ], "An operation input is an input type.", "input", kind);
5038
+ else namedType(check, node.input, [...path, "input"]);
5039
+ }
5040
+ check.array(node.errors, [...path, "errors"])?.forEach((entry, index) => {
5041
+ const at = [
5042
+ ...path,
5043
+ "errors",
5044
+ index
5045
+ ];
5046
+ const error = check.record(entry, ERROR_KEYS, at);
5047
+ if (error === void 0) return;
5048
+ check.string(error.id, [...at, "id"]);
5049
+ check.string(error.key, [...at, "key"]);
5050
+ for (const key of [
5051
+ "code",
5052
+ "name",
5053
+ "description",
5054
+ "template"
5055
+ ]) check.nullableString(error[key], [...at, key]);
5056
+ });
5057
+ examples(check, node.examples, [...path, "examples"], [
5058
+ "id",
5059
+ "key",
5060
+ "value"
5061
+ ]);
5062
+ }
5063
+ function storedScalar(check, value, name, path) {
5064
+ const node = check.record(value, [
5065
+ "kind",
5066
+ "formatVersion",
5067
+ "name",
5068
+ "representation",
5069
+ "description",
5070
+ "coercion",
5071
+ "coercionProfile"
5072
+ ], path);
5073
+ if (node === void 0) return;
5074
+ check.literal(node.kind, "powerhouse.scalar", [...path, "kind"]);
5075
+ check.literal(node.formatVersion, 1, [...path, "formatVersion"]);
5076
+ check.literal(node.name, name, [...path, "name"]);
5077
+ check.oneOf(node.representation, SCALAR_REPRESENTATIONS, [...path, "representation"]);
5078
+ check.string(node.description, [...path, "description"]);
5079
+ check.literal(node.coercionProfile, "catalog-v1", [...path, "coercionProfile"]);
5080
+ const coercion = check.record(node.coercion, ["source"], [...path, "coercion"]);
5081
+ if (coercion !== void 0) check.oneOf(coercion.source, ["derived", "explicit"], [
5082
+ ...path,
5083
+ "coercion",
5084
+ "source"
5085
+ ]);
5086
+ }
5087
+ function scalars(check, value, path) {
5088
+ const declared = /* @__PURE__ */ new Set();
5089
+ check.array(value, path)?.forEach((entry, index) => {
5090
+ const at = [...path, index];
5091
+ const isPackage = typeof entry === "object" && entry !== null && Object.hasOwn(entry, "definition");
5092
+ const scalar = check.record(entry, [
5093
+ "name",
5094
+ "implementation",
5095
+ "coercionProfile",
5096
+ "definition"
5097
+ ], at);
5098
+ if (scalar === void 0) return;
5099
+ check.literal(scalar.coercionProfile, "catalog-v1", [...at, "coercionProfile"]);
5100
+ if (check.rejectHostOnlyScalar(scalar.name, [...at, "name"])) return;
5101
+ if (!isPackage) {
5102
+ const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, "name"]);
5103
+ if (name !== void 0) check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [...at, "implementation"]);
5104
+ return;
5105
+ }
5106
+ const name = check.graphQLName(scalar.name, [...at, "name"]);
5107
+ if (name === void 0) return;
5108
+ if (MODEL_SCALARS.has(name) || declared.has(name)) {
5109
+ check.fail([...at, "name"], "A package scalar has a name no catalog scalar, GraphQL built-in, or other package scalar uses.", "an unused GraphQL name", name);
5110
+ return;
5111
+ }
5112
+ check.literal(scalar.implementation, `package#${name}`, [...at, "implementation"]);
5113
+ storedScalar(check, scalar.definition, name, [...at, "definition"]);
5114
+ declared.add(name);
5115
+ });
5116
+ return declared;
5117
+ }
5118
+ function specification(check, value, path) {
5119
+ const node = check.record(value, [
5120
+ "version",
5121
+ "scalars",
5122
+ "graphQLCompatibility",
5123
+ "types",
5124
+ "state",
5125
+ "modules",
5126
+ "changeLog"
5127
+ ], path);
5128
+ if (node === void 0) return;
5129
+ if (typeof node.version !== "number" || !Number.isSafeInteger(node.version) || node.version <= 0) check.fail([...path, "version"], "A specification version is a positive safe integer.", "a positive safe integer", node.version);
5130
+ check.packageScalars = scalars(check, node.scalars, [...path, "scalars"]);
5131
+ if (node.graphQLCompatibility !== null) {
5132
+ const at = [...path, "graphQLCompatibility"];
5133
+ const compatibility = check.record(node.graphQLCompatibility, [
5134
+ "kind",
5135
+ "document",
5136
+ "preserveDefinitionOrder"
5137
+ ], at);
5138
+ if (compatibility !== void 0) {
5139
+ check.literal(compatibility.kind, "graphql-ast-v1", [...at, "kind"]);
5140
+ check.literal(compatibility.preserveDefinitionOrder, true, [...at, "preserveDefinitionOrder"]);
5141
+ check.collector.merge(validateLocationFreeDocument(compatibility.document, [...at, "document"]));
5142
+ }
5143
+ }
5144
+ const declared = /* @__PURE__ */ new Set();
5145
+ check.array(node.types, [...path, "types"])?.forEach((entry, index) => {
5146
+ const name = namedType(check, entry, [
5147
+ ...path,
5148
+ "types",
5149
+ index
5150
+ ]);
5151
+ if (name === void 0) return;
5152
+ if (declared.has(name) || check.packageScalars.has(name)) check.fail([
5153
+ ...path,
5154
+ "types",
5155
+ index,
5156
+ "name"
5157
+ ], "A named type is declared once per specification, and never under a package scalar's name.", "one definition per name", name);
5158
+ declared.add(name);
5159
+ });
5160
+ const stateNode = check.record(node.state, ["global", "local"], [...path, "state"]);
5161
+ if (stateNode !== void 0) for (const scope of ["global", "local"]) {
5162
+ state(check, stateNode[scope], [
5163
+ ...path,
5164
+ "state",
5165
+ scope
5166
+ ], scope);
5167
+ const root = stateNode[scope]?.root;
5168
+ if (typeof root?.name === "string" && !declared.has(root.name)) check.fail([
5169
+ ...path,
5170
+ "state",
5171
+ scope,
5172
+ "root",
5173
+ "name"
5174
+ ], "A state root is declared in this specification's types.", [...declared].join(" | "), root.name);
5175
+ }
5176
+ check.array(node.modules, [...path, "modules"])?.forEach((entry, index) => {
5177
+ const at = [
5178
+ ...path,
5179
+ "modules",
5180
+ index
5181
+ ];
5182
+ const module = check.record(entry, [
5183
+ "id",
5184
+ "key",
5185
+ "name",
5186
+ "description",
5187
+ "operations"
5188
+ ], at);
5189
+ if (module === void 0) return;
5190
+ check.string(module.id, [...at, "id"]);
5191
+ check.string(module.key, [...at, "key"]);
5192
+ check.string(module.name, [...at, "name"]);
5193
+ check.nullableString(module.description, [...at, "description"]);
5194
+ check.array(module.operations, [...at, "operations"])?.forEach((candidate, operationIndex) => operation(check, candidate, [
5195
+ ...at,
5196
+ "operations",
5197
+ operationIndex
5198
+ ]));
5199
+ });
5200
+ check.array(node.changeLog, [...path, "changeLog"])?.forEach((entry, index) => check.string(entry, [
5201
+ ...path,
5202
+ "changeLog",
5203
+ index
5204
+ ]));
5205
+ }
5206
+ function checkDocumentModelDefinitionShape(value, path = []) {
5207
+ const check = new ShapeChecker();
5208
+ const node = check.record(value, [
5209
+ "kind",
5210
+ "formatVersion",
5211
+ "compatibility",
5212
+ "model",
5213
+ "specifications"
5214
+ ], path);
5215
+ if (node === void 0) return check.collector.diagnostics;
5216
+ check.literal(node.kind, "powerhouse.document-model", [...path, "kind"]);
5217
+ check.literal(node.formatVersion, 1, [...path, "formatVersion"]);
5218
+ const compatibilityPath = [...path, "compatibility"];
5219
+ const compatibility = check.record(node.compatibility, [
5220
+ "identity",
5221
+ "scalarCoercion",
5222
+ "serialization"
5223
+ ], compatibilityPath);
5224
+ if (compatibility !== void 0) {
5225
+ check.oneOf(compatibility.identity, ["derived-v1", "explicit-schema-first"], [...compatibilityPath, "identity"]);
5226
+ check.literal(compatibility.scalarCoercion, "catalog-v1", [...compatibilityPath, "scalarCoercion"]);
5227
+ check.oneOf(compatibility.serialization, ["canonical-v1", "explicit-schema-first"], [...compatibilityPath, "serialization"]);
5228
+ }
5229
+ const modelPath = [...path, "model"];
5230
+ const model = check.record(node.model, [
5231
+ "documentType",
5232
+ "graphQLName",
5233
+ "name",
5234
+ "description",
5235
+ "extension",
5236
+ "author"
5237
+ ], modelPath);
5238
+ if (model !== void 0) {
5239
+ if (check.string(model.documentType, [...modelPath, "documentType"]) === "") check.fail([...modelPath, "documentType"], "A document type is not empty.", "a document type", "\"\"");
5240
+ check.graphQLName(model.graphQLName, [...modelPath, "graphQLName"]);
5241
+ for (const key of [
5242
+ "name",
5243
+ "description",
5244
+ "extension"
5245
+ ]) check.string(model[key], [...modelPath, key]);
5246
+ const author = check.record(model.author, ["name", "website"], [...modelPath, "author"]);
5247
+ if (author !== void 0) {
5248
+ check.string(author.name, [
5249
+ ...modelPath,
5250
+ "author",
5251
+ "name"
5252
+ ]);
5253
+ check.nullableString(author.website, [
5254
+ ...modelPath,
5255
+ "author",
5256
+ "website"
5257
+ ]);
5258
+ }
5259
+ }
5260
+ const specifications = check.array(node.specifications, [...path, "specifications"]);
5261
+ if (specifications?.length === 0) check.fail([...path, "specifications"], "A definition carries at least one specification.", "a nonempty specification history", "an empty array");
5262
+ specifications?.forEach((entry, index) => specification(check, entry, [
5263
+ ...path,
5264
+ "specifications",
5265
+ index
5266
+ ]));
5267
+ return check.collector.diagnostics;
5268
+ }
5269
+ //#endregion
5270
+ //#region src/definition/runtime/inspection.ts
5271
+ const REPAIR = "Materialize the module and its definition from the same declaration, and export the module materialize returned.";
5272
+ function keepsSchemaFirstText(definition, specification) {
5273
+ return definition.compatibility.serialization !== "canonical-v1" || specification.graphQLCompatibility !== null;
5274
+ }
5275
+ const checkedDefinitions = /* @__PURE__ */ new WeakMap();
5276
+ function readDefinition(module) {
5277
+ let read;
5278
+ try {
5279
+ read = module.definition;
5280
+ } catch (error) {
5281
+ return unreadable(error);
5282
+ }
5283
+ if (read === void 0) return { kind: "absent" };
5284
+ if (typeof read !== "object" || read === null) return checkedSnapshot(read);
5285
+ let checked = checkedDefinitions.get(read);
5286
+ if (checked === void 0) {
5287
+ checked = checkedSnapshot(read);
5288
+ checkedDefinitions.set(read, checked);
5289
+ }
5290
+ return checked;
5291
+ }
5292
+ function checkedSnapshot(read) {
5293
+ try {
5294
+ const value = structuredClone(read);
5295
+ const diagnostics = checkDocumentModelDefinitionShape(value, ["definition"]);
5296
+ if (diagnostics.length > 0) return {
5297
+ kind: "invalid",
5298
+ diagnostics
5299
+ };
5300
+ return {
5301
+ kind: "read",
5302
+ value: deepFreeze(value)
5303
+ };
5304
+ } catch (error) {
5305
+ return unreadable(error);
5306
+ }
5307
+ }
5308
+ function deepFreeze(value) {
5309
+ const pending = [value];
5310
+ while (pending.length > 0) {
5311
+ const next = pending.pop();
5312
+ if (typeof next !== "object" || next === null || Object.isFrozen(next)) continue;
5313
+ Object.freeze(next);
5314
+ pending.push(...Object.values(next));
5315
+ }
5316
+ return value;
5317
+ }
5318
+ function unreadable(error) {
5319
+ const thrown = describeThrown(error);
5320
+ const collector = new DefinitionDiagnosticCollector(compilerDiagnostics);
5321
+ collector.add({
5322
+ code: "PH-DM-DECLARATION-INVALID",
5323
+ path: ["definition"],
5324
+ message: `The structured definition cannot be read: ${thrown.message}`,
5325
+ expected: "a finite, plain JSON definition",
5326
+ received: thrown.name,
5327
+ repair: REPAIR
5328
+ });
5329
+ return {
5330
+ kind: "invalid",
5331
+ diagnostics: collector.diagnostics
5332
+ };
5333
+ }
5334
+ function describeThrown(error) {
5335
+ try {
5336
+ return error instanceof Error ? {
5337
+ message: String(error.message),
5338
+ name: String(error.name)
5339
+ } : {
5340
+ message: String(error),
5341
+ name: typeof error
5342
+ };
5343
+ } catch {
5344
+ return {
5345
+ message: "a thrown value that cannot be described",
5346
+ name: typeof error
5347
+ };
5348
+ }
5349
+ }
5350
+ /**
5351
+ * Reads the structured definition a module carries. `structured` holds the
5352
+ * specification the stored path serves, `specifications.at(-1)`. A module
5353
+ * without a valid, matching, canonically serialized definition is served from
5354
+ * its stored model.
5355
+ */
5356
+ function inspectDocumentModelDefinition(module) {
5357
+ const read = readDefinition(module);
5358
+ if (read.kind === "absent") return {
5359
+ kind: "stored",
5360
+ reason: "absent"
5361
+ };
5362
+ if (read.kind === "invalid") return {
5363
+ kind: "stored",
5364
+ reason: "invalid",
5365
+ diagnostics: read.diagnostics
5366
+ };
5367
+ const definition = read.value;
5368
+ const { version } = module;
5369
+ const mismatch = definitionModuleMismatch(definition, {
5370
+ documentType: module.documentModel.global.id,
5371
+ version: typeof version === "number" ? version : void 0
5372
+ }, ["definition"]);
5373
+ if (mismatch !== void 0) {
5374
+ const collector = new DefinitionDiagnosticCollector(compilerDiagnostics);
5375
+ collector.add(mismatch);
5376
+ return {
5377
+ kind: "stored",
5378
+ reason: "mismatch",
5379
+ diagnostics: collector.diagnostics
5380
+ };
5381
+ }
5382
+ const specification = definition.specifications.at(-1);
5383
+ if (keepsSchemaFirstText(definition, specification)) return {
5384
+ kind: "stored",
5385
+ reason: "retained"
5386
+ };
5387
+ return {
5388
+ kind: "structured",
5389
+ definition,
5390
+ specification
5391
+ };
5392
+ }
5393
+ //#endregion
4402
5394
  //#region src/definition/runtime/materialize.ts
4403
5395
  function cloneJson(value) {
4404
5396
  return JSON.parse(JSON.stringify(value));
@@ -4647,6 +5639,6 @@ function materialize(definition) {
4647
5639
  return materializeFamily(family.versions, copyUpgradeManifest(family.upgradeManifest));
4648
5640
  }
4649
5641
  //#endregion
4650
- export { ConsoleLogger, DefinitionError, DocumentModelController, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, defineDocumentModel, defineDocumentModelFamily, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, isDocumentOfType, isStateOfType, logger, materialize, ph, setErrorHandler, setLogLevel };
5642
+ export { ConsoleLogger, DefinitionError, DocumentModelController, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, defineDocumentModel, defineDocumentModelFamily, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, inspectDocumentModelDefinition, isDocumentOfType, isStateOfType, logger, materialize, ph, projectDocumentModelGraphQL, setErrorHandler, setLogLevel };
4651
5643
 
4652
5644
  //# sourceMappingURL=index.js.map