document-model 6.2.3-dev.95 → 6.2.3-dev.97

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/tooling.mjs CHANGED
@@ -4,7 +4,8 @@ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "n
4
4
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
5
5
  import { z } from "zod";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
- import { DEFAULT_AUTHORING_MODE, parseDefinitionSourcesConfig } from "@powerhousedao/shared/clis/definition-sources";
7
+ import { COMMONJS_DEFINITION_SOURCE, COMMONJS_DEFINITION_SOURCE_REPAIR, DEFAULT_AUTHORING_MODE, DEFINITION_SOURCE_EXTENSION, parseDefinitionSourcesConfig } from "@powerhousedao/shared/clis/definition-sources";
8
+ import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
8
9
  import { camelCase, constantCase, pascalCase } from "change-case";
9
10
  //#region src/definition/kernel/hashes.ts
10
11
  function rotateRight(value, shift) {
@@ -209,9 +210,54 @@ function canonicalDigest(value) {
209
210
  function compareCodeUnits(a, b) {
210
211
  return a < b ? -1 : a > b ? 1 : 0;
211
212
  }
213
+ const DIGIT_0 = 48;
214
+ const DIGIT_9 = 57;
215
+ function isDigit(code) {
216
+ return DIGIT_0 <= code && code <= DIGIT_9;
217
+ }
218
+ /**
219
+ * graphql-js's `naturalCompare`, which `lexicographicSortSchema` sorts a
220
+ * generated schema with: runs of digits compare as numbers, so `item2`
221
+ * precedes `item10`. Copied, not imported, so a model never loads `graphql`.
222
+ */
223
+ function compareGeneratedOrder(a, b) {
224
+ let aIndex = 0;
225
+ let bIndex = 0;
226
+ while (aIndex < a.length && bIndex < b.length) {
227
+ let aChar = a.charCodeAt(aIndex);
228
+ let bChar = b.charCodeAt(bIndex);
229
+ if (isDigit(aChar) && isDigit(bChar)) {
230
+ let aNumber = 0;
231
+ do {
232
+ ++aIndex;
233
+ aNumber = aNumber * 10 + aChar - DIGIT_0;
234
+ aChar = a.charCodeAt(aIndex);
235
+ } while (isDigit(aChar) && aNumber > 0);
236
+ let bNumber = 0;
237
+ do {
238
+ ++bIndex;
239
+ bNumber = bNumber * 10 + bChar - DIGIT_0;
240
+ bChar = b.charCodeAt(bIndex);
241
+ } while (isDigit(bChar) && bNumber > 0);
242
+ if (aNumber !== bNumber) return aNumber < bNumber ? -1 : 1;
243
+ } else {
244
+ if (aChar !== bChar) return aChar < bChar ? -1 : 1;
245
+ ++aIndex;
246
+ ++bIndex;
247
+ }
248
+ }
249
+ return a.length - b.length;
250
+ }
251
+ const EMPTY_INPUT_FIELD_NAME = "_empty";
212
252
  function isGraphQLName(value) {
213
253
  return typeof value === "string" && /^[_A-Za-z][_0-9A-Za-z]*$/.test(value);
214
254
  }
255
+ function isAuthoredSchemaName(value) {
256
+ return isGraphQLName(value) && !value.startsWith("__");
257
+ }
258
+ function isEnumValueName(value) {
259
+ return isAuthoredSchemaName(value) && value !== "true" && value !== "false" && value !== "null";
260
+ }
215
261
  function isNFC(value) {
216
262
  return value.normalize("NFC") === value;
217
263
  }
@@ -339,7 +385,10 @@ function formatPointer(path) {
339
385
  return path.map((segment) => `/${String(segment).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
340
386
  }
341
387
  function formatSource(source) {
342
- if (source === void 0) return "(no source)";
388
+ return source === void 0 ? "(no source)" : formatDefinitionSource(source);
389
+ }
390
+ /** @experimental A source as `specifier#/export/path`, each segment escaped as a JSON Pointer token. */
391
+ function formatDefinitionSource(source) {
343
392
  const exportPath = source.exportPath ?? [];
344
393
  return exportPath.length === 0 ? source.specifier : `${source.specifier}#${formatPointer(exportPath)}`;
345
394
  }
@@ -694,7 +743,7 @@ const schema = z.object({
694
743
  });
695
744
  //#endregion
696
745
  //#region src/scalars/catalog.ts
697
- const declarations = [
746
+ const declarations$1 = [
698
747
  unknownScalar,
699
748
  dateTimeScalar,
700
749
  addressScalar,
@@ -750,7 +799,7 @@ const declarations = [
750
799
  representation: "json-object"
751
800
  })
752
801
  ];
753
- const scalarCatalog = Object.freeze([...declarations]);
802
+ const scalarCatalog = Object.freeze([...declarations$1]);
754
803
  new Map(scalarCatalog.map((definition) => [definition.name, definition]));
755
804
  const documentModelScalars = Object.freeze(scalarCatalog.filter((definition) => definition.typescriptType !== null && definition.zodSource !== null));
756
805
  //#endregion
@@ -1077,6 +1126,62 @@ const kernelDiagnostics = defineDiagnosticCatalog({
1077
1126
  }
1078
1127
  });
1079
1128
  //#endregion
1129
+ //#region src/definition/kernel/equals-pattern.ts
1130
+ /**
1131
+ * The regular expression source the generator writes for `@equals(value: v)`.
1132
+ * The plugin fills its template `/^$1$/` with `String.prototype.replace`, so
1133
+ * `v` is inserted unescaped and its replacement tokens (`$&`, `` $` ``, `$'`,
1134
+ * `$$`) are expanded first.
1135
+ */
1136
+ function equalsPattern(value) {
1137
+ return "/^$1$/".replace("$1", value).slice(1, -1);
1138
+ }
1139
+ const LINE_TERMINATORS = /* @__PURE__ */ new Set([
1140
+ "\n",
1141
+ "\r",
1142
+ "\u2028",
1143
+ "\u2029"
1144
+ ]);
1145
+ /**
1146
+ * Why an `@equals` pattern cannot be validated the way the generator does,
1147
+ * if it cannot. The generator writes the pattern, as `equalsPattern`
1148
+ * expands it, into a regex literal: a `/` outside a character class ends
1149
+ * that literal, and a line terminator cannot appear in one, so either leaves
1150
+ * generated code that does not compile or does not validate.
1151
+ */
1152
+ function equalsPatternProblem(pattern) {
1153
+ const expected = "a regular expression pattern the generator can write as /^pattern$/";
1154
+ const source = equalsPattern(pattern);
1155
+ let inClass = false;
1156
+ for (let index = 0; index < source.length; index++) {
1157
+ const character = source[index];
1158
+ const escaped = character === "\\";
1159
+ if (escaped) index++;
1160
+ if (LINE_TERMINATORS.has(source[index])) return {
1161
+ message: "The @equals pattern contains a line terminator, which a regular expression literal cannot hold.",
1162
+ expected,
1163
+ repair: "Write the line terminator as an escape such as \\n, which the regular expression reads the same way."
1164
+ };
1165
+ if (escaped) continue;
1166
+ if (character === "[") inClass = true;
1167
+ else if (character === "]") inClass = false;
1168
+ else if (character === "/" && !inClass) return {
1169
+ message: "The @equals pattern contains a / outside a character class, which ends the generated regular expression literal.",
1170
+ expected,
1171
+ repair: "Escape the slash as \\/ (written \"\\\\/\" in a JavaScript string), or put it in a character class such as [/]."
1172
+ };
1173
+ }
1174
+ try {
1175
+ new RegExp(source);
1176
+ } catch (error) {
1177
+ return {
1178
+ message: `The @equals pattern is not a valid regular expression: ${error instanceof Error ? error.message : String(error)}`,
1179
+ expected,
1180
+ repair: "Fix the pattern, or escape the characters that have a meaning in a regular expression."
1181
+ };
1182
+ }
1183
+ }
1184
+ //#endregion
1080
1185
  //#region src/definition/kernel/graphql-ast.ts
1081
1186
  const AST_KINDS = {
1082
1187
  object: "ObjectTypeDefinition",
@@ -1317,116 +1422,128 @@ function validateLocationFreeDocument(value, path) {
1317
1422
  visit(value, path);
1318
1423
  return diagnostics;
1319
1424
  }
1425
+ function definitionEquals(field) {
1426
+ const value = field.directives?.find((directive) => directive.name === "equals")?.arguments.find((argument) => argument.name === "value")?.value;
1427
+ return typeof value === "string" ? value : null;
1428
+ }
1320
1429
  //#endregion
1321
- //#region src/definition/compiler/diagnostic-codes.ts
1322
- const compilerDiagnostics = defineDiagnosticCatalog({
1323
- "PH-DM-DUPLICATE-ACTION": {
1430
+ //#region src/definition/dsl/diagnostic-codes.ts
1431
+ const dslDiagnostics = defineDiagnosticCatalog({
1432
+ "PH-DEF-FIELD-OPTION-UNSUPPORTED": {
1324
1433
  severity: "error",
1325
1434
  phase: "definition",
1326
- meaning: "Two operations derive the same persisted action type, or an operation derives one the document runtime owns"
1435
+ meaning: "A field use contains an option its builder or its position does not support"
1327
1436
  },
1328
- "PH-DM-DUPLICATE-NAME": {
1437
+ "PH-DEF-TYPE-AS-FIELD": {
1329
1438
  severity: "error",
1330
1439
  phase: "definition",
1331
- meaning: "Two declarations derive the same module, GraphQL type, or creator name"
1440
+ meaning: "A named type is used as a field without ph.ref"
1332
1441
  },
1333
- "PH-DM-IDENTITY-INVALID": {
1442
+ "PH-DEF-NAME-INVALID": {
1334
1443
  severity: "error",
1335
1444
  phase: "definition",
1336
- meaning: "An identity segment, compatibility ID, or derived UUID violates the V1 contract"
1445
+ meaning: "An authored GraphQL type, field, or enum value name is lexically invalid or reserved"
1337
1446
  },
1338
- "PH-DM-DECLARATION-INVALID": {
1447
+ "PH-DEF-FIELD-INVALID": {
1339
1448
  severity: "error",
1340
1449
  phase: "definition",
1341
- meaning: "A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged"
1450
+ meaning: "A field position holds a value that is neither a field use nor a named type"
1342
1451
  },
1343
- "PH-DM-DEFAULT-UNSUPPORTED": {
1452
+ "PH-DEF-REFERENCE-TARGET-INVALID": {
1344
1453
  severity: "error",
1345
1454
  phase: "definition",
1346
- meaning: "A document state field declares a GraphQL default value"
1455
+ meaning: "A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input"
1347
1456
  },
1348
- "PH-DM-INTERFACE-INVALID": {
1457
+ "PH-DEF-ENUM-VALUES-INVALID": {
1349
1458
  severity: "error",
1350
1459
  phase: "definition",
1351
- meaning: "An object or interface does not satisfy an implemented interface's fields or ancestor requirements"
1460
+ meaning: "An enum declares no values, a duplicate value, or a reserved value"
1352
1461
  },
1353
- "PH-DM-INPUT-CYCLE": {
1462
+ "PH-DEF-UNION-MEMBERS-INVALID": {
1354
1463
  severity: "error",
1355
1464
  phase: "definition",
1356
- meaning: "An input type contains itself through singular non-null input fields, so no finite value satisfies it"
1465
+ meaning: "A union declares no members, a duplicate member, or a member that is not a ph.object"
1357
1466
  },
1358
- "PH-DM-TYPE-POSITION-INVALID": {
1467
+ "PH-DEF-IMPLEMENTS-INVALID": {
1359
1468
  severity: "error",
1360
1469
  phase: "definition",
1361
- meaning: "An input type is referenced from an output position, or an output type from an input position"
1470
+ meaning: "An object or an interface implements something that is not a ph.interface, or the same interface twice"
1362
1471
  },
1363
- "PH-DM-INITIAL-VALUE-INVALID": {
1472
+ "PH-SCALAR-FACTORY-AS-FIELD": {
1364
1473
  severity: "error",
1365
1474
  phase: "definition",
1366
- meaning: "A scope initial value cannot produce a stored JSON string, or its own state validator rejects it"
1475
+ meaning: "A scalar field-use factory is used as a field without being called"
1367
1476
  },
1368
- "PH-SCALAR-DUPLICATE-NAME": {
1477
+ "PH-SCALAR-INTERNAL": {
1369
1478
  severity: "error",
1370
1479
  phase: "definition",
1371
- meaning: "Two different project scalars of one model claim one name"
1372
- }
1373
- }, defineDiagnosticCatalog({
1374
- "PH-DEF-FIELD-OPTION-UNSUPPORTED": {
1480
+ meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
1481
+ },
1482
+ "PH-SCALAR-DEFINITION-INVALID": {
1375
1483
  severity: "error",
1376
1484
  phase: "definition",
1377
- meaning: "A field use contains an option its builder or its position does not support"
1485
+ meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
1378
1486
  },
1379
- "PH-DEF-TYPE-AS-FIELD": {
1487
+ "PH-SCALAR-UNKNOWN": {
1380
1488
  severity: "error",
1381
1489
  phase: "definition",
1382
- meaning: "A named type is used as a field without ph.ref"
1490
+ meaning: "A ph.<Scalar>() factory names no catalog scalar"
1491
+ }
1492
+ }, kernelDiagnostics);
1493
+ //#endregion
1494
+ //#region src/definition/compiler/diagnostic-codes.ts
1495
+ const compilerDiagnostics = defineDiagnosticCatalog({
1496
+ "PH-DM-DUPLICATE-ACTION": {
1497
+ severity: "error",
1498
+ phase: "definition",
1499
+ meaning: "Two operations derive the same persisted action type, or an operation derives one the document runtime owns"
1383
1500
  },
1384
- "PH-DEF-NAME-INVALID": {
1501
+ "PH-DM-DUPLICATE-NAME": {
1385
1502
  severity: "error",
1386
1503
  phase: "definition",
1387
- meaning: "An authored GraphQL type, field, or enum value name is lexically invalid or reserved"
1504
+ meaning: "Two declarations derive the same module, GraphQL type, or creator name"
1388
1505
  },
1389
- "PH-DEF-FIELD-INVALID": {
1506
+ "PH-DM-IDENTITY-INVALID": {
1390
1507
  severity: "error",
1391
1508
  phase: "definition",
1392
- meaning: "A field position holds a value that is neither a field use nor a named type"
1509
+ meaning: "An identity segment, compatibility ID, or derived UUID violates the V1 contract"
1393
1510
  },
1394
- "PH-DEF-REFERENCE-TARGET-INVALID": {
1511
+ "PH-DM-DECLARATION-INVALID": {
1395
1512
  severity: "error",
1396
1513
  phase: "definition",
1397
- meaning: "A ph.ref target is not a named type: a field use, another reference, undefined, or an anonymous input"
1514
+ meaning: "A model, module, operation, error, example, version, or family declaration member is absent, malformed, unsupported, or forged"
1398
1515
  },
1399
- "PH-DEF-ENUM-VALUES-INVALID": {
1516
+ "PH-DM-DEFAULT-UNSUPPORTED": {
1400
1517
  severity: "error",
1401
1518
  phase: "definition",
1402
- meaning: "An enum declares no values, a duplicate value, or a reserved value"
1519
+ meaning: "A document state field declares a GraphQL default value"
1403
1520
  },
1404
- "PH-DEF-UNION-MEMBERS-INVALID": {
1521
+ "PH-DM-INTERFACE-INVALID": {
1405
1522
  severity: "error",
1406
1523
  phase: "definition",
1407
- meaning: "A union declares no members, a duplicate member, or a member that is not a ph.object"
1524
+ meaning: "An object or interface does not satisfy an implemented interface's fields or ancestor requirements"
1408
1525
  },
1409
- "PH-DEF-IMPLEMENTS-INVALID": {
1526
+ "PH-DM-INPUT-CYCLE": {
1410
1527
  severity: "error",
1411
1528
  phase: "definition",
1412
- meaning: "An object or an interface implements something that is not a ph.interface, or the same interface twice"
1529
+ meaning: "An input type contains itself through singular non-null input fields, so no finite value satisfies it"
1413
1530
  },
1414
- "PH-SCALAR-FACTORY-AS-FIELD": {
1531
+ "PH-DM-TYPE-POSITION-INVALID": {
1415
1532
  severity: "error",
1416
1533
  phase: "definition",
1417
- meaning: "A scalar field-use factory is used as a field without being called"
1534
+ meaning: "An input type is referenced from an output position, or an output type from an input position"
1418
1535
  },
1419
- "PH-SCALAR-INTERNAL": {
1536
+ "PH-DM-INITIAL-VALUE-INVALID": {
1420
1537
  severity: "error",
1421
1538
  phase: "definition",
1422
- meaning: "A field uses a catalog scalar that only the reactor host declares, such as JSONObject"
1539
+ meaning: "A scope initial value cannot produce a stored JSON string, or its own state validator rejects it"
1423
1540
  },
1424
- "PH-SCALAR-DEFINITION-INVALID": {
1541
+ "PH-SCALAR-DUPLICATE-NAME": {
1425
1542
  severity: "error",
1426
1543
  phase: "definition",
1427
- meaning: "ph.scalar received a value that is not a scalar definition of this release's format"
1544
+ meaning: "Two different project scalars of one model claim one name"
1428
1545
  }
1429
- }, kernelDiagnostics));
1546
+ }, dslDiagnostics);
1430
1547
  //#endregion
1431
1548
  //#region src/definition/compiler/wire-shape.ts
1432
1549
  const BUILT_IN_SCALARS$1 = [
@@ -1612,7 +1729,7 @@ const NAMED_TYPE_MEMBERS = {
1612
1729
  input: "fields",
1613
1730
  union: "members"
1614
1731
  };
1615
- function namedType$1(check, value, path) {
1732
+ function namedType$2(check, value, path) {
1616
1733
  const kind = value?.kind;
1617
1734
  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);
1618
1735
  const typed = kind;
@@ -1749,7 +1866,7 @@ function operation(check, value, path) {
1749
1866
  "input",
1750
1867
  "kind"
1751
1868
  ], "An operation input is an input type.", "input", kind);
1752
- else namedType$1(check, node.input, [...path, "input"]);
1869
+ else namedType$2(check, node.input, [...path, "input"]);
1753
1870
  }
1754
1871
  check.array(node.errors, [...path, "errors"])?.forEach((entry, index) => {
1755
1872
  const at = [
@@ -1857,7 +1974,7 @@ function specification(check, value, path) {
1857
1974
  }
1858
1975
  const declared = /* @__PURE__ */ new Set();
1859
1976
  check.array(node.types, [...path, "types"])?.forEach((entry, index) => {
1860
- const name = namedType$1(check, entry, [
1977
+ const name = namedType$2(check, entry, [
1861
1978
  ...path,
1862
1979
  "types",
1863
1980
  index
@@ -2197,10 +2314,6 @@ function isCanonicalText(value) {
2197
2314
  }
2198
2315
  return isNFC(value);
2199
2316
  }
2200
- function isWithin(root, path) {
2201
- const child = relative(root, path);
2202
- return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
2203
- }
2204
2317
  function normalizeSpecifier(value) {
2205
2318
  if (!value.startsWith("./") || /[\\#?]/.test(value) || !isCanonicalText(value)) return {
2206
2319
  ok: false,
@@ -2218,7 +2331,14 @@ function normalizeSpecifier(value) {
2218
2331
  code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
2219
2332
  message: "The normalized definition source path leaves the package root."
2220
2333
  };
2221
- if (!/\.(?:[cm]?[jt]s|[jt]sx)$/.test(value)) return {
2334
+ if (COMMONJS_DEFINITION_SOURCE.test(value)) return {
2335
+ ok: false,
2336
+ code: "PH-CONFIG-SOURCE-INVALID",
2337
+ message: "A definition source is evaluated as an ES module, so a CommonJS module cannot be one.",
2338
+ expected: "a .ts, .mts, .tsx, .js, .mjs or .jsx module",
2339
+ repair: COMMONJS_DEFINITION_SOURCE_REPAIR
2340
+ };
2341
+ if (!DEFINITION_SOURCE_EXTENSION.test(value)) return {
2222
2342
  ok: false,
2223
2343
  code: "PH-CONFIG-SOURCE-INVALID",
2224
2344
  message: "A definition source names a JavaScript or TypeScript module file with its extension."
@@ -2228,21 +2348,6 @@ function normalizeSpecifier(value) {
2228
2348
  specifier: `./${normalized}`
2229
2349
  };
2230
2350
  }
2231
- /**
2232
- * Resolves symlinks as far as the path exists, so a source that is not
2233
- * written yet is still judged against the real package root.
2234
- */
2235
- function realPathThroughExistingParent(path) {
2236
- let current = path;
2237
- const suffix = [];
2238
- while (!existsSync(current)) {
2239
- const parent = dirname(current);
2240
- if (parent === current) return path;
2241
- suffix.unshift(relative(parent, current));
2242
- current = parent;
2243
- }
2244
- return resolve(realpathSync.native(current), ...suffix);
2245
- }
2246
2351
  /** Where a lexically contained module really lives, unless a symlink takes it out of the package. */
2247
2352
  function realModulePath(packageRoot, packageRootIdentity, specifier) {
2248
2353
  let moduleIdentity;
@@ -2254,7 +2359,7 @@ function realModulePath(packageRoot, packageRootIdentity, specifier) {
2254
2359
  reason: "unresolvable"
2255
2360
  };
2256
2361
  }
2257
- return isWithin(packageRootIdentity, moduleIdentity) ? {
2362
+ return pathWithin(packageRootIdentity, moduleIdentity) !== null ? {
2258
2363
  ok: true,
2259
2364
  moduleIdentity
2260
2365
  } : {
@@ -2285,9 +2390,9 @@ function normalizeEntry(value, position, packageRoot, packageRootIdentity) {
2285
2390
  code: normalized.code,
2286
2391
  path: specifierPath,
2287
2392
  message: normalized.message,
2288
- expected: "a './' path contained by the selected package root",
2393
+ expected: normalized.expected ?? "a './' path contained by the selected package root",
2289
2394
  received: entry.specifier,
2290
- repair: "Move the module inside the package and spell its path relative to the config file."
2395
+ repair: normalized.repair ?? "Move the module inside the package and spell its path relative to the config file."
2291
2396
  }) };
2292
2397
  const { specifier } = normalized;
2293
2398
  let exportPath;
@@ -2532,6 +2637,45 @@ function definitionRef(value) {
2532
2637
  function isPathSegment(segment) {
2533
2638
  return typeof segment === "string" || typeof segment === "number" && Number.isSafeInteger(segment);
2534
2639
  }
2640
+ function definitionPath(value) {
2641
+ const path = snapshotArray(value, []);
2642
+ return path.ok && path.value.every(isPathSegment) ? path.value : void 0;
2643
+ }
2644
+ function relatedSource(value) {
2645
+ if (value === void 0) return void 0;
2646
+ const snapshot = snapshotRecord(value, void 0, []);
2647
+ if (!snapshot.ok) return null;
2648
+ const { specifier, exportPath } = snapshot.value;
2649
+ if (typeof specifier !== "string" || !specifier.startsWith("./")) return null;
2650
+ const source = { specifier };
2651
+ if (exportPath === void 0) return source;
2652
+ const path = snapshotArray(exportPath, []);
2653
+ if (!path.ok || !path.value.every((key) => typeof key === "string")) return null;
2654
+ return {
2655
+ ...source,
2656
+ exportPath: path.value
2657
+ };
2658
+ }
2659
+ function relatedLocations(value) {
2660
+ if (value === void 0) return void 0;
2661
+ const list = snapshotArray(value, []);
2662
+ if (!list.ok) return null;
2663
+ const locations = [];
2664
+ for (const candidate of list.value) {
2665
+ const entry = snapshotRecord(candidate, void 0, []);
2666
+ if (!entry.ok) return null;
2667
+ const path = definitionPath(entry.value.path);
2668
+ const source = relatedSource(entry.value.source);
2669
+ const { message } = entry.value;
2670
+ if (path === void 0 || source === null || typeof message !== "string") return null;
2671
+ locations.push({
2672
+ ...source !== void 0 && { source },
2673
+ path,
2674
+ message
2675
+ });
2676
+ }
2677
+ return locations;
2678
+ }
2535
2679
  function structuredDiagnostics(value, source) {
2536
2680
  if (value === null || typeof value !== "object" && typeof value !== "function") return;
2537
2681
  const list = readProperty(value, "diagnostics");
@@ -2543,18 +2687,20 @@ function structuredDiagnostics(value, source) {
2543
2687
  const entry = snapshotRecord(candidate, void 0, []);
2544
2688
  if (!entry.ok) return void 0;
2545
2689
  const { code, message, repair, expected, received } = entry.value;
2546
- const path = snapshotArray(entry.value.path, []);
2547
- if (typeof code !== "string" || !Object.hasOwn(toolingDiagnostics.codes, code) || typeof message !== "string" || typeof repair !== "string" || !path.ok || !path.value.every(isPathSegment) || expected !== void 0 && typeof expected !== "string" || received !== void 0 && typeof received !== "string") return;
2690
+ const path = definitionPath(entry.value.path);
2691
+ const related = relatedLocations(entry.value.related);
2692
+ if (typeof code !== "string" || !Object.hasOwn(toolingDiagnostics.codes, code) || typeof message !== "string" || typeof repair !== "string" || path === void 0 || related === null || expected !== void 0 && typeof expected !== "string" || received !== void 0 && typeof received !== "string") return;
2548
2693
  const definition = definitionRef(entry.value.definition);
2549
2694
  rebuilt.push(toolingDiagnostics.create({
2550
2695
  code,
2551
2696
  source,
2552
2697
  ...definition !== void 0 && { definition },
2553
- path: path.value,
2698
+ path,
2554
2699
  message,
2555
2700
  ...expected !== void 0 && { expected },
2556
2701
  ...received !== void 0 && { received },
2557
- repair
2702
+ repair,
2703
+ ...related !== void 0 && { related }
2558
2704
  }));
2559
2705
  }
2560
2706
  return rebuilt;
@@ -2810,7 +2956,7 @@ function revisionDiagnostic(revision) {
2810
2956
  repair: "Pass a revision digest of the package's current files."
2811
2957
  });
2812
2958
  }
2813
- function refusedModule(specifier, code, message) {
2959
+ function refusedModule(specifier, code, message, refusal = {}) {
2814
2960
  return {
2815
2961
  ok: false,
2816
2962
  diagnostic: toolingDiagnostics.create({
@@ -2818,9 +2964,9 @@ function refusedModule(specifier, code, message) {
2818
2964
  source: { specifier },
2819
2965
  path: [],
2820
2966
  message,
2821
- expected: "a './' module path whose real path stays inside the package root",
2967
+ expected: refusal.expected ?? "a './' module path whose real path stays inside the package root",
2822
2968
  received: specifier,
2823
- repair: "Keep the module inside the package, and do not reach it through a symlink that leaves the package."
2969
+ repair: refusal.repair ?? "Keep the module inside the package, and do not reach it through a symlink that leaves the package."
2824
2970
  })
2825
2971
  };
2826
2972
  }
@@ -2828,7 +2974,7 @@ function refusedModule(specifier, code, message) {
2828
2974
  function containedPackageModule(request) {
2829
2975
  const { packageRoot, packageRootIdentity } = packageRoots(request);
2830
2976
  const normalized = normalizeSpecifier(request.specifier);
2831
- if (!normalized.ok) return refusedModule(request.specifier, normalized.code, normalized.message);
2977
+ if (!normalized.ok) return refusedModule(request.specifier, normalized.code, normalized.message, normalized);
2832
2978
  const real = realModulePath(packageRoot, packageRootIdentity, normalized.specifier);
2833
2979
  if (real.ok) return {
2834
2980
  ok: true,
@@ -3665,7 +3811,7 @@ function enumValue(node) {
3665
3811
  ...uses !== void 0 && { directives: uses }
3666
3812
  };
3667
3813
  }
3668
- function namedType(node, declared) {
3814
+ function namedType$1(node, declared) {
3669
3815
  switch (node.kind) {
3670
3816
  case "ObjectTypeDefinition":
3671
3817
  case "InterfaceTypeDefinition": return {
@@ -3711,7 +3857,7 @@ function declaredTypeNames(definitions) {
3711
3857
  * reference is a scalar.
3712
3858
  */
3713
3859
  function structuredTypes(definitions, declared = declaredTypeNames(definitions)) {
3714
- return [...foldTypeExtensions(definitions, []).types.values()].map(({ node }) => namedType(node, declared));
3860
+ return [...foldTypeExtensions(definitions, []).types.values()].map(({ node }) => namedType$1(node, declared));
3715
3861
  }
3716
3862
  function namedTypeName(node) {
3717
3863
  return node.kind === "NamedType" ? node.name.value : namedTypeName(node.type);
@@ -4130,15 +4276,16 @@ const storedMaterializationCheck = {
4130
4276
  /** Turns each declaration the project scan found unregistered into one diagnostic. */
4131
4277
  const unregisteredDefinitionsCheck = {
4132
4278
  name: "unregistered-definitions",
4133
- run: ({ unregistered }) => unregistered.map(({ unit, specifier }) => {
4279
+ run: ({ unregistered }) => unregistered.map(({ unit, specifier, reason }) => {
4134
4280
  const entry = `{ "specifier": "${specifier}" }`;
4281
+ const notExported = reason === "not-exported";
4135
4282
  return checkDiagnostics.create({
4136
4283
  code: "PH-PKG-DEFINITION-UNREGISTERED",
4137
4284
  source: { specifier },
4138
4285
  path: [],
4139
- message: `${unit} declares a code-first document model that no definitionSources entry reaches, so the package leaves it out.`,
4140
- expected: `a definitionSources entry that reaches ${specifier}`,
4141
- received: "no entry",
4286
+ message: notExported ? `${unit} declares a code-first document model that a selected source imports but does not export, so the package leaves it out.` : `${unit} declares a code-first document model that no definitionSources entry reaches, so the package leaves it out.`,
4287
+ expected: notExported ? `a definitionSources entry that exports the model ${specifier} declares` : `a definitionSources entry that reaches ${specifier}`,
4288
+ received: notExported ? "imported, not exported" : "no entry",
4142
4289
  repair: `Add ${entry} to definitionSources.entries in powerhouse.config.json. If definitionSources is absent or schema-first, set it to { "formatVersion": 1, "mode": "code-first", "entries": [${entry}] }; schema-first models keep generating from their stored files.`
4143
4290
  });
4144
4291
  })
@@ -4266,6 +4413,11 @@ const releaseDiagnostics = defineDiagnosticCatalog({
4266
4413
  phase: "package",
4267
4414
  meaning: "A model declares a package scalar whose stored metadata differs from the binding the package registers"
4268
4415
  },
4416
+ "PH-REL-HOST-SCALAR-UNCOMPARABLE": {
4417
+ severity: "error",
4418
+ phase: "package",
4419
+ meaning: "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"
4420
+ },
4269
4421
  "PH-REL-HOST-DEFINITION-INVALID": {
4270
4422
  severity: "error",
4271
4423
  phase: "definition",
@@ -4367,6 +4519,23 @@ function hostFindingDiagnostic(artifacts, finding) {
4367
4519
  ...related.length > 0 && { related }
4368
4520
  });
4369
4521
  }
4522
+ case "scalar-uncomparable": {
4523
+ const { source, path, related } = attribution(sites, finding, `This version also declares ${finding.scalar}.`);
4524
+ return releaseDiagnostics.create({
4525
+ code: "PH-REL-HOST-SCALAR-UNCOMPARABLE",
4526
+ ...source !== void 0 && { source },
4527
+ definition: {
4528
+ kind: "scalar",
4529
+ key: finding.scalar
4530
+ },
4531
+ path,
4532
+ 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.`,
4533
+ expected: finding.declared,
4534
+ received: finding.registered,
4535
+ repair: `Use the ${finding.scalar} binding that scalars/index.ts exports in the model, so the model and the package declare one ${finding.scalar}.`,
4536
+ ...related.length > 0 && { related }
4537
+ });
4538
+ }
4370
4539
  case "definition-invalid":
4371
4540
  case "definition-mismatch": {
4372
4541
  const { source, path, related } = attribution(sites, finding, `This version of ${documentType} carries the same definition.`);
@@ -4538,6 +4707,40 @@ async function loadProjectScalars(request) {
4538
4707
  };
4539
4708
  }
4540
4709
  //#endregion
4710
+ //#region src/definition/compiler/initial-value.ts
4711
+ function serializeAndValidateInitialValue(root, value) {
4712
+ let serialized;
4713
+ try {
4714
+ serialized = JSON.stringify(value);
4715
+ } catch (error) {
4716
+ return {
4717
+ ok: false,
4718
+ reason: "not-serializable",
4719
+ message: error instanceof Error ? error.message : String(error)
4720
+ };
4721
+ }
4722
+ if (serialized === void 0) return {
4723
+ ok: false,
4724
+ reason: "not-serializable",
4725
+ message: `JSON.stringify returned undefined for a value of type ${typeof value}`
4726
+ };
4727
+ const parsed = JSON.parse(serialized);
4728
+ try {
4729
+ root.validator.parse(parsed);
4730
+ } catch (error) {
4731
+ return {
4732
+ ok: false,
4733
+ reason: "rejected",
4734
+ message: error instanceof Error ? error.message : String(error)
4735
+ };
4736
+ }
4737
+ return {
4738
+ ok: true,
4739
+ value: parsed,
4740
+ serialized
4741
+ };
4742
+ }
4743
+ //#endregion
4541
4744
  //#region src/scalars/stored-definition.ts
4542
4745
  /** The metadata a stored definition records for a `defineScalar` binding. */
4543
4746
  function storedScalarDefinition(definition) {
@@ -4568,6 +4771,814 @@ function scalarReferences(catalogScalars, packageScalars) {
4568
4771
  return [...catalog, ...declared];
4569
4772
  }
4570
4773
  //#endregion
4774
+ //#region src/definition/kernel/global-registry.ts
4775
+ function getGlobalRegistry(key, create) {
4776
+ const registries = globalThis;
4777
+ return registries[Symbol.for(key)] ??= create();
4778
+ }
4779
+ //#endregion
4780
+ //#region src/definition/dsl/descriptor-registry.ts
4781
+ const registry = getGlobalRegistry("powerhouse.document-model.descriptors.v1", () => ({
4782
+ fieldDescriptors: /* @__PURE__ */ new WeakSet(),
4783
+ typeDescriptors: /* @__PURE__ */ new WeakSet(),
4784
+ scalarFactories: /* @__PURE__ */ new WeakSet(),
4785
+ referenceResolvers: /* @__PURE__ */ new WeakMap()
4786
+ }));
4787
+ function registerFieldDescriptor(descriptor) {
4788
+ registry.fieldDescriptors.add(descriptor);
4789
+ return descriptor;
4790
+ }
4791
+ function registerTypeDescriptor(descriptor) {
4792
+ registry.typeDescriptors.add(descriptor);
4793
+ return descriptor;
4794
+ }
4795
+ function registerScalarFactory(factory) {
4796
+ registry.scalarFactories.add(factory);
4797
+ return factory;
4798
+ }
4799
+ function isFieldDescriptor(value) {
4800
+ return value !== null && typeof value === "object" && registry.fieldDescriptors.has(value);
4801
+ }
4802
+ function isTypeDescriptor(value) {
4803
+ return value !== null && typeof value === "object" && registry.typeDescriptors.has(value);
4804
+ }
4805
+ function isScalarFactory(value) {
4806
+ return typeof value === "function" && registry.scalarFactories.has(value);
4807
+ }
4808
+ function registerReference(descriptor, resolve) {
4809
+ registry.referenceResolvers.set(descriptor, resolve);
4810
+ return descriptor;
4811
+ }
4812
+ function referenceResolver(descriptor) {
4813
+ return registry.referenceResolvers.get(descriptor);
4814
+ }
4815
+ //#endregion
4816
+ //#region src/definition/dsl/types.ts
4817
+ const FIELD_USE_ROLE = "field use";
4818
+ const NAMED_TYPE_ROLE = "named type; wrap it with ph.ref(Type) to use it as a field";
4819
+ //#endregion
4820
+ //#region src/definition/dsl/zod.ts
4821
+ /**
4822
+ * The generator wraps a nullable field of an object or an input with
4823
+ * `.nullish()`, a nullable list item that is itself a list with `.nullish()`,
4824
+ * and any other nullable list item with `.nullable()`. So the slot a field use
4825
+ * fills decides, and a descriptor's own validator is its field-slot validator.
4826
+ */
4827
+ function itemValidator(item) {
4828
+ const base = fieldBase(item);
4829
+ if (item.required) return base;
4830
+ return item.kind === "list" ? base.nullish() : base.nullable();
4831
+ }
4832
+ function fieldBase(field) {
4833
+ switch (field.kind) {
4834
+ case "scalar": return field.baseValidator;
4835
+ case "list": return z.array(itemValidator(field.item));
4836
+ case "ref": {
4837
+ const reference = field;
4838
+ return z.lazy(() => resolveReference(reference).validator);
4839
+ }
4840
+ }
4841
+ }
4842
+ /**
4843
+ * The generator maps `@equals(value: v)` to `.regex(/^v$/)` and ignores every
4844
+ * other directive.
4845
+ */
4846
+ function applyDirective(base, directive) {
4847
+ const value = directive.arguments.find((argument) => argument.name === "value")?.value;
4848
+ if (directive.name !== "equals" || typeof value !== "string") return base;
4849
+ return base.check(z.regex(new RegExp(equalsPattern(value))));
4850
+ }
4851
+ function constrainedBase(field) {
4852
+ return field.presentation.directives.reduce(applyDirective, fieldBase(field));
4853
+ }
4854
+ /**
4855
+ * The generator emits `.default(v)` only on a field that is not a list and
4856
+ * whose default is a string, number, boolean, or enum literal. A list, input
4857
+ * object, or `null` default leaves the field as required as it was, although
4858
+ * the generated types make every defaulted field an optional key.
4859
+ */
4860
+ function withDefault(field, base) {
4861
+ const fallback = field.presentation.default;
4862
+ if (!fallback.present || field.kind === "list") return base;
4863
+ const { value } = fallback;
4864
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? base.default(value) : base;
4865
+ }
4866
+ /**
4867
+ * Generated schemas list their members in `lexicographicSortSchema` order,
4868
+ * after an optional `__typename` literal. Shape order carries no validation meaning, but Zod
4869
+ * reports issues in shape order and a failed operation persists that message,
4870
+ * so the compiled schemas keep the generated order.
4871
+ */
4872
+ function objectShape(fields) {
4873
+ return Object.fromEntries(Object.entries(fields).sort(([left], [right]) => compareGeneratedOrder(left, right)).map(([key, field]) => [key, field.validator]));
4874
+ }
4875
+ function resolveReference(descriptor) {
4876
+ const resolve = referenceResolver(descriptor);
4877
+ if (resolve === void 0) throw new TypeError("The reference descriptor was not created by ph.ref.");
4878
+ return resolve();
4879
+ }
4880
+ function buildValidator(descriptor) {
4881
+ switch (descriptor.kind) {
4882
+ case "scalar":
4883
+ case "list":
4884
+ case "ref": {
4885
+ const field = descriptor;
4886
+ const base = withDefault(field, constrainedBase(field));
4887
+ return field.required ? base : base.nullish();
4888
+ }
4889
+ case "enum": {
4890
+ const names = descriptor.values.map((value) => value.name).sort(compareGeneratedOrder);
4891
+ return z.enum(names);
4892
+ }
4893
+ case "input": {
4894
+ const shape = objectShape(descriptor.fields);
4895
+ return z.object(Object.keys(shape).length === 0 ? { [EMPTY_INPUT_FIELD_NAME]: z.boolean().nullish() } : shape);
4896
+ }
4897
+ case "object": {
4898
+ const object = descriptor;
4899
+ return z.object({
4900
+ __typename: z.literal(object.name).optional(),
4901
+ ...objectShape(object.fields)
4902
+ });
4903
+ }
4904
+ case "interface": return z.object(objectShape(descriptor.fields));
4905
+ case "union": {
4906
+ const members = [...descriptor.members].sort((left, right) => compareGeneratedOrder(left.name, right.name)).map((member) => member.validator);
4907
+ return z.union(members);
4908
+ }
4909
+ }
4910
+ }
4911
+ //#endregion
4912
+ //#region src/definition/dsl/field-options.ts
4913
+ const FIELD_OPTION_KEYS = Object.freeze([
4914
+ "required",
4915
+ "description",
4916
+ "deprecated",
4917
+ "defaultValue"
4918
+ ]);
4919
+ const SCALAR_FIELD_OPTION_KEYS = Object.freeze([...FIELD_OPTION_KEYS, "equals"]);
4920
+ const LIST_ITEM_METADATA_KEYS = [
4921
+ "description",
4922
+ "deprecated",
4923
+ "defaultValue"
4924
+ ];
4925
+ function rejectionPath(rejection) {
4926
+ return rejection.path.map((segment) => typeof segment === "number" ? segment : String(segment));
4927
+ }
4928
+ const FOREIGN_ARRAY = "Expected a plain array, not an Array subclass or an array from another realm.";
4929
+ function optionRejection(rejection, unsupportedKeyCode, allowedKeys) {
4930
+ if (rejection.reason === "unknown-key") return dslDiagnostics.fail({
4931
+ code: unsupportedKeyCode,
4932
+ path: rejectionPath(rejection),
4933
+ message: `Option ${JSON.stringify(rejection.key)} is not supported here.`,
4934
+ expected: allowedKeys.join(", "),
4935
+ received: rejection.key,
4936
+ repair: `Remove ${JSON.stringify(rejection.key)}; the supported options are ${allowedKeys.join(", ")}.`
4937
+ });
4938
+ if (rejection.reason === "custom-prototype" && rejection.expected === "array") return dslDiagnostics.fail({
4939
+ code: "PH-DEF-OPTION-INVALID",
4940
+ path: rejectionPath(rejection),
4941
+ message: FOREIGN_ARRAY,
4942
+ received: rejection.received,
4943
+ repair: "Pass an array literal, or copy the array with Array.from(...)."
4944
+ });
4945
+ return dslDiagnostics.fail({
4946
+ code: "PH-DEF-OPTION-INVALID",
4947
+ path: rejectionPath(rejection),
4948
+ message: `The option value could not be snapshotted (${rejection.reason}).`,
4949
+ received: rejectionReceived(rejection),
4950
+ repair: "Pass a plain object literal with enumerable string-keyed data properties and no accessors, symbols, or class instances."
4951
+ });
4952
+ }
4953
+ function snapshotDataOptions(value, allowedKeys, path, unsupportedKeyCode = "PH-DEF-OPTION-INVALID") {
4954
+ const snapshot = snapshotDataRecord(value, allowedKeys, path);
4955
+ if (!snapshot.ok) return optionRejection(snapshot, unsupportedKeyCode, allowedKeys);
4956
+ return snapshot.value;
4957
+ }
4958
+ function snapshotDescriptorOptions(value, allowedKeys, path) {
4959
+ const snapshot = snapshotRecord(value, allowedKeys, path);
4960
+ if (!snapshot.ok) return optionRejection(snapshot, "PH-DEF-OPTION-INVALID", allowedKeys);
4961
+ return snapshot.value;
4962
+ }
4963
+ function snapshotDescriptorArray(value, path, code, repair) {
4964
+ const snapshot = snapshotArray(value, path);
4965
+ if (snapshot.ok) return snapshot.value;
4966
+ if (snapshot.reason === "not-array") return dslDiagnostics.fail({
4967
+ code,
4968
+ path,
4969
+ message: "Expected an array.",
4970
+ received: snapshot.received,
4971
+ repair
4972
+ });
4973
+ if (snapshot.reason === "custom-prototype" && snapshot.expected === "array") return dslDiagnostics.fail({
4974
+ code,
4975
+ path,
4976
+ message: FOREIGN_ARRAY,
4977
+ received: snapshot.received,
4978
+ repair: `${repair} Copy an Array subclass or an array from another realm with Array.from(...).`
4979
+ });
4980
+ return optionRejection(snapshot, code, []);
4981
+ }
4982
+ function snapshotFieldMap(value, path) {
4983
+ const snapshot = snapshotRecord(value, void 0, path);
4984
+ if (!snapshot.ok) return optionRejection(snapshot, "PH-DEF-OPTION-INVALID", []);
4985
+ return snapshot.value;
4986
+ }
4987
+ function assertAuthoredName(value, path) {
4988
+ if (!isAuthoredSchemaName(value)) return dslDiagnostics.fail({
4989
+ code: "PH-DEF-NAME-INVALID",
4990
+ path,
4991
+ message: "A GraphQL name must match /^[_A-Za-z][_0-9A-Za-z]*$/ and must not start with two underscores.",
4992
+ expected: "a GraphQL name such as InvoiceLineItem",
4993
+ received: typeof value === "string" ? value : describeReceived(value),
4994
+ repair: "Use letters, digits, and underscores, start with a letter or one underscore, and avoid the reserved __ prefix."
4995
+ });
4996
+ return value;
4997
+ }
4998
+ function assertFieldUse(value, path) {
4999
+ if (isFieldDescriptor(value)) return;
5000
+ if (isScalarFactory(value)) {
5001
+ const role = value.role;
5002
+ dslDiagnostics.fail({
5003
+ code: "PH-SCALAR-FACTORY-AS-FIELD",
5004
+ path,
5005
+ message: "A scalar factory was used as a field without being called.",
5006
+ expected: FIELD_USE_ROLE,
5007
+ received: role,
5008
+ repair: role.slice(role.indexOf("call it, as ") + 12)
5009
+ });
5010
+ }
5011
+ if (isTypeDescriptor(value)) dslDiagnostics.fail({
5012
+ code: "PH-DEF-TYPE-AS-FIELD",
5013
+ path,
5014
+ message: `Named type ${JSON.stringify(value.name)} was used directly as a field.`,
5015
+ expected: FIELD_USE_ROLE,
5016
+ received: value.role,
5017
+ repair: `Wrap the type with ph.ref(${value.name ?? "Type"}).`
5018
+ });
5019
+ dslDiagnostics.fail({
5020
+ code: "PH-DEF-FIELD-INVALID",
5021
+ path,
5022
+ message: "A field position must hold a field use created by ph.",
5023
+ received: describeReceived(value),
5024
+ repair: "Use a called scalar factory such as ph.String(), ph.list(...), or ph.ref(Type)."
5025
+ });
5026
+ }
5027
+ function assertNamedType(value, path, code, repair) {
5028
+ if (isTypeDescriptor(value)) return;
5029
+ const received = isFieldDescriptor(value) ? `field use (${value.kind})` : isScalarFactory(value) ? "scalar factory" : describeReceived(value);
5030
+ dslDiagnostics.fail({
5031
+ code,
5032
+ path,
5033
+ message: "Expected a named type created by ph.enum, ph.object, ph.input, ph.interface, or ph.union.",
5034
+ expected: "a named type descriptor",
5035
+ received,
5036
+ repair
5037
+ });
5038
+ }
5039
+ function stringOption(options, key, path) {
5040
+ const value = options[key];
5041
+ if (value === void 0) return null;
5042
+ if (typeof value !== "string") return dslDiagnostics.fail({
5043
+ code: "PH-DEF-OPTION-INVALID",
5044
+ path: [...path, key],
5045
+ message: `Option ${key} must be a string.`,
5046
+ expected: "string",
5047
+ received: describeReceived(value),
5048
+ repair: `Pass a string ${key} or omit it.`
5049
+ });
5050
+ return value;
5051
+ }
5052
+ function defaultOption(options, path) {
5053
+ if (!Object.hasOwn(options, "defaultValue")) return { present: false };
5054
+ const value = options.defaultValue;
5055
+ if (value === void 0) return dslDiagnostics.fail({
5056
+ code: "PH-DEF-OPTION-INVALID",
5057
+ path: [...path, "defaultValue"],
5058
+ message: "defaultValue is present but undefined.",
5059
+ expected: "a JSON value, or no defaultValue property at all",
5060
+ received: "undefined",
5061
+ repair: "Delete the defaultValue property to omit the default, or give it a JSON value such as null."
5062
+ });
5063
+ try {
5064
+ canonicalJson(value);
5065
+ } catch (error) {
5066
+ return dslDiagnostics.fail({
5067
+ code: "PH-DEF-OPTION-INVALID",
5068
+ path: [...path, "defaultValue"],
5069
+ message: `defaultValue is not JSON: ${error instanceof Error ? error.message : String(error)}`,
5070
+ repair: "Use a JSON value for defaultValue."
5071
+ });
5072
+ }
5073
+ return {
5074
+ present: true,
5075
+ value
5076
+ };
5077
+ }
5078
+ const NO_DIRECTIVES = Object.freeze([]);
5079
+ function equalsDirectives(options, path) {
5080
+ const value = stringOption(options, "equals", path);
5081
+ if (value === null) return NO_DIRECTIVES;
5082
+ const problem = equalsPatternProblem(value);
5083
+ if (problem !== void 0) return dslDiagnostics.fail({
5084
+ code: "PH-DEF-OPTION-INVALID",
5085
+ path: [...path, "equals"],
5086
+ received: value,
5087
+ ...problem
5088
+ });
5089
+ return Object.freeze([Object.freeze({
5090
+ name: "equals",
5091
+ arguments: Object.freeze([Object.freeze({
5092
+ name: "value",
5093
+ value
5094
+ })])
5095
+ })]);
5096
+ }
5097
+ function resolveFieldOptions(options, path, allowedKeys = FIELD_OPTION_KEYS) {
5098
+ const config = options === void 0 ? {} : snapshotDataOptions(options, allowedKeys, path, "PH-DEF-FIELD-OPTION-UNSUPPORTED");
5099
+ const required = config.required === void 0 ? false : config.required;
5100
+ if (typeof required !== "boolean") return dslDiagnostics.fail({
5101
+ code: "PH-DEF-OPTION-INVALID",
5102
+ path: [...path, "required"],
5103
+ message: "Option required must be a boolean.",
5104
+ expected: "boolean",
5105
+ received: describeReceived(required),
5106
+ repair: "Use required: true, required: false, or omit the option."
5107
+ });
5108
+ return {
5109
+ required,
5110
+ presentation: Object.freeze({
5111
+ description: stringOption(config, "description", path),
5112
+ deprecated: stringOption(config, "deprecated", path),
5113
+ default: Object.freeze(defaultOption(config, path)),
5114
+ directives: equalsDirectives(config, path)
5115
+ })
5116
+ };
5117
+ }
5118
+ function assertBareListItem(item, path) {
5119
+ const authored = LIST_ITEM_METADATA_KEYS.filter((key) => key === "defaultValue" ? item.presentation.default.present : item.presentation[key] !== null);
5120
+ if (authored.length > 0) dslDiagnostics.fail({
5121
+ code: "PH-DEF-OPTION-INVALID",
5122
+ path: [
5123
+ ...path,
5124
+ "options",
5125
+ authored[0]
5126
+ ],
5127
+ message: `A list item carries ${authored.join(", ")}, but GraphQL has no field or argument definition for a list item.`,
5128
+ received: authored.join(", "),
5129
+ repair: `Move ${authored.join(", ")} to the ph.list(...) options of the outer field use.`
5130
+ });
5131
+ if (item.presentation.directives.length > 0) dslDiagnostics.fail({
5132
+ code: "PH-DEF-OPTION-INVALID",
5133
+ path: [
5134
+ ...path,
5135
+ "options",
5136
+ "equals"
5137
+ ],
5138
+ message: "A list item carries equals, but GraphQL has no field or argument definition for a list item to carry @equals on.",
5139
+ received: "equals",
5140
+ repair: "Remove equals from the list item; a list cannot constrain its items with @equals."
5141
+ });
5142
+ }
5143
+ function createScalarField(scalarName, baseValidator, options, definition) {
5144
+ const { required, presentation } = resolveFieldOptions(options, ["options"], SCALAR_FIELD_OPTION_KEYS);
5145
+ const carriesPattern = typeof baseValidator.regex === "function";
5146
+ if (presentation.directives.length > 0 && !carriesPattern) dslDiagnostics.fail({
5147
+ code: "PH-DEF-FIELD-OPTION-UNSUPPORTED",
5148
+ path: ["options", "equals"],
5149
+ message: `Option equals adds a pattern check, and the validator of ${scalarName} is not a Zod string schema that can carry one.`,
5150
+ received: scalarName,
5151
+ repair: "Remove equals, or use it on a scalar whose validator is a Zod string schema, such as ph.String() or ph.PHID()."
5152
+ });
5153
+ const descriptor = {
5154
+ kind: "scalar",
5155
+ role: FIELD_USE_ROLE,
5156
+ identity: Object.freeze({
5157
+ kind: "scalar",
5158
+ name: scalarName,
5159
+ required
5160
+ }),
5161
+ scalarName,
5162
+ baseValidator,
5163
+ ...definition !== void 0 && { definition },
5164
+ required,
5165
+ presentation,
5166
+ validator: void 0
5167
+ };
5168
+ descriptor.validator = buildValidator(descriptor);
5169
+ return registerFieldDescriptor(Object.freeze(descriptor));
5170
+ }
5171
+ //#endregion
5172
+ //#region src/definition/dsl/scalar-fields.ts
5173
+ const BUILDER_NAMES = {
5174
+ Amount_Money: "Money",
5175
+ Amount_Percentage: "Percentage",
5176
+ Amount_Tokens: "Tokens",
5177
+ Amount_Fiat: "AmountFiat",
5178
+ Amount_Crypto: "AmountCrypto",
5179
+ Amount_Currency: "AmountCurrency"
5180
+ };
5181
+ function builderName(name) {
5182
+ return Object.hasOwn(BUILDER_NAMES, name) ? BUILDER_NAMES[name] : name;
5183
+ }
5184
+ function scalarFactory(call, name, validator, definition) {
5185
+ const factory = (options) => createScalarField(name, validator, options, definition);
5186
+ return registerScalarFactory(Object.freeze(Object.assign(factory, {
5187
+ role: `field-use factory; call it, as ${call}({ required: true })`,
5188
+ kind: "scalar-factory"
5189
+ })));
5190
+ }
5191
+ const builtInScalarFactories = {
5192
+ ID: scalarFactory("ph.ID", "ID", z.string()),
5193
+ String: scalarFactory("ph.String", "String", z.string()),
5194
+ Boolean: scalarFactory("ph.Boolean", "Boolean", z.boolean()),
5195
+ Int: scalarFactory("ph.Int", "Int", z.number()),
5196
+ Float: scalarFactory("ph.Float", "Float", z.number())
5197
+ };
5198
+ const catalogScalarFactories = Object.fromEntries(documentModelScalars.map((definition) => {
5199
+ const builder = builderName(definition.name);
5200
+ return [builder, scalarFactory(`ph.${builder}`, definition.name, definition.schema, definition)];
5201
+ }));
5202
+ const modelScalarNames = new Set(documentModelScalars.map((definition) => definition.name));
5203
+ const hostOnlyScalars = new Set(scalarCatalog.map((definition) => definition.name).filter((name) => !modelScalarNames.has(name)));
5204
+ function scalarField(definition, options) {
5205
+ if (!isScalarDefinition(definition)) refuseScalarDefinition(definition);
5206
+ if (hostOnlyScalars.has(definition.name)) refuseHostOnlyScalar(definition.name);
5207
+ return createScalarField(definition.name, definition.schema, options, definition);
5208
+ }
5209
+ function refuseHostOnlyScalar(name) {
5210
+ return dslDiagnostics.fail({
5211
+ code: "PH-SCALAR-INTERNAL",
5212
+ definition: {
5213
+ kind: "scalar",
5214
+ key: name
5215
+ },
5216
+ path: ["definition"],
5217
+ message: `${name} is internal to the reactor host. A document model cannot use it.`,
5218
+ received: name,
5219
+ repair: "Use ph.Unknown() for an unconstrained value, or ph.object(...) for a structured one."
5220
+ });
5221
+ }
5222
+ function refuseScalarFactory(name) {
5223
+ if (hostOnlyScalars.has(name)) refuseHostOnlyScalar(name);
5224
+ return dslDiagnostics.fail({
5225
+ code: "PH-SCALAR-UNKNOWN",
5226
+ path: [name],
5227
+ message: `ph.${name} names no catalog scalar.`,
5228
+ expected: `a scalar factory: ${[...Object.keys(builtInScalarFactories), ...Object.keys(catalogScalarFactories).sort()].join(", ")}`,
5229
+ received: `ph.${name}`,
5230
+ repair: "Correct the factory name, or declare a project scalar with defineScalar and use it as ph.scalar(definition)."
5231
+ });
5232
+ }
5233
+ const EXPECTED_DEFINITION = "a ScalarDefinition from defineScalar in document-model/scalars";
5234
+ function refuseScalarDefinition(value) {
5235
+ const version = scalarDefinitionVersion(value);
5236
+ if (version === void 0) return dslDiagnostics.fail({
5237
+ code: "PH-SCALAR-DEFINITION-INVALID",
5238
+ path: ["definition"],
5239
+ message: "ph.scalar takes a scalar definition returned by defineScalar.",
5240
+ expected: EXPECTED_DEFINITION,
5241
+ received: describeReceived(value),
5242
+ repair: "Pass the value defineScalar returned, or use a ph.<Scalar>() factory for a catalog scalar."
5243
+ });
5244
+ const received = typeof version === "number" ? String(version) : describeReceived(version);
5245
+ return dslDiagnostics.fail({
5246
+ code: "PH-SCALAR-DEFINITION-INVALID",
5247
+ path: ["definition"],
5248
+ message: `The scalar definition has format version ${received}; this release reads version 1.`,
5249
+ expected: EXPECTED_DEFINITION,
5250
+ received,
5251
+ repair: "Install the same document-model release in the package that defines the scalar and the package that uses it."
5252
+ });
5253
+ }
5254
+ //#endregion
5255
+ //#region src/definition/dsl/field.ts
5256
+ const KIND_NOUNS = {
5257
+ enum: "an enum",
5258
+ object: "an object",
5259
+ input: "an input",
5260
+ interface: "an interface",
5261
+ union: "a union"
5262
+ };
5263
+ function fieldMap(value, path) {
5264
+ const members = snapshotFieldMap(value, path);
5265
+ for (const [key, member] of Object.entries(members)) {
5266
+ assertAuthoredName(key, [...path, key]);
5267
+ assertFieldUse(member, [...path, key]);
5268
+ }
5269
+ return Object.freeze({ ...members });
5270
+ }
5271
+ function enumValues(input) {
5272
+ const entries = snapshotDescriptorArray(input, ["options", "values"], "PH-DEF-ENUM-VALUES-INVALID", "Pass values as a nonempty array of strings or { name, description?, deprecated? } entries.");
5273
+ if (entries.length === 0) dslDiagnostics.fail({
5274
+ code: "PH-DEF-ENUM-VALUES-INVALID",
5275
+ path: ["options", "values"],
5276
+ message: "An enum must declare at least one value.",
5277
+ repair: "Add at least one enum value."
5278
+ });
5279
+ const seen = /* @__PURE__ */ new Set();
5280
+ return Object.freeze(entries.map((entry, index) => {
5281
+ const path = [
5282
+ "options",
5283
+ "values",
5284
+ index
5285
+ ];
5286
+ const normalized = typeof entry === "string" ? { name: entry } : snapshotDataOptions(entry, [
5287
+ "name",
5288
+ "description",
5289
+ "deprecated"
5290
+ ], path);
5291
+ const name = assertAuthoredName(normalized.name, [...path, "name"]);
5292
+ if (!isEnumValueName(name)) dslDiagnostics.fail({
5293
+ code: "PH-DEF-ENUM-VALUES-INVALID",
5294
+ path: [...path, "name"],
5295
+ message: `${JSON.stringify(name)} is a reserved GraphQL literal and cannot be an enum value.`,
5296
+ received: name,
5297
+ repair: `Rename the value; true, false, and null are GraphQL literals.`
5298
+ });
5299
+ if (seen.has(name)) dslDiagnostics.fail({
5300
+ code: "PH-DEF-ENUM-VALUES-INVALID",
5301
+ path: [...path, "name"],
5302
+ message: `Enum value ${JSON.stringify(name)} is declared twice.`,
5303
+ received: name,
5304
+ repair: "Keep one declaration per enum value."
5305
+ });
5306
+ seen.add(name);
5307
+ return Object.freeze({
5308
+ name,
5309
+ description: stringOption(normalized, "description", path),
5310
+ deprecated: stringOption(normalized, "deprecated", path)
5311
+ });
5312
+ }));
5313
+ }
5314
+ function namedType(node) {
5315
+ const descriptor = {
5316
+ ...node,
5317
+ role: NAMED_TYPE_ROLE,
5318
+ identity: Object.freeze({
5319
+ kind: node.kind,
5320
+ name: node.name,
5321
+ description: node.description
5322
+ }),
5323
+ validator: void 0
5324
+ };
5325
+ descriptor.validator = buildValidator(descriptor);
5326
+ return registerTypeDescriptor(Object.freeze(descriptor));
5327
+ }
5328
+ function refTarget(candidate, path) {
5329
+ assertNamedType(candidate, path, "PH-DEF-REFERENCE-TARGET-INVALID", "Pass a named type returned by ph.enum, ph.object, ph.input, ph.interface, or ph.union, or a thunk returning one.");
5330
+ if (candidate.name === null) dslDiagnostics.fail({
5331
+ code: "PH-DEF-REFERENCE-TARGET-INVALID",
5332
+ path,
5333
+ message: "An anonymous input cannot be a reference target.",
5334
+ repair: "Give the input a name: ph.input(\"NameInput\", { fields })."
5335
+ });
5336
+ return candidate;
5337
+ }
5338
+ function implementedInterfaces(config) {
5339
+ const implemented = config.implements !== void 0 ? snapshotDescriptorArray(config.implements, ["options", "implements"], "PH-DEF-IMPLEMENTS-INVALID", "Pass implements as an array of descriptors returned by ph.interface.") : [];
5340
+ const seen = /* @__PURE__ */ new Set();
5341
+ implemented.forEach((candidate, index) => {
5342
+ const path = [
5343
+ "options",
5344
+ "implements",
5345
+ index
5346
+ ];
5347
+ assertNamedType(candidate, path, "PH-DEF-IMPLEMENTS-INVALID", "Pass a descriptor returned by ph.interface.");
5348
+ if (candidate.kind !== "interface") dslDiagnostics.fail({
5349
+ code: "PH-DEF-IMPLEMENTS-INVALID",
5350
+ path,
5351
+ message: `${JSON.stringify(candidate.name)} is ${KIND_NOUNS[candidate.kind]}, not an interface.`,
5352
+ received: candidate.kind,
5353
+ repair: "Only descriptors returned by ph.interface can be implemented."
5354
+ });
5355
+ const interfaceName = candidate.name;
5356
+ if (seen.has(interfaceName)) dslDiagnostics.fail({
5357
+ code: "PH-DEF-IMPLEMENTS-INVALID",
5358
+ path,
5359
+ message: `Interface ${JSON.stringify(interfaceName)} is implemented twice.`,
5360
+ received: interfaceName,
5361
+ repair: "List each implemented interface once."
5362
+ });
5363
+ seen.add(interfaceName);
5364
+ });
5365
+ return Object.freeze([...implemented]);
5366
+ }
5367
+ function objectType(name, options) {
5368
+ return namedType({
5369
+ kind: "object",
5370
+ ...implementingMembers(name, options)
5371
+ });
5372
+ }
5373
+ function interfaceType(name, options) {
5374
+ return namedType({
5375
+ kind: "interface",
5376
+ ...implementingMembers(name, options)
5377
+ });
5378
+ }
5379
+ function implementingMembers(name, options) {
5380
+ const validName = assertAuthoredName(name, ["name"]);
5381
+ const config = snapshotDescriptorOptions(options, [
5382
+ "fields",
5383
+ "description",
5384
+ "implements"
5385
+ ], ["options"]);
5386
+ return {
5387
+ name: validName,
5388
+ description: stringOption(config, "description", ["options"]),
5389
+ fields: fieldMap(config.fields, ["options", "fields"]),
5390
+ implements: implementedInterfaces(config)
5391
+ };
5392
+ }
5393
+ function scalarFactoryGuard(builders) {
5394
+ return new Proxy(Object.freeze(builders), { get(target, key, receiver) {
5395
+ if (typeof key === "string" && /^[A-Z]/.test(key) && !Object.hasOwn(target, key)) refuseScalarFactory(key);
5396
+ return Reflect.get(target, key, receiver);
5397
+ } });
5398
+ }
5399
+ /**
5400
+ * @experimental The field and type builders of a code-first document model:
5401
+ * scalar factories such as `ph.String()` and `ph.PHID()`, `ph.scalar` for a
5402
+ * project scalar, and `list`, `ref`, `enum`, `object`, `interface`, `input`,
5403
+ * and `union`.
5404
+ */
5405
+ const ph = scalarFactoryGuard({
5406
+ ...builtInScalarFactories,
5407
+ ...catalogScalarFactories,
5408
+ scalar: scalarField,
5409
+ list(item, options) {
5410
+ assertFieldUse(item, ["item"]);
5411
+ assertBareListItem(item, ["item"]);
5412
+ const { required, presentation } = resolveFieldOptions(options, ["options"]);
5413
+ const descriptor = {
5414
+ kind: "list",
5415
+ role: FIELD_USE_ROLE,
5416
+ identity: Object.freeze({
5417
+ kind: "list",
5418
+ required,
5419
+ item: item.identity
5420
+ }),
5421
+ item,
5422
+ required,
5423
+ presentation,
5424
+ validator: void 0
5425
+ };
5426
+ descriptor.validator = buildValidator(descriptor);
5427
+ return registerFieldDescriptor(Object.freeze(descriptor));
5428
+ },
5429
+ ref(target, options) {
5430
+ let resolved;
5431
+ const resolve = () => {
5432
+ if (resolved === void 0) resolved = refTarget(typeof target === "function" && !isTypeDescriptor(target) ? target() : target, ["target"]);
5433
+ return resolved;
5434
+ };
5435
+ if (typeof target !== "function") resolve();
5436
+ const { required, presentation } = resolveFieldOptions(options, ["options"]);
5437
+ const descriptor = {
5438
+ kind: "ref",
5439
+ role: FIELD_USE_ROLE,
5440
+ identity: Object.freeze({
5441
+ kind: "ref",
5442
+ required
5443
+ }),
5444
+ target,
5445
+ required,
5446
+ presentation,
5447
+ validator: void 0
5448
+ };
5449
+ const reference = descriptor;
5450
+ registerReference(reference, resolve);
5451
+ descriptor.validator = buildValidator(reference);
5452
+ return registerFieldDescriptor(Object.freeze(reference));
5453
+ },
5454
+ enum(name, options) {
5455
+ const validName = assertAuthoredName(name, ["name"]);
5456
+ const config = snapshotDescriptorOptions(options, ["values", "description"], ["options"]);
5457
+ return namedType({
5458
+ kind: "enum",
5459
+ name: validName,
5460
+ description: stringOption(config, "description", ["options"]),
5461
+ values: enumValues(config.values)
5462
+ });
5463
+ },
5464
+ object: objectType,
5465
+ interface: interfaceType,
5466
+ input(...args) {
5467
+ const [nameOrOptions, maybeOptions] = args;
5468
+ const name = typeof nameOrOptions === "string" ? assertAuthoredName(nameOrOptions, ["name"]) : null;
5469
+ const config = snapshotDescriptorOptions(typeof nameOrOptions === "string" ? maybeOptions : nameOrOptions, ["fields", "description"], ["options"]);
5470
+ return namedType({
5471
+ kind: "input",
5472
+ name,
5473
+ description: stringOption(config, "description", ["options"]),
5474
+ fields: fieldMap(config.fields, ["options", "fields"])
5475
+ });
5476
+ },
5477
+ union(name, options) {
5478
+ const validName = assertAuthoredName(name, ["name"]);
5479
+ const config = snapshotDescriptorOptions(options, ["members", "description"], ["options"]);
5480
+ const members = snapshotDescriptorArray(config.members, ["options", "members"], "PH-DEF-UNION-MEMBERS-INVALID", "Pass members as a nonempty array of descriptors returned by ph.object.");
5481
+ if (members.length === 0) dslDiagnostics.fail({
5482
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
5483
+ path: ["options", "members"],
5484
+ message: "A union must declare at least one object member.",
5485
+ repair: "Add at least one ph.object descriptor to members."
5486
+ });
5487
+ const seen = /* @__PURE__ */ new Set();
5488
+ members.forEach((member, index) => {
5489
+ const path = [
5490
+ "options",
5491
+ "members",
5492
+ index
5493
+ ];
5494
+ assertNamedType(member, path, "PH-DEF-UNION-MEMBERS-INVALID", "Replace the member with a descriptor returned by ph.object.");
5495
+ if (member.kind !== "object") dslDiagnostics.fail({
5496
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
5497
+ path,
5498
+ message: `Union member ${JSON.stringify(member.name)} is ${KIND_NOUNS[member.kind]}; GraphQL unions hold object types only.`,
5499
+ received: member.kind,
5500
+ repair: "Replace the member with a descriptor returned by ph.object."
5501
+ });
5502
+ const memberName = member.name;
5503
+ if (seen.has(memberName)) dslDiagnostics.fail({
5504
+ code: "PH-DEF-UNION-MEMBERS-INVALID",
5505
+ path,
5506
+ message: `Union member ${JSON.stringify(memberName)} is declared twice.`,
5507
+ received: memberName,
5508
+ repair: "List each member object once."
5509
+ });
5510
+ seen.add(memberName);
5511
+ });
5512
+ return namedType({
5513
+ kind: "union",
5514
+ name: validName,
5515
+ description: stringOption(config, "description", ["options"]),
5516
+ members: Object.freeze([...members])
5517
+ });
5518
+ }
5519
+ });
5520
+ //#endregion
5521
+ //#region src/definition/tooling/schema-first/state-descriptor.ts
5522
+ function storedStateDescriptor(typesByName, root, scalars) {
5523
+ const scalarsByName = new Map([...scalarCatalog, ...scalars].map((scalar) => [scalar.name, scalar]));
5524
+ const built = /* @__PURE__ */ new Map();
5525
+ const fieldUse = (type, field) => {
5526
+ const options = {
5527
+ required: type.required,
5528
+ ...field !== void 0 && "defaultValue" in field && field.defaultValue !== void 0 && { defaultValue: field.defaultValue }
5529
+ };
5530
+ switch (type.kind) {
5531
+ case "list": return ph.list(fieldUse(type.item), options);
5532
+ case "named": return ph.ref(() => named(type.name), options);
5533
+ case "scalar": {
5534
+ const equals = field === void 0 ? null : definitionEquals(field);
5535
+ const scalarOptions = {
5536
+ ...options,
5537
+ ...equals !== null && { equals }
5538
+ };
5539
+ if (Object.hasOwn(builtInScalarFactories, type.name)) return builtInScalarFactories[type.name](scalarOptions);
5540
+ const definition = scalarsByName.get(type.name);
5541
+ if (definition === void 0) throw new TypeError(`Unknown scalar ${type.name}.`);
5542
+ return createScalarField(definition.name, definition.schema, scalarOptions, definition);
5543
+ }
5544
+ }
5545
+ };
5546
+ const fields = (members) => Object.fromEntries(members.map((member) => [member.name, fieldUse(member.type, member)]));
5547
+ const named = (name) => {
5548
+ const existing = built.get(name);
5549
+ if (existing !== void 0) return existing;
5550
+ const type = typesByName.get(name);
5551
+ if (type === void 0) throw new TypeError(`Unknown type ${name}.`);
5552
+ const descriptor = describe(type);
5553
+ built.set(name, descriptor);
5554
+ return descriptor;
5555
+ };
5556
+ const describe = (type) => {
5557
+ switch (type.kind) {
5558
+ case "enum": return ph.enum(type.name, { values: type.values.map(({ name }) => name) });
5559
+ case "object": return ph.object(type.name, { fields: fields(type.fields) });
5560
+ case "interface": return ph.interface(type.name, { fields: fields(type.fields) });
5561
+ case "input": return ph.input(type.name, { fields: fields(type.fields) });
5562
+ case "union": return ph.union(type.name, { members: type.members.map((member) => named(member)) });
5563
+ }
5564
+ };
5565
+ const reachable = (name, seen) => {
5566
+ if (seen.has(name)) return;
5567
+ seen.add(name);
5568
+ named(name);
5569
+ const type = typesByName.get(name);
5570
+ const references = (reference) => reference.kind === "list" ? references(reference.item) : reference.kind === "named" ? [reference.name] : [];
5571
+ const next = type === void 0 ? [] : type.kind === "union" ? type.members : type.kind === "enum" ? [] : type.fields.flatMap((field) => references(field.type));
5572
+ for (const member of next) reachable(member, seen);
5573
+ };
5574
+ try {
5575
+ reachable(root, /* @__PURE__ */ new Set());
5576
+ return named(root);
5577
+ } catch {
5578
+ return;
5579
+ }
5580
+ }
5581
+ //#endregion
4571
5582
  //#region src/definition/tooling/schema-first/schema-first-document-model-module-adapter.ts
4572
5583
  const EXAMPLE_KEY_PREFIX = "schema-first-id:";
4573
5584
  function producesRuntimeSymbol(name) {
@@ -4679,9 +5690,25 @@ function normalizeOperation(collector, operation, typesByName, path) {
4679
5690
  reducer: operation.reducer
4680
5691
  };
4681
5692
  }
4682
- function rootState(collector, stored, root, path, scope) {
4683
- const initialValue = parseInitialValue(collector, stored.initialValue, [...path, "initialValue"], scope === "local");
4684
- if (initialValue === void 0) return void 0;
5693
+ function acceptedByRoot(collector, initialValue, root, types, path) {
5694
+ const descriptor = storedStateDescriptor(types.byName, root, types.scalars);
5695
+ if (descriptor === void 0) return true;
5696
+ const checked = serializeAndValidateInitialValue(descriptor, initialValue);
5697
+ if (checked.ok) return true;
5698
+ collector.add({
5699
+ code: "PH-DM-INITIAL-VALUE-INVALID",
5700
+ path,
5701
+ message: `The ${root} schema rejects this initial value.`,
5702
+ expected: `a value ${root} accepts`,
5703
+ received: checked.message,
5704
+ repair: "Correct the stored initial value so the declared state schema accepts it."
5705
+ });
5706
+ return false;
5707
+ }
5708
+ function rootState(collector, stored, root, path, scope, types) {
5709
+ const initialValuePath = [...path, "initialValue"];
5710
+ const initialValue = parseInitialValue(collector, stored.initialValue, initialValuePath, scope === "local");
5711
+ if (initialValue === void 0 || root !== null && !acceptedByRoot(collector, initialValue, root, types, initialValuePath)) return;
4685
5712
  const materialized = {
4686
5713
  initialValue: stored.initialValue,
4687
5714
  examples: stored.examples.map(({ id, value }) => ({
@@ -4858,12 +5885,18 @@ function normalizeSpecification(collector, specification, roots, path, scalars)
4858
5885
  ...path,
4859
5886
  "state",
4860
5887
  "global"
4861
- ], "global");
5888
+ ], "global", {
5889
+ byName: typesByName,
5890
+ scalars
5891
+ });
4862
5892
  const local = rootState(collector, specification.state.local, hasLocalRoot ? roots.local : null, [
4863
5893
  ...path,
4864
5894
  "state",
4865
5895
  "local"
4866
- ], "local");
5896
+ ], "local", {
5897
+ byName: typesByName,
5898
+ scalars
5899
+ });
4867
5900
  if (global === void 0 || global.root === null || local === void 0) return;
4868
5901
  const inputs = new Set(modules.flatMap((module) => module.operations.flatMap((operation) => operation.input === null ? [] : [operation.input.name])));
4869
5902
  return {
@@ -5150,7 +6183,7 @@ function storedModelFiles(packageRoot, documentModelsDir) {
5150
6183
  diagnostics.push(unreadable(packageRoot, directory, "document model directory", error));
5151
6184
  continue;
5152
6185
  }
5153
- if (isWithin(packageRootIdentity, real)) files.push(file);
6186
+ if (pathWithin(packageRootIdentity, real) !== null) files.push(file);
5154
6187
  else diagnostics.push(outsidePackage(packageSpecifier(packageRoot, file)));
5155
6188
  }
5156
6189
  return {
@@ -5274,16 +6307,7 @@ function startsRegExp(code) {
5274
6307
  const before = code.slice(-64).trimEnd();
5275
6308
  return before === "" || /[(,=:[!&|?{};+\-*%<>~^}]$/.test(before) || /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(before);
5276
6309
  }
5277
- function readCodeAndStrings(file) {
5278
- let text;
5279
- try {
5280
- text = readFileSync(file, "utf8");
5281
- } catch {
5282
- return {
5283
- code: "",
5284
- strings: []
5285
- };
5286
- }
6310
+ function lexCodeAndStrings(text) {
5287
6311
  let code = "";
5288
6312
  const strings = [];
5289
6313
  const literal = (contents) => {
@@ -5358,27 +6382,32 @@ function valueBindings(clause) {
5358
6382
  });
5359
6383
  }
5360
6384
  function isSourceFile(name) {
5361
- return /\.m?tsx?$/.test(name) && !/\.d\.m?ts$/.test(name);
6385
+ return DEFINITION_SOURCE_EXTENSION.test(name) && !/\.d\.m?ts$/.test(name);
5362
6386
  }
5363
6387
  function isTestFile(name) {
5364
- return /\.(?:test|spec)\.m?tsx?$/.test(name);
6388
+ return /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/.test(name);
5365
6389
  }
5366
6390
  /**
5367
- * Sorted, with symlinks followed. An entry that cannot be read, or whose real
5368
- * path leaves the package, is not the package's and is skipped.
6391
+ * Sorted, with symlinks followed. An entry whose real path cannot be read, or
6392
+ * leaves the package, is not the package's and is skipped; a directory that
6393
+ * cannot be listed goes to `unreadable`.
5369
6394
  */
5370
- function packageEntries(path, packageRootIdentity) {
6395
+ function packageEntries(path, packageRootIdentity, unreadable) {
5371
6396
  let names;
5372
6397
  try {
5373
6398
  names = readdirSync(path);
5374
- } catch {
6399
+ } catch (error) {
6400
+ unreadable.push({
6401
+ path,
6402
+ error
6403
+ });
5375
6404
  return [];
5376
6405
  }
5377
6406
  return names.filter((name) => name !== "node_modules" && !name.startsWith(".")).sort(compareCodeUnits).flatMap((name) => {
5378
6407
  const child = join(path, name);
5379
6408
  try {
5380
6409
  const real = realpathSync.native(child);
5381
- if (!isWithin(packageRootIdentity, real)) return [];
6410
+ if (pathWithin(packageRootIdentity, real) === null) return [];
5382
6411
  return [{
5383
6412
  name,
5384
6413
  path: child,
@@ -5391,19 +6420,66 @@ function packageEntries(path, packageRootIdentity) {
5391
6420
  });
5392
6421
  }
5393
6422
  /** `visited` holds real directories, so a symlink cycle ends. */
5394
- function sourceFilesUnder(directory, packageRootIdentity, visited) {
6423
+ function sourceFilesUnder(directory, packageRootIdentity, visited, unreadable) {
5395
6424
  if (visited.has(directory.real)) return [];
5396
6425
  visited.add(directory.real);
5397
- return packageEntries(directory.path, packageRootIdentity).flatMap((entry) => {
5398
- if (entry.isDirectory) return entry.name === "__tests__" ? [] : sourceFilesUnder(entry, packageRootIdentity, visited);
6426
+ return packageEntries(directory.path, packageRootIdentity, unreadable).flatMap((entry) => {
6427
+ if (entry.isDirectory) return entry.name === "__tests__" ? [] : sourceFilesUnder(entry, packageRootIdentity, visited, unreadable);
5399
6428
  return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];
5400
6429
  });
5401
6430
  }
5402
- function declares(file) {
6431
+ /**
6432
+ * The object literal's own `id` when its source spells it as a plain string.
6433
+ * A spread can override it and an escape changes its spelling, so either
6434
+ * leaves it unknown.
6435
+ */
6436
+ function topLevelId(code, strings, open) {
6437
+ let depth = 0;
6438
+ let id;
6439
+ for (let i = open; i < code.length; i += 1) {
6440
+ const char = code[i];
6441
+ if ("{([".includes(char)) depth += 1;
6442
+ else if ("})]".includes(char)) {
6443
+ depth -= 1;
6444
+ if (depth === 0) break;
6445
+ } else if (depth === 1 && code.startsWith("...", i)) return;
6446
+ else if (depth === 1 && !/[\w$]/.test(code[i - 1] ?? "")) {
6447
+ const rest = code.slice(i, i + 16);
6448
+ const quoted = /^"#(\d+)"\s*:\s*/.exec(rest);
6449
+ const key = /^id\s*:\s*/.exec(rest) ?? (quoted !== null && strings[+quoted[1]] === "id" ? quoted : null);
6450
+ if (key !== null) {
6451
+ const value = /^"#(\d+)"/.exec(code.slice(i + key[0].length));
6452
+ id = value === null ? void 0 : strings[+value[1]];
6453
+ }
6454
+ }
6455
+ }
6456
+ return id === void 0 || id === "" || id.includes("\\") ? void 0 : id;
6457
+ }
6458
+ function declarations(code, strings) {
5403
6459
  const { module, factory } = DECLARATION;
5404
- const { code, strings } = readCodeAndStrings(file);
5405
6460
  const isFactory = new RegExp(`^${factory}$`);
5406
- return [...[...code.matchAll(NAMED_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).flatMap(([, clause]) => valueBindings(clause).filter(({ imported }) => isFactory.test(imported)).map(({ local }) => escapeRegExp(local))), ...[...code.matchAll(NAMESPACE_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).map(([, namespace]) => `${escapeRegExp(namespace)}\\s*\\.\\s*${factory}`)].some((callee) => new RegExp(`(?<![\\w$.])${callee}\\s*(?:<[^;()]*>\\s*)?\\(`).test(code));
6461
+ const callees = [...[...code.matchAll(NAMED_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).flatMap(([, clause]) => valueBindings(clause).filter(({ imported }) => isFactory.test(imported)).map(({ imported, local }) => ({
6462
+ callee: escapeRegExp(local),
6463
+ family: imported !== "defineDocumentModel"
6464
+ }))), ...[...code.matchAll(NAMESPACE_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).flatMap(([, namespace]) => [false, true].map((family) => ({
6465
+ callee: `${escapeRegExp(namespace)}\\s*\\.\\s*defineDocumentModel${family ? "Family" : ""}`,
6466
+ family
6467
+ })))];
6468
+ let declares = false;
6469
+ let ids = [];
6470
+ for (const { callee, family } of callees) {
6471
+ const calls = new RegExp(`(?<![\\w$.])${callee}\\s*(?:<[^;()]*>\\s*)?\\((?:\\s*\\{)?`, "g");
6472
+ for (const call of code.matchAll(calls)) {
6473
+ declares = true;
6474
+ const id = family || !call[0].endsWith("{") ? void 0 : topLevelId(code, strings, call.index + call[0].length - 1);
6475
+ if (id === void 0) ids = null;
6476
+ else ids?.push(id);
6477
+ }
6478
+ }
6479
+ return {
6480
+ declares,
6481
+ ids
6482
+ };
5407
6483
  }
5408
6484
  function escapeRegExp(name) {
5409
6485
  return name.replaceAll("$", "\\$");
@@ -5419,34 +6495,80 @@ function realPathOrSelf(path) {
5419
6495
  }
5420
6496
  }
5421
6497
  /** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */
5422
- function modelUnit(packageRoot, packageRootIdentity, directory) {
5423
- const declaring = sourceFilesUnder(directory, packageRootIdentity, /* @__PURE__ */ new Set()).filter(({ real }) => declares(real));
6498
+ function modelUnit(packageRoot, packageRootIdentity, directory, unreadable) {
6499
+ const declaring = [];
6500
+ for (const entry of sourceFilesUnder(directory, packageRootIdentity, /* @__PURE__ */ new Set(), unreadable)) {
6501
+ let text;
6502
+ try {
6503
+ text = readFileSync(entry.real, "utf8");
6504
+ } catch (error) {
6505
+ unreadable.push({
6506
+ path: entry.path,
6507
+ error
6508
+ });
6509
+ continue;
6510
+ }
6511
+ const { code, strings } = lexCodeAndStrings(text);
6512
+ const found = declarations(code, strings);
6513
+ if (found.declares) declaring.push({
6514
+ entry,
6515
+ ids: found.ids
6516
+ });
6517
+ }
5424
6518
  const index = join(directory.path, "index.ts");
5425
- const suggested = declaring.find(({ path }) => path === index) ?? declaring.at(0);
6519
+ const suggested = declaring.find(({ entry }) => entry.path === index) ?? declaring.at(0);
5426
6520
  if (suggested === void 0) return void 0;
5427
6521
  return {
5428
6522
  kind: "document-model",
5429
6523
  unit: `${packagePath(packageRoot, directory.path)}/`,
5430
- specifier: packagePath(packageRoot, suggested.path),
5431
- declaring: declaring.map(({ real }) => real)
6524
+ specifier: packagePath(packageRoot, suggested.entry.path),
6525
+ declaring: declaring.map(({ entry }) => entry.real),
6526
+ ids: declaring.some(({ ids }) => ids === null) ? null : declaring.flatMap(({ ids }) => ids ?? [])
5432
6527
  };
5433
6528
  }
6529
+ function unreadableDiagnostic(packageRoot, { path, error }) {
6530
+ return toolingDiagnostics.create({
6531
+ code: "PH-IMPORT-FAILED",
6532
+ source: { specifier: packagePath(packageRoot, path) },
6533
+ path: [],
6534
+ message: "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 definitionSources entry reaches.",
6535
+ expected: "a readable file or directory",
6536
+ received: describeThrown(error),
6537
+ repair: "Fix the permissions of the path, or move it out of the document models directory."
6538
+ });
6539
+ }
5434
6540
  /**
5435
6541
  * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model
5436
- * that no selected source's import reached. A selected source that did not
6542
+ * that no selected source's import reached, or that a selected source reached
6543
+ * without exporting the model's literal id. A selected source that did not
5437
6544
  * import reaches files no one can name, so the scan then reports nothing.
5438
6545
  */
5439
6546
  function findUnregisteredDefinitions(request) {
5440
- const { packageRoot, documentModelsDir, sources, importedFiles } = request;
6547
+ const { packageRoot, documentModelsDir, sources, importedFiles, loadedDocumentTypes } = request;
5441
6548
  const imported = sources.map(({ specifier }) => importedFiles(specifier));
5442
- if (imported.some((files) => files.length === 0)) return [];
6549
+ if (imported.some((files) => files.length === 0)) return {
6550
+ unregistered: [],
6551
+ diagnostics: []
6552
+ };
5443
6553
  const reached = new Set(imported.flat().map(realPathOrSelf));
5444
6554
  const packageRootIdentity = realPathOrSelf(packageRoot);
5445
- return packageEntries(documentModelsDir, packageRootIdentity).flatMap((entry) => entry.isDirectory ? modelUnit(packageRoot, packageRootIdentity, entry) ?? [] : []).filter((unit) => !unit.declaring.some((file) => reached.has(file))).map(({ kind, unit, specifier }) => ({
5446
- kind,
5447
- unit,
5448
- specifier
5449
- }));
6555
+ const unreadable = [];
6556
+ const directories = packageEntries(documentModelsDir, packageRootIdentity, []).filter(({ isDirectory }) => isDirectory);
6557
+ const units = directories.flatMap((entry) => modelUnit(packageRoot, packageRootIdentity, entry, unreadable) ?? []);
6558
+ const modelDirectories = new Set(directories.map(({ path }) => path));
6559
+ return {
6560
+ unregistered: units.flatMap(({ kind, unit, specifier, declaring, ids }) => {
6561
+ const isReached = declaring.some((file) => reached.has(file));
6562
+ if (isReached && (ids === null || ids.some((id) => loadedDocumentTypes.has(id)))) return [];
6563
+ return [{
6564
+ kind,
6565
+ unit,
6566
+ specifier,
6567
+ reason: isReached ? "not-exported" : "unreached"
6568
+ }];
6569
+ }),
6570
+ diagnostics: unreadable.filter(({ path }) => !modelDirectories.has(path)).map((entry) => unreadableDiagnostic(packageRoot, entry))
6571
+ };
5450
6572
  }
5451
6573
  //#endregion
5452
6574
  //#region src/definition/tooling/project/project-definitions.ts
@@ -5493,9 +6615,9 @@ function documentModelsDirectory(packageRoot, configFile) {
5493
6615
  repair: "Set documentModelsDir to a package-relative directory, or remove it to use ./document-models."
5494
6616
  })] };
5495
6617
  const path = resolve(packageRoot, configured);
5496
- let inside = isWithin(packageRoot, path);
6618
+ let inside = pathWithin(packageRoot, path) !== null;
5497
6619
  try {
5498
- inside &&= isWithin(realpathSync.native(packageRoot), realPathThroughExistingParent(path));
6620
+ inside &&= pathWithin(realpathSync.native(packageRoot), realPathThroughExistingParent(path)) !== null;
5499
6621
  } catch {
5500
6622
  inside = false;
5501
6623
  }
@@ -5566,7 +6688,16 @@ async function loadProjectDefinitions(request) {
5566
6688
  const produced = [];
5567
6689
  for (const producer of producers) produced.push(await producer(input));
5568
6690
  request.signal?.throwIfAborted();
5569
- const selectionKnown = !loaded.diagnostics.some(({ phase, severity }) => phase === "configuration" && severity === "error");
6691
+ const scan = !loaded.diagnostics.some(({ phase, severity }) => phase === "configuration" && severity === "error") && modelsDir !== void 0 ? findUnregisteredDefinitions({
6692
+ packageRoot,
6693
+ documentModelsDir: modelsDir,
6694
+ sources: loaded.sourceSet.sources,
6695
+ importedFiles,
6696
+ loadedDocumentTypes: /* @__PURE__ */ new Set([...loaded.documentModels.map(({ value }) => value.documentModel.global.id), ...loaded.diagnostics.flatMap(({ definition }) => definition?.kind === "document-model" ? [definition.key] : [])])
6697
+ }) : {
6698
+ unregistered: [],
6699
+ diagnostics: []
6700
+ };
5570
6701
  return {
5571
6702
  packageRoot,
5572
6703
  sourceSet: loaded.sourceSet,
@@ -5576,17 +6707,13 @@ async function loadProjectDefinitions(request) {
5576
6707
  diagnostics: sortedUniqueDiagnostics(packageRelative([
5577
6708
  ...loaded.diagnostics,
5578
6709
  ...directory.diagnostics,
5579
- ...produced.flatMap(({ diagnostics }) => diagnostics)
6710
+ ...produced.flatMap(({ diagnostics }) => diagnostics),
6711
+ ...scan.diagnostics
5580
6712
  ], packageRoot)),
5581
- unregistered: selectionKnown && modelsDir !== void 0 ? findUnregisteredDefinitions({
5582
- packageRoot,
5583
- documentModelsDir: modelsDir,
5584
- sources: loaded.sourceSet.sources,
5585
- importedFiles
5586
- }) : []
6713
+ unregistered: scan.unregistered
5587
6714
  };
5588
6715
  }
5589
6716
  //#endregion
5590
- export { DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, checkProjectDefinitions, documentModelChecks, formatDefinitionDiagnostic, inspectProjectDefinitions, loadProjectDefinitions, releaseChecks, resolveDefinitionSelection };
6717
+ export { DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, checkProjectDefinitions, documentModelChecks, formatDefinitionDiagnostic, formatDefinitionSource, inspectProjectDefinitions, loadProjectDefinitions, releaseChecks, resolveDefinitionSelection };
5591
6718
 
5592
6719
  //# sourceMappingURL=tooling.mjs.map