document-model 6.2.3-dev.101 → 6.2.3-dev.103

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
@@ -1,10 +1,10 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { DocumentModelGlobalStateSchema, defaultBaseState } from "@powerhousedao/shared/document-model";
3
- import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
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 { COMMONJS_DEFINITION_SOURCE, COMMONJS_DEFINITION_SOURCE_REPAIR, DEFAULT_AUTHORING_MODE, DEFINITION_SOURCE_EXTENSION, parseDefinitionSourcesConfig } from "@powerhousedao/shared/clis/definition-sources";
7
+ import { COMMONJS_DEFINITION_SOURCE, COMMONJS_DEFINITION_SOURCE_REPAIR, DEFINITION_SOURCE_EXTENSION, DOCUMENT_MODEL_ENTRY_FILES } from "@powerhousedao/shared/clis/definition-sources";
8
8
  import { pathWithin, realPathThroughExistingParent } from "@powerhousedao/shared/clis/real-paths";
9
9
  import { camelCase, constantCase, pascalCase } from "change-case";
10
10
  //#region src/definition/kernel/hashes.ts
@@ -1182,6 +1182,28 @@ function equalsPatternProblem(pattern) {
1182
1182
  }
1183
1183
  }
1184
1184
  //#endregion
1185
+ //#region src/definition/kernel/printer.ts
1186
+ const LINE = "\n";
1187
+ function isControlCodePoint(code) {
1188
+ return code < 32 || code === 127;
1189
+ }
1190
+ function hasControlCodePoint(value) {
1191
+ for (const point of value) if (isControlCodePoint(point.codePointAt(0) ?? 0)) return true;
1192
+ return false;
1193
+ }
1194
+ /**
1195
+ * A block string survives the lexer's dedent only when every line is nonempty
1196
+ * and carries no leading or trailing whitespace of its own, and the value ends
1197
+ * in neither a quote nor a backslash. Every other description prints as an
1198
+ * escaped single-line string, which always round-trips.
1199
+ */
1200
+ function blockStringable(value) {
1201
+ if (!value.includes(LINE)) return false;
1202
+ if (value.includes("\"\"\"")) return false;
1203
+ if (value.endsWith("\"") || value.endsWith("\\")) return false;
1204
+ return value.split(LINE).every((line) => line.length > 0 && line.trim() === line && !hasControlCodePoint(line) && !line.includes("\r"));
1205
+ }
1206
+ //#endregion
1185
1207
  //#region src/definition/kernel/graphql-ast.ts
1186
1208
  const AST_KINDS = {
1187
1209
  object: "ObjectTypeDefinition",
@@ -1729,7 +1751,7 @@ const NAMED_TYPE_MEMBERS = {
1729
1751
  input: "fields",
1730
1752
  union: "members"
1731
1753
  };
1732
- function namedType$2(check, value, path) {
1754
+ function namedType$3(check, value, path) {
1733
1755
  const kind = value?.kind;
1734
1756
  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);
1735
1757
  const typed = kind;
@@ -1866,7 +1888,7 @@ function operation(check, value, path) {
1866
1888
  "input",
1867
1889
  "kind"
1868
1890
  ], "An operation input is an input type.", "input", kind);
1869
- else namedType$2(check, node.input, [...path, "input"]);
1891
+ else namedType$3(check, node.input, [...path, "input"]);
1870
1892
  }
1871
1893
  check.array(node.errors, [...path, "errors"])?.forEach((entry, index) => {
1872
1894
  const at = [
@@ -1974,7 +1996,7 @@ function specification(check, value, path) {
1974
1996
  }
1975
1997
  const declared = /* @__PURE__ */ new Set();
1976
1998
  check.array(node.types, [...path, "types"])?.forEach((entry, index) => {
1977
- const name = namedType$2(check, entry, [
1999
+ const name = namedType$3(check, entry, [
1978
2000
  ...path,
1979
2001
  "types",
1980
2002
  index
@@ -2103,22 +2125,17 @@ const toolingDiagnostics = defineDiagnosticCatalog({
2103
2125
  "PH-CONFIG-SOURCE-INVALID": {
2104
2126
  severity: "error",
2105
2127
  phase: "configuration",
2106
- meaning: "The config file, a definition source entry, or an export pointer cannot select a module export"
2128
+ meaning: "The config file, the models directory, a model directory's entry, or an export pointer cannot select a module export"
2107
2129
  },
2108
2130
  "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE": {
2109
2131
  severity: "error",
2110
2132
  phase: "configuration",
2111
- meaning: "A definition source path, or the real path behind its symlinks, leaves the package root"
2133
+ meaning: "The models directory, a model directory, or the real path behind its symlinks, leaves the package root"
2112
2134
  },
2113
2135
  "PH-CONFIG-DUPLICATE-SOURCE": {
2114
2136
  severity: "error",
2115
2137
  phase: "configuration",
2116
- meaning: "Two entries select the same module and export path"
2117
- },
2118
- "PH-CONFIG-VERSION-UNSUPPORTED": {
2119
- severity: "error",
2120
- phase: "configuration",
2121
- meaning: "definitionSources declares a format version this release does not read"
2138
+ meaning: "Two sources select the same module and export path"
2122
2139
  },
2123
2140
  "PH-IMPORT-FAILED": {
2124
2141
  severity: "error",
@@ -2130,6 +2147,11 @@ const toolingDiagnostics = defineDiagnosticCatalog({
2130
2147
  phase: "package",
2131
2148
  meaning: "A selected export holds no materialized document model, family, or upgrade manifest"
2132
2149
  },
2150
+ "PH-PKG-STORED-SPEC-MISSING": {
2151
+ severity: "warning",
2152
+ phase: "package",
2153
+ meaning: "A model directory holds generated schema-first code without its stored specification"
2154
+ },
2133
2155
  "PH-PKG-DEFINITION-UNINSPECTABLE": {
2134
2156
  severity: "error",
2135
2157
  phase: "package",
@@ -2273,6 +2295,310 @@ function adaptCodeFirstDocumentModelSource(value, source) {
2273
2295
  };
2274
2296
  }
2275
2297
  //#endregion
2298
+ //#region src/definition/tooling/structured-diagnostics.ts
2299
+ function describeThrown(error) {
2300
+ if (error === null) return "null";
2301
+ try {
2302
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
2303
+ } catch {}
2304
+ return typeof error;
2305
+ }
2306
+ /** Reads an own data property without running a getter or a Proxy trap twice. */
2307
+ function readProperty(value, key) {
2308
+ try {
2309
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2310
+ if (descriptor === void 0 || !("value" in descriptor)) return { ok: false };
2311
+ return {
2312
+ ok: true,
2313
+ value: descriptor.value
2314
+ };
2315
+ } catch {
2316
+ return { ok: false };
2317
+ }
2318
+ }
2319
+ const DEFINITION_KINDS = [
2320
+ "document-model",
2321
+ "subgraph",
2322
+ "scalar",
2323
+ "package"
2324
+ ];
2325
+ function definitionRef(value) {
2326
+ const snapshot = snapshotRecord(value, void 0, []);
2327
+ if (!snapshot.ok) return void 0;
2328
+ const { kind, key, version } = snapshot.value;
2329
+ if (typeof key !== "string" || key === "" || !DEFINITION_KINDS.includes(kind)) return;
2330
+ return {
2331
+ kind,
2332
+ key,
2333
+ ...typeof version === "number" && { version }
2334
+ };
2335
+ }
2336
+ function isPathSegment(segment) {
2337
+ return typeof segment === "string" || typeof segment === "number" && Number.isSafeInteger(segment);
2338
+ }
2339
+ function definitionPath(value) {
2340
+ const path = snapshotArray(value, []);
2341
+ return path.ok && path.value.every(isPathSegment) ? path.value : void 0;
2342
+ }
2343
+ function relatedSource(value) {
2344
+ if (value === void 0) return void 0;
2345
+ const snapshot = snapshotRecord(value, void 0, []);
2346
+ if (!snapshot.ok) return null;
2347
+ const { specifier, exportPath } = snapshot.value;
2348
+ if (typeof specifier !== "string" || !specifier.startsWith("./")) return null;
2349
+ const source = { specifier };
2350
+ if (exportPath === void 0) return source;
2351
+ const path = snapshotArray(exportPath, []);
2352
+ if (!path.ok || !path.value.every((key) => typeof key === "string")) return null;
2353
+ return {
2354
+ ...source,
2355
+ exportPath: path.value
2356
+ };
2357
+ }
2358
+ function relatedLocations(value) {
2359
+ if (value === void 0) return void 0;
2360
+ const list = snapshotArray(value, []);
2361
+ if (!list.ok) return null;
2362
+ const locations = [];
2363
+ for (const candidate of list.value) {
2364
+ const entry = snapshotRecord(candidate, void 0, []);
2365
+ if (!entry.ok) return null;
2366
+ const path = definitionPath(entry.value.path);
2367
+ const source = relatedSource(entry.value.source);
2368
+ const { message } = entry.value;
2369
+ if (path === void 0 || source === null || typeof message !== "string") return null;
2370
+ locations.push({
2371
+ ...source !== void 0 && { source },
2372
+ path,
2373
+ message
2374
+ });
2375
+ }
2376
+ return locations;
2377
+ }
2378
+ function structuredDiagnostics(value, source) {
2379
+ if (value === null || typeof value !== "object" && typeof value !== "function") return;
2380
+ const list = readProperty(value, "diagnostics");
2381
+ if (!list.ok) return void 0;
2382
+ const snapshot = snapshotArray(list.value, []);
2383
+ if (!snapshot.ok || snapshot.value.length === 0) return void 0;
2384
+ const rebuilt = [];
2385
+ for (const candidate of snapshot.value) {
2386
+ const entry = snapshotRecord(candidate, void 0, []);
2387
+ if (!entry.ok) return void 0;
2388
+ const { code, message, repair, expected, received } = entry.value;
2389
+ const path = definitionPath(entry.value.path);
2390
+ const related = relatedLocations(entry.value.related);
2391
+ 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;
2392
+ const definition = definitionRef(entry.value.definition);
2393
+ rebuilt.push(toolingDiagnostics.create({
2394
+ code,
2395
+ source,
2396
+ ...definition !== void 0 && { definition },
2397
+ path,
2398
+ message,
2399
+ ...expected !== void 0 && { expected },
2400
+ ...received !== void 0 && { received },
2401
+ repair,
2402
+ ...related !== void 0 && { related }
2403
+ }));
2404
+ }
2405
+ return rebuilt;
2406
+ }
2407
+ //#endregion
2408
+ //#region src/definition/tooling/model-directories.ts
2409
+ /** @experimental The models directory a config without `documentModelsDir` uses. */
2410
+ const DEFAULT_DOCUMENT_MODELS_DIR = "./document-models";
2411
+ /** `./`-prefixed POSIX path of `path` inside `packageRoot`. */
2412
+ function packageSpecifier$1(packageRoot, path) {
2413
+ return `./${relative(packageRoot, path).split(sep).join("/")}`;
2414
+ }
2415
+ function statOrUndefined(path, stat = statSync) {
2416
+ return stat(path, { throwIfNoEntry: false });
2417
+ }
2418
+ function isDirectory(path) {
2419
+ return statOrUndefined(path)?.isDirectory() === true;
2420
+ }
2421
+ function hasGeneratedSchemaFirstLayout(directory) {
2422
+ if (isDirectory(join(directory, "gen"))) return true;
2423
+ return readdirSync(directory).some((name) => /^v\d+$/.test(name) && isDirectory(join(directory, name, "gen")));
2424
+ }
2425
+ function entryFiles(directory) {
2426
+ return DOCUMENT_MODEL_ENTRY_FILES.filter((name) => statOrUndefined(join(directory, name))?.isFile() === true);
2427
+ }
2428
+ /**
2429
+ * The configured models directory, resolved inside the package, or why it
2430
+ * cannot be read. The package root itself is refused: its directories are
2431
+ * the package's other sources, not models.
2432
+ */
2433
+ function resolveDocumentModelsDir(packageRoot, config) {
2434
+ const configured = config.documentModelsDir ?? "./document-models";
2435
+ const invalid = (message, received) => ({
2436
+ ok: false,
2437
+ diagnostic: toolingDiagnostics.create({
2438
+ code: "PH-CONFIG-SOURCE-INVALID",
2439
+ path: ["documentModelsDir"],
2440
+ message,
2441
+ expected: "a package-relative directory such as ./document-models",
2442
+ received,
2443
+ repair: "Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models."
2444
+ })
2445
+ });
2446
+ if (typeof configured !== "string" || configured.trim() === "") return invalid("documentModelsDir is not a directory path.", JSON.stringify(configured));
2447
+ const path = resolve(packageRoot, configured);
2448
+ let inside = pathWithin(packageRoot, path) !== null;
2449
+ try {
2450
+ inside &&= pathWithin(realpathSync.native(packageRoot), realPathThroughExistingParent(path)) !== null;
2451
+ } catch {
2452
+ inside = false;
2453
+ }
2454
+ if (!inside) return {
2455
+ ok: false,
2456
+ diagnostic: toolingDiagnostics.create({
2457
+ code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
2458
+ path: ["documentModelsDir"],
2459
+ message: "documentModelsDir leaves the package root, so its models are not this package's.",
2460
+ expected: "a directory inside the package",
2461
+ received: configured,
2462
+ repair: "Point documentModelsDir at a directory inside the package."
2463
+ })
2464
+ };
2465
+ if (resolve(path) === resolve(packageRoot)) return invalid("documentModelsDir names the package root, whose directories are not document models.", configured);
2466
+ let stats;
2467
+ try {
2468
+ stats = statOrUndefined(path);
2469
+ } catch {
2470
+ stats = void 0;
2471
+ }
2472
+ if (stats !== void 0 && !stats.isDirectory()) return invalid("documentModelsDir names a file, not a directory.", configured);
2473
+ return {
2474
+ ok: true,
2475
+ path
2476
+ };
2477
+ }
2478
+ function classify(packageRoot, packageRootIdentity, name, path, diagnostics) {
2479
+ const at = {
2480
+ name,
2481
+ path
2482
+ };
2483
+ const specification = join(path, `${name}.json`);
2484
+ const stored = statOrUndefined(specification, lstatSync) !== void 0;
2485
+ const generated = !stored && hasGeneratedSchemaFirstLayout(path);
2486
+ const entries = stored || generated ? [] : entryFiles(path);
2487
+ if (!stored && !generated && entries.length === 0) return {
2488
+ ...at,
2489
+ kind: "none"
2490
+ };
2491
+ const real = realpathSync.native(path);
2492
+ if (pathWithin(packageRootIdentity, real) === null) {
2493
+ diagnostics.push(toolingDiagnostics.create({
2494
+ code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
2495
+ source: { specifier: packageSpecifier$1(packageRoot, path) },
2496
+ path: [],
2497
+ message: "This model directory resolves through a symlink that leaves the package root, so its model is not this package's.",
2498
+ expected: "a model directory whose real path stays inside the package",
2499
+ received: packageSpecifier$1(packageRoot, path),
2500
+ repair: "Replace the symlink with a model directory that really lives in this package."
2501
+ }));
2502
+ return {
2503
+ ...at,
2504
+ kind: "invalid"
2505
+ };
2506
+ }
2507
+ if (stored) return {
2508
+ ...at,
2509
+ kind: "stored",
2510
+ specification: packageSpecifier$1(packageRoot, specification)
2511
+ };
2512
+ if (generated) {
2513
+ diagnostics.push(toolingDiagnostics.create({
2514
+ code: "PH-PKG-STORED-SPEC-MISSING",
2515
+ source: { specifier: packageSpecifier$1(packageRoot, path) },
2516
+ path: [],
2517
+ message: `This directory holds generated schema-first code but no ${name}.json, so the model it generated cannot be checked or regenerated.`,
2518
+ expected: packageSpecifier$1(packageRoot, specification),
2519
+ received: "generated code only",
2520
+ repair: `Restore ${name}.json from version control or export it again from the document model editor.`
2521
+ }));
2522
+ return {
2523
+ ...at,
2524
+ kind: "generated"
2525
+ };
2526
+ }
2527
+ if (entries.length > 1) {
2528
+ const found = entries.map((entry) => packageSpecifier$1(packageRoot, join(path, entry)));
2529
+ diagnostics.push(toolingDiagnostics.create({
2530
+ code: "PH-CONFIG-SOURCE-INVALID",
2531
+ source: { specifier: found[0] },
2532
+ path: [],
2533
+ message: "This model directory has several entry modules, so discovery cannot tell which one exports the model.",
2534
+ expected: "one index module per model directory",
2535
+ received: found.join(", "),
2536
+ repair: `Keep one of ${found.join(", ")} and delete or rename the others.`
2537
+ }));
2538
+ return {
2539
+ ...at,
2540
+ kind: "invalid"
2541
+ };
2542
+ }
2543
+ return {
2544
+ ...at,
2545
+ kind: "module",
2546
+ entry: packageSpecifier$1(packageRoot, join(path, entries[0]))
2547
+ };
2548
+ }
2549
+ /**
2550
+ * @experimental Classifies each immediate directory of the models directory
2551
+ * by the files it holds, without importing anything. Discovery never reads
2552
+ * the generated barrels beside the directories. A missing models directory
2553
+ * holds no models; a directory that cannot be read is `invalid` with a
2554
+ * diagnostic, so no caller mistakes it for an absent model.
2555
+ */
2556
+ function discoverDocumentModelDirectories(packageRoot, documentModelsDir) {
2557
+ const diagnostics = [];
2558
+ let names;
2559
+ let packageRootIdentity;
2560
+ try {
2561
+ packageRootIdentity = realpathSync.native(packageRoot);
2562
+ names = readdirSync(documentModelsDir);
2563
+ } catch (error) {
2564
+ if (error.code !== "ENOENT") diagnostics.push(unreadable$1(packageRoot, documentModelsDir, error));
2565
+ return {
2566
+ documentModelsDir,
2567
+ directories: [],
2568
+ diagnostics
2569
+ };
2570
+ }
2571
+ return {
2572
+ documentModelsDir,
2573
+ directories: names.filter((name) => name !== "node_modules" && !name.startsWith(".")).sort(compareCodeUnits).flatMap((name) => {
2574
+ const path = join(documentModelsDir, name);
2575
+ try {
2576
+ if (!isDirectory(path)) return [];
2577
+ return [classify(packageRoot, packageRootIdentity, name, path, diagnostics)];
2578
+ } catch (error) {
2579
+ diagnostics.push(unreadable$1(packageRoot, path, error));
2580
+ return [{
2581
+ name,
2582
+ path,
2583
+ kind: "invalid"
2584
+ }];
2585
+ }
2586
+ }),
2587
+ diagnostics
2588
+ };
2589
+ }
2590
+ function unreadable$1(packageRoot, path, error) {
2591
+ return toolingDiagnostics.create({
2592
+ code: "PH-IMPORT-FAILED",
2593
+ source: { specifier: packageSpecifier$1(packageRoot, path) },
2594
+ path: [],
2595
+ message: "This path under the document models directory could not be read, so discovery cannot tell which model it holds.",
2596
+ expected: "a readable directory",
2597
+ received: describeThrown(error),
2598
+ repair: "Fix the permissions of the path, or move it out of the document models directory."
2599
+ });
2600
+ }
2601
+ //#endregion
2276
2602
  //#region src/definition/tooling/definition-source-resolution.ts
2277
2603
  const CONFIG_FILE_NAME = "./powerhouse.config.json";
2278
2604
  const IDENTITY_SEPARATOR = String.fromCharCode(0);
@@ -2285,11 +2611,12 @@ function render(value) {
2285
2611
  return typeof value;
2286
2612
  }
2287
2613
  }
2288
- function sourceSet(mode, origin, sources) {
2614
+ function sourceSet(origin, documentModelsDir, sources, stored = []) {
2289
2615
  const value = {
2290
- mode,
2291
2616
  origin,
2292
- sources
2617
+ documentModelsDir,
2618
+ sources,
2619
+ stored
2293
2620
  };
2294
2621
  return {
2295
2622
  ...value,
@@ -2434,37 +2761,18 @@ function duplicateDiagnostics(sources) {
2434
2761
  code: "PH-CONFIG-DUPLICATE-SOURCE",
2435
2762
  source: first.source,
2436
2763
  path: first.position,
2437
- message: "Several entries select the same module and export path, so one of them can only repeat the other's definitions.",
2438
- expected: "one entry per module and export path",
2439
- received: `${group.length} entries`,
2440
- repair: "Remove every duplicate entry except one.",
2764
+ message: "Several sources reach the same module and export path, so one of them can only repeat the other's definitions. A model directory symlinked to another is one of them.",
2765
+ expected: "one source per module and export path",
2766
+ received: `${group.length} sources`,
2767
+ repair: "Remove every duplicate except one, or replace a symlinked model directory with the directory itself.",
2441
2768
  related: rest.map((entry) => ({
2442
2769
  source: entry.source,
2443
2770
  path: entry.position,
2444
- message: "This entry resolves to the same module and export path."
2771
+ message: "This source resolves to the same module and export path."
2445
2772
  }))
2446
2773
  });
2447
2774
  });
2448
2775
  }
2449
- function failed(roots, diagnostics, origin = "config", sources = []) {
2450
- return {
2451
- ...roots,
2452
- status: "failed",
2453
- sourceSet: sourceSet("code-first", origin, sources),
2454
- diagnostics: sortDefinitionDiagnostics(diagnostics),
2455
- resolved: []
2456
- };
2457
- }
2458
- function skipped(roots, skipReason, mode) {
2459
- return {
2460
- ...roots,
2461
- status: "skipped",
2462
- skipReason,
2463
- sourceSet: sourceSet(mode, "config", []),
2464
- diagnostics: [],
2465
- resolved: []
2466
- };
2467
- }
2468
2776
  const CONFIG_FAILURE_REPAIR = {
2469
2777
  missing: "Create the config file, or point --config-file at the package's existing one.",
2470
2778
  "read-failed": "Fix the permissions of the selected config file.",
@@ -2500,24 +2808,6 @@ function readConfigObject(configFile) {
2500
2808
  value: parsed
2501
2809
  };
2502
2810
  }
2503
- function selectionDiagnostic(narrowed) {
2504
- if (narrowed.reason === "unsupported-version") return toolingDiagnostics.create({
2505
- code: "PH-CONFIG-VERSION-UNSUPPORTED",
2506
- path: narrowed.path,
2507
- message: "The definitionSources format version is not one this release reads.",
2508
- expected: "1",
2509
- received: render(narrowed.received),
2510
- repair: "Set definitionSources.formatVersion to 1, or upgrade ph."
2511
- });
2512
- return toolingDiagnostics.create({
2513
- code: "PH-CONFIG-SOURCE-INVALID",
2514
- path: narrowed.path,
2515
- message: "The definitionSources selection is malformed.",
2516
- expected: narrowed.expected,
2517
- received: render(narrowed.received),
2518
- repair: `Set this member to ${narrowed.expected}.`
2519
- });
2520
- }
2521
2811
  /** The selected config file, its directory, and that directory's real path when it exists. */
2522
2812
  function packageRoots(request) {
2523
2813
  const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);
@@ -2536,174 +2826,130 @@ function packageRoots(request) {
2536
2826
  };
2537
2827
  }
2538
2828
  }
2539
- function resolveDefinitionSources(request) {
2829
+ function readPackage(request) {
2540
2830
  const { configFile, ...roots } = packageRoots(request);
2541
- const { packageRoot, packageRootIdentity } = roots;
2542
- if (request.allowMissingConfig === true && !existsSync(configFile)) return skipped(roots, "definition-sources-absent", DEFAULT_AUTHORING_MODE);
2543
- const config = readConfigObject(configFile);
2544
- if (!config.ok) return failed(roots, [toolingDiagnostics.create({
2545
- code: "PH-CONFIG-SOURCE-INVALID",
2546
- path: ["configFile"],
2547
- message: "The selected Powerhouse config file could not be read; its directory is the package root.",
2548
- expected: "an existing config file holding one JSON object",
2549
- received: config.reason,
2550
- repair: CONFIG_FAILURE_REPAIR[config.reason]
2551
- })]);
2552
- const origin = "config";
2553
- const narrowed = parseDefinitionSourcesConfig(config.value.definitionSources);
2554
- if (!narrowed.ok) return narrowed.reason === "missing" ? skipped(roots, "definition-sources-absent", DEFAULT_AUTHORING_MODE) : failed(roots, [selectionDiagnostic(narrowed)], origin);
2555
- if (narrowed.mode === "schema-first") return skipped(roots, "explicit-schema-first-mode", "schema-first");
2556
- if (narrowed.entries.length === 0) return skipped(roots, "definition-sources-empty", "code-first");
2557
- const normalized = narrowed.entries.map((value, index) => normalizeEntry(value, [
2558
- "definitionSources",
2559
- "entries",
2560
- index
2561
- ], packageRoot, packageRootIdentity));
2562
- const resolved = normalized.flatMap((result) => "source" in result ? [result.source] : []).sort((left, right) => compareDefinitionSources(left.source, right.source));
2563
- const sources = resolved.map((entry) => entry.source);
2564
- const entryDiagnostics = normalized.flatMap((result) => "diagnostic" in result ? [result.diagnostic] : []);
2565
- if (entryDiagnostics.length > 0) return failed(roots, entryDiagnostics, origin, sources);
2566
- const duplicates = duplicateDiagnostics(resolved);
2567
- if (duplicates.length > 0) return failed(roots, duplicates, origin, sources);
2831
+ const fallback = {
2832
+ ...roots,
2833
+ documentModelsDir: "./document-models"
2834
+ };
2835
+ let config = {};
2836
+ if (request.allowMissingConfig !== true || existsSync(configFile)) {
2837
+ const read = readConfigObject(configFile);
2838
+ if (!read.ok) return {
2839
+ ...fallback,
2840
+ ok: false,
2841
+ diagnostics: [toolingDiagnostics.create({
2842
+ code: "PH-CONFIG-SOURCE-INVALID",
2843
+ path: ["configFile"],
2844
+ message: "The selected Powerhouse config file could not be read; its directory is the package root.",
2845
+ expected: "an existing config file holding one JSON object",
2846
+ received: read.reason,
2847
+ repair: CONFIG_FAILURE_REPAIR[read.reason]
2848
+ })]
2849
+ };
2850
+ config = read.value;
2851
+ }
2852
+ const directory = resolveDocumentModelsDir(roots.packageRoot, config);
2853
+ if (!directory.ok) return {
2854
+ ...fallback,
2855
+ ok: false,
2856
+ diagnostics: [directory.diagnostic]
2857
+ };
2568
2858
  return {
2569
2859
  ...roots,
2570
- status: "ready",
2571
- sourceSet: sourceSet("code-first", origin, sources),
2572
- diagnostics: [],
2573
- resolved
2860
+ ok: true,
2861
+ documentModelsDir: packageSpecifier$1(roots.packageRoot, directory.path),
2862
+ documentModelsPath: directory.path,
2863
+ diagnostics: []
2574
2864
  };
2575
2865
  }
2576
- function publicResolution(value) {
2866
+ function failed(base, origin, diagnostics, sources = [], stored = []) {
2867
+ return {
2868
+ packageRoot: base.packageRoot,
2869
+ packageRootIdentity: base.packageRootIdentity,
2870
+ status: "failed",
2871
+ sourceSet: sourceSet(origin, base.documentModelsDir, sources, stored),
2872
+ diagnostics: sortDefinitionDiagnostics(diagnostics),
2873
+ resolved: []
2874
+ };
2875
+ }
2876
+ function resolveSources(base, origin, entries, stored, diagnostics) {
2877
+ const normalized = entries.map(({ value, position }) => normalizeEntry(value, position, base.packageRoot, base.packageRootIdentity));
2878
+ const candidates = normalized.flatMap((result) => "source" in result ? [result.source] : []).sort((left, right) => compareDefinitionSources(left.source, right.source));
2879
+ const resolved = origin === "discovery" ? candidates.filter((entry, index) => candidates.findIndex((other) => other.moduleIdentity === entry.moduleIdentity) === index) : candidates;
2880
+ const sources = resolved.map((entry) => entry.source);
2881
+ const errors = [...normalized.flatMap((result) => "diagnostic" in result ? [result.diagnostic] : []), ...duplicateDiagnostics(resolved)];
2882
+ if (errors.length > 0 || diagnostics.some(({ severity }) => severity === "error")) return failed(base, origin, [...diagnostics, ...errors], sources, stored);
2577
2883
  const common = {
2578
- packageRoot: value.packageRoot,
2579
- sourceSet: value.sourceSet,
2580
- diagnostics: value.diagnostics
2884
+ packageRoot: base.packageRoot,
2885
+ packageRootIdentity: base.packageRootIdentity,
2886
+ sourceSet: sourceSet(origin, base.documentModelsDir, sources, stored),
2887
+ diagnostics: sortDefinitionDiagnostics(diagnostics)
2581
2888
  };
2582
- return value.status === "skipped" ? {
2889
+ return sources.length === 0 ? {
2583
2890
  ...common,
2584
2891
  status: "skipped",
2585
- skipReason: value.skipReason
2892
+ skipReason: "no-document-models",
2893
+ resolved: []
2586
2894
  } : {
2587
2895
  ...common,
2588
- status: value.status
2896
+ status: "ready",
2897
+ resolved
2589
2898
  };
2590
2899
  }
2591
2900
  /**
2592
- * @experimental The selection a command would load, resolved without
2593
- * importing anything and without any machine-specific path but the root.
2901
+ * Discovers the package's model directories: each code-first directory's
2902
+ * entry module becomes a source, each schema-first one's stored file is
2903
+ * listed beside them. Nothing is imported.
2594
2904
  */
2595
- function resolveDefinitionSelection(request) {
2596
- return publicResolution(resolveDefinitionSources(request));
2597
- }
2598
- //#endregion
2599
- //#region src/definition/tooling/structured-diagnostics.ts
2600
- function describeThrown(error) {
2601
- if (error === null) return "null";
2602
- try {
2603
- if (error instanceof Error) return `${error.name}: ${error.message}`;
2604
- } catch {}
2605
- return typeof error;
2606
- }
2607
- /** Reads an own data property without running a getter or a Proxy trap twice. */
2608
- function readProperty(value, key) {
2609
- try {
2610
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2611
- if (descriptor === void 0 || !("value" in descriptor)) return { ok: false };
2612
- return {
2613
- ok: true,
2614
- value: descriptor.value
2615
- };
2616
- } catch {
2617
- return { ok: false };
2618
- }
2619
- }
2620
- const DEFINITION_KINDS = [
2621
- "document-model",
2622
- "subgraph",
2623
- "scalar",
2624
- "package"
2625
- ];
2626
- function definitionRef(value) {
2627
- const snapshot = snapshotRecord(value, void 0, []);
2628
- if (!snapshot.ok) return void 0;
2629
- const { kind, key, version } = snapshot.value;
2630
- if (typeof key !== "string" || key === "" || !DEFINITION_KINDS.includes(kind)) return;
2905
+ function resolveDefinitionSources(request) {
2906
+ const base = readPackage(request);
2907
+ if (!base.ok || base.documentModelsPath === void 0) return {
2908
+ ...failed(base, "discovery", base.diagnostics),
2909
+ directories: []
2910
+ };
2911
+ const found = discoverDocumentModelDirectories(base.packageRoot, base.documentModelsPath);
2631
2912
  return {
2632
- kind,
2633
- key,
2634
- ...typeof version === "number" && { version }
2913
+ ...resolveSources(base, "discovery", found.directories.flatMap((directory) => directory.kind === "module" ? [{
2914
+ value: { specifier: directory.entry },
2915
+ position: []
2916
+ }] : []), found.directories.flatMap((directory) => directory.kind === "stored" ? [{ specifier: directory.specification }] : []), found.diagnostics),
2917
+ documentModelsDir: base.documentModelsPath,
2918
+ directories: found.directories
2635
2919
  };
2636
2920
  }
2637
- function isPathSegment(segment) {
2638
- return typeof segment === "string" || typeof segment === "number" && Number.isSafeInteger(segment);
2639
- }
2640
- function definitionPath(value) {
2641
- const path = snapshotArray(value, []);
2642
- return path.ok && path.value.every(isPathSegment) ? path.value : void 0;
2921
+ /**
2922
+ * @experimental Resolves sources a caller names instead of discovering them.
2923
+ */
2924
+ function resolveRequestedSources(request) {
2925
+ const base = readPackage(request);
2926
+ if (!base.ok) return failed(base, "request", base.diagnostics);
2927
+ return resolveSources(base, "request", request.sources.map((value, index) => ({
2928
+ value,
2929
+ position: ["sources", index]
2930
+ })), [], []);
2643
2931
  }
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
2932
+ function publicResolution(value) {
2933
+ const common = {
2934
+ packageRoot: value.packageRoot,
2935
+ sourceSet: value.sourceSet,
2936
+ diagnostics: value.diagnostics
2937
+ };
2938
+ return value.status === "skipped" ? {
2939
+ ...common,
2940
+ status: "skipped",
2941
+ skipReason: value.skipReason
2942
+ } : {
2943
+ ...common,
2944
+ status: value.status
2657
2945
  };
2658
2946
  }
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
- }
2679
- function structuredDiagnostics(value, source) {
2680
- if (value === null || typeof value !== "object" && typeof value !== "function") return;
2681
- const list = readProperty(value, "diagnostics");
2682
- if (!list.ok) return void 0;
2683
- const snapshot = snapshotArray(list.value, []);
2684
- if (!snapshot.ok || snapshot.value.length === 0) return void 0;
2685
- const rebuilt = [];
2686
- for (const candidate of snapshot.value) {
2687
- const entry = snapshotRecord(candidate, void 0, []);
2688
- if (!entry.ok) return void 0;
2689
- const { code, message, repair, expected, received } = entry.value;
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;
2693
- const definition = definitionRef(entry.value.definition);
2694
- rebuilt.push(toolingDiagnostics.create({
2695
- code,
2696
- source,
2697
- ...definition !== void 0 && { definition },
2698
- path,
2699
- message,
2700
- ...expected !== void 0 && { expected },
2701
- ...received !== void 0 && { received },
2702
- repair,
2703
- ...related !== void 0 && { related }
2704
- }));
2705
- }
2706
- return rebuilt;
2947
+ /**
2948
+ * @experimental The sources discovery finds, resolved without importing
2949
+ * anything and without any machine-specific path but the root.
2950
+ */
2951
+ function resolveDefinitionSelection(request) {
2952
+ return publicResolution(resolveDefinitionSources(request));
2707
2953
  }
2708
2954
  //#endregion
2709
2955
  //#region src/definition/tooling/definition-source-loader.ts
@@ -2753,7 +2999,7 @@ function claim(collected, logicalKey, describe, source, path) {
2753
2999
  message: `Two different values both declare ${describe}, so a host registering this package would keep only one of them.`,
2754
3000
  expected: "one value per logical definition",
2755
3001
  received: describe,
2756
- repair: "Export one canonical value for this definition and remove the other source entry.",
3002
+ repair: "Export one canonical value for this definition and remove the other export.",
2757
3003
  related: [{
2758
3004
  source: existing.source,
2759
3005
  path: existing.path,
@@ -2786,6 +3032,10 @@ function collectUpgradeManifest(collected, value, source, path) {
2786
3032
  });
2787
3033
  claim(collected, ["upgrade-manifest", manifest.documentType].join(KEY_SEPARATOR), `the upgrade manifest of ${manifest.documentType}`, source, path);
2788
3034
  }
3035
+ /**
3036
+ * How many definitions `value` holds. One that an earlier source already
3037
+ * collected is counted again without being collected twice.
3038
+ */
2789
3039
  function visit(collected, value, source, path) {
2790
3040
  if (value === null || typeof value !== "object") return 0;
2791
3041
  const alias = collected.visited.get(value);
@@ -2855,7 +3105,7 @@ function checkManifestCoverage(collected) {
2855
3105
  message: "The upgrade manifest and the selected modules of this document type describe different version sets.",
2856
3106
  expected: `supportedVersions ${JSON.stringify(loaded)} with latestVersion ${String(loaded.at(-1))}`,
2857
3107
  received: `supportedVersions ${JSON.stringify(declared)} with latestVersion ${String(latestVersion)}`,
2858
- repair: "Select the whole family that materialize returned, so its modules and its manifest stay one declaration."
3108
+ repair: "Export the whole family that materialize returned, so its modules and its manifest stay one declaration."
2859
3109
  }));
2860
3110
  continue;
2861
3111
  }
@@ -2901,10 +3151,10 @@ function importDiagnostics(error, source, missing) {
2901
3151
  code: "PH-IMPORT-FAILED",
2902
3152
  source,
2903
3153
  path: [],
2904
- message: "definitionSources lists a module that does not exist.",
3154
+ message: "This source module does not exist.",
2905
3155
  expected: "an existing module inside the package",
2906
3156
  received: source.specifier,
2907
- repair: "Fix the specifier, or remove the entry from definitionSources.entries in powerhouse.config.json."
3157
+ repair: "Restore the module, or remove the model directory that names it."
2908
3158
  })];
2909
3159
  const structured = structuredDiagnostics(error, source);
2910
3160
  if (structured !== void 0) return structured;
@@ -2984,18 +3234,20 @@ function containedPackageModule(request) {
2984
3234
  };
2985
3235
  return real.reason === "outside" ? refusedModule(request.specifier, "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE", "The package module resolves through a symlink that leaves the package root.") : refusedModule(request.specifier, "PH-CONFIG-SOURCE-INVALID", "The package module path could not be resolved.");
2986
3236
  }
2987
- function empty(resolution) {
3237
+ function empty(resolution, discovered) {
2988
3238
  return {
2989
3239
  ...resolution,
3240
+ ...discovered,
2990
3241
  documentModels: [],
2991
- upgradeManifests: []
3242
+ upgradeManifests: [],
3243
+ sourcesWithDefinitions: []
2992
3244
  };
2993
3245
  }
2994
3246
  /**
2995
- * @experimental Imports the selected definition sources and finds the
3247
+ * @experimental Imports the discovered definition sources and finds the
2996
3248
  * materialized document models, families and upgrade manifests they export.
2997
3249
  * It folds aliases, reports two values that claim one `documentType@version`,
2998
- * and returns everything sorted by source, so neither config order nor
3250
+ * and returns everything sorted by source, so neither directory order nor
2999
3251
  * import completion order changes a result. Validity belongs to the
3000
3252
  * adapters; registration belongs to the host.
3001
3253
  */
@@ -3009,26 +3261,45 @@ var DefinitionSourceLoader = class {
3009
3261
  resolve(request) {
3010
3262
  return publicResolution(resolveDefinitionSources(request));
3011
3263
  }
3264
+ /**
3265
+ * Imports the entry module of every model directory discovery finds and
3266
+ * collects the models, families and upgrade manifests it exports.
3267
+ */
3012
3268
  async normalizeDefinitionSources(request) {
3013
3269
  request.signal?.throwIfAborted();
3014
3270
  const resolution = resolveDefinitionSources(request);
3015
- if (resolution.status !== "ready") return empty(publicResolution(resolution));
3271
+ return await this.#normalize(resolution, request, {
3272
+ ...resolution.documentModelsDir !== void 0 && { documentModelsDir: resolution.documentModelsDir },
3273
+ directories: resolution.directories
3274
+ });
3275
+ }
3276
+ /**
3277
+ * @experimental Loads sources the caller names, through the same imports
3278
+ * and checks as discovered ones.
3279
+ */
3280
+ async normalizeRequestedSources(request) {
3281
+ request.signal?.throwIfAborted();
3282
+ return await this.#normalize(resolveRequestedSources(request), request, {});
3283
+ }
3284
+ async #normalize(resolution, request, discovered) {
3285
+ if (resolution.status !== "ready") return empty(publicResolution(resolution), discovered);
3016
3286
  if (!isSha256Digest(request.packageRevision)) return empty({
3017
3287
  packageRoot: resolution.packageRoot,
3018
3288
  sourceSet: resolution.sourceSet,
3019
3289
  status: "failed",
3020
3290
  diagnostics: [revisionDiagnostic(request.packageRevision)]
3021
- });
3291
+ }, discovered);
3022
3292
  await this.#retainRevision(request.packageRevision);
3023
3293
  const namespaces = await this.#importModules(resolution, request);
3024
3294
  request.signal?.throwIfAborted();
3025
3295
  const collected = {
3026
3296
  documentModels: [],
3027
3297
  upgradeManifests: [],
3028
- diagnostics: [],
3298
+ diagnostics: [...resolution.diagnostics],
3029
3299
  visited: /* @__PURE__ */ new Map(),
3030
3300
  claimed: /* @__PURE__ */ new Map()
3031
3301
  };
3302
+ const sourcesWithDefinitions = [];
3032
3303
  for (const entry of resolution.resolved) {
3033
3304
  const namespace = namespaces.get(entry.moduleIdentity);
3034
3305
  if (namespace === void 0) continue;
@@ -3041,14 +3312,15 @@ var DefinitionSourceLoader = class {
3041
3312
  collected.diagnostics.push(selected.diagnostic);
3042
3313
  continue;
3043
3314
  }
3044
- if (visit(collected, selected.value, entry.source, []) === 0) collected.diagnostics.push(toolingDiagnostics.create({
3315
+ if (visit(collected, selected.value, entry.source, []) > 0) sourcesWithDefinitions.push(entry.source);
3316
+ else if (resolution.sourceSet.origin === "request") collected.diagnostics.push(toolingDiagnostics.create({
3045
3317
  code: "PH-PKG-DEFINITION-UNRECOGNIZED",
3046
3318
  source: entry.source,
3047
3319
  path: [],
3048
- message: "This source exports no materialized document model, so selecting it loads nothing.",
3320
+ message: "This source exports no materialized document model, so it adds no model to the package.",
3049
3321
  expected: "a module or family materialize returned, or a collection holding them",
3050
3322
  received: "no recognized definition",
3051
- repair: "Point this entry at the export that materialize(...) returned."
3323
+ repair: "Export the value materialize(...) returned from this module."
3052
3324
  }));
3053
3325
  }
3054
3326
  checkManifestCoverage(collected);
@@ -3056,10 +3328,12 @@ var DefinitionSourceLoader = class {
3056
3328
  return {
3057
3329
  packageRoot: resolution.packageRoot,
3058
3330
  sourceSet: resolution.sourceSet,
3331
+ ...discovered,
3059
3332
  status: diagnostics.some(({ severity }) => severity === "error") ? "failed" : "ready",
3060
3333
  diagnostics,
3061
3334
  documentModels: sortBySource(collected.documentModels),
3062
- upgradeManifests: sortBySource(collected.upgradeManifests)
3335
+ upgradeManifests: sortBySource(collected.upgradeManifests),
3336
+ sourcesWithDefinitions
3063
3337
  };
3064
3338
  }
3065
3339
  /**
@@ -3201,7 +3475,7 @@ const checkDiagnostics = defineDiagnosticCatalog({
3201
3475
  "PH-PKG-DEFINITION-UNREGISTERED": {
3202
3476
  severity: "error",
3203
3477
  phase: "package",
3204
- meaning: "A code-first document model under the document models directory is reached by no definitionSources entry, so the package leaves it out"
3478
+ meaning: "A code-first document model under the document models directory is exported by no model entry module, so the package leaves it out"
3205
3479
  }
3206
3480
  }, toolingDiagnostics);
3207
3481
  //#endregion
@@ -3733,7 +4007,7 @@ function assignStoredSegments(input) {
3733
4007
  /** graphql-js's reason for a bare `@deprecated`. */
3734
4008
  const DEFAULT_DEPRECATION_REASON = "No longer supported";
3735
4009
  const NAMED_TYPE_NODE = /^(?:Object|Interface|InputObject|Enum|Union)Type(?:Definition|Extension)$/;
3736
- function description(node) {
4010
+ function description$1(node) {
3737
4011
  return node === void 0 ? null : node.value;
3738
4012
  }
3739
4013
  function constValue(node) {
@@ -3783,7 +4057,7 @@ function inputField(node, declared) {
3783
4057
  return {
3784
4058
  key: node.name.value,
3785
4059
  name: node.name.value,
3786
- description: description(node.description),
4060
+ description: description$1(node.description),
3787
4061
  deprecated,
3788
4062
  type: typeReference(node.type, declared),
3789
4063
  ...node.defaultValue !== void 0 && { defaultValue: constValue(node.defaultValue) },
@@ -3795,7 +4069,7 @@ function outputField(node, declared) {
3795
4069
  return {
3796
4070
  key: node.name.value,
3797
4071
  name: node.name.value,
3798
- description: description(node.description),
4072
+ description: description$1(node.description),
3799
4073
  deprecated,
3800
4074
  ...node.arguments.length > 0 && { args: node.arguments.map((argument) => inputField(argument, declared)) },
3801
4075
  type: typeReference(node.type, declared),
@@ -3806,38 +4080,38 @@ function enumValue(node) {
3806
4080
  const { deprecated, uses } = directives(node.directives);
3807
4081
  return {
3808
4082
  name: node.name.value,
3809
- description: description(node.description),
4083
+ description: description$1(node.description),
3810
4084
  deprecated,
3811
4085
  ...uses !== void 0 && { directives: uses }
3812
4086
  };
3813
4087
  }
3814
- function namedType$1(node, declared) {
4088
+ function namedType$2(node, declared) {
3815
4089
  switch (node.kind) {
3816
4090
  case "ObjectTypeDefinition":
3817
4091
  case "InterfaceTypeDefinition": return {
3818
4092
  kind: node.kind === "ObjectTypeDefinition" ? "object" : "interface",
3819
4093
  name: node.name.value,
3820
- description: description(node.description),
4094
+ description: description$1(node.description),
3821
4095
  ...node.interfaces.length > 0 && { implements: node.interfaces.map((entry) => entry.name.value) },
3822
4096
  fields: node.fields.map((field) => outputField(field, declared))
3823
4097
  };
3824
4098
  case "InputObjectTypeDefinition": return {
3825
4099
  kind: "input",
3826
4100
  name: node.name.value,
3827
- description: description(node.description),
4101
+ description: description$1(node.description),
3828
4102
  unknownKeys: "preserve",
3829
4103
  fields: node.fields.map((field) => inputField(field, declared))
3830
4104
  };
3831
4105
  case "EnumTypeDefinition": return {
3832
4106
  kind: "enum",
3833
4107
  name: node.name.value,
3834
- description: description(node.description),
4108
+ description: description$1(node.description),
3835
4109
  values: node.values.map(enumValue)
3836
4110
  };
3837
4111
  case "UnionTypeDefinition": return {
3838
4112
  kind: "union",
3839
4113
  name: node.name.value,
3840
- description: description(node.description),
4114
+ description: description$1(node.description),
3841
4115
  members: node.types.map((member) => member.name.value)
3842
4116
  };
3843
4117
  }
@@ -3857,7 +4131,7 @@ function declaredTypeNames(definitions) {
3857
4131
  * reference is a scalar.
3858
4132
  */
3859
4133
  function structuredTypes(definitions, declared = declaredTypeNames(definitions)) {
3860
- return [...foldTypeExtensions(definitions, []).types.values()].map(({ node }) => namedType$1(node, declared));
4134
+ return [...foldTypeExtensions(definitions, []).types.values()].map(({ node }) => namedType$2(node, declared));
3861
4135
  }
3862
4136
  function namedTypeName(node) {
3863
4137
  return node.kind === "NamedType" ? node.name.value : namedTypeName(node.type);
@@ -4273,23 +4547,44 @@ const storedMaterializationCheck = {
4273
4547
  };
4274
4548
  //#endregion
4275
4549
  //#region src/definition/tooling/check/checks/unregistered-definitions.ts
4550
+ function described({ unit, specifier, reason }) {
4551
+ const entry = `${unit}index.ts`;
4552
+ switch (reason) {
4553
+ case "stored-directory": return {
4554
+ message: `${unit} stores a schema-first specification, so discovery reads it as schema-first and leaves out the code-first document model ${specifier} declares.`,
4555
+ expected: "one authoring style per model directory",
4556
+ received: "a stored specification and a code-first declaration",
4557
+ repair: `Move the code-first model to a directory of its own with an index.ts that exports it, or delete the stored specification in ${unit}.`
4558
+ };
4559
+ case "not-exported": return {
4560
+ message: `${unit} declares a code-first document model that an entry module imports but does not export, so the package leaves it out.`,
4561
+ expected: `an entry module that exports the model ${specifier} declares`,
4562
+ received: "imported, not exported",
4563
+ repair: specifier === entry ? `Export the value materialize(...) returned from ${entry}.` : `Export from ${entry} the value materialize(...) returned for the model ${specifier} declares.`
4564
+ };
4565
+ case "unreached": return {
4566
+ message: `${unit} declares a code-first document model that no model entry module exports, so the package leaves it out.`,
4567
+ expected: `${entry} exporting the model ${specifier} declares`,
4568
+ received: "no entry",
4569
+ repair: specifier === entry ? `Export the value materialize(...) returned from ${entry}.` : `Create ${entry} and export from it the value materialize(...) returned for the model ${specifier} declares.`
4570
+ };
4571
+ default: return reason;
4572
+ }
4573
+ }
4276
4574
  /** Turns each declaration the project scan found unregistered into one diagnostic. */
4277
4575
  const unregisteredDefinitionsCheck = {
4278
4576
  name: "unregistered-definitions",
4279
- run: ({ unregistered }) => unregistered.map(({ unit, specifier, reason }) => {
4280
- const entry = `{ "specifier": "${specifier}" }`;
4281
- const notExported = reason === "not-exported";
4282
- return checkDiagnostics.create({
4283
- code: "PH-PKG-DEFINITION-UNREGISTERED",
4284
- source: { specifier },
4285
- path: [],
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",
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.`
4290
- });
4291
- })
4577
+ run: ({ unregistered }) => unregisteredDefinitionDiagnostics(unregistered)
4292
4578
  };
4579
+ /** @experimental Reports declarations that an entry does not publish. */
4580
+ function unregisteredDefinitionDiagnostics(unregistered) {
4581
+ return unregistered.map((definition) => checkDiagnostics.create({
4582
+ code: "PH-PKG-DEFINITION-UNREGISTERED",
4583
+ source: { specifier: definition.specifier },
4584
+ path: [],
4585
+ ...described(definition)
4586
+ }));
4587
+ }
4293
4588
  //#endregion
4294
4589
  //#region src/definition/tooling/report/status.ts
4295
4590
  /** These phases mean the tool could not read the package, not that a model is wrong. */
@@ -4332,7 +4627,7 @@ function definitionCheckReport(input) {
4332
4627
  const errors = diagnostics.filter(({ severity }) => severity === "error").length;
4333
4628
  const common = {
4334
4629
  kind: "powerhouse.definition-check",
4335
- formatVersion: 1,
4630
+ formatVersion: 2,
4336
4631
  profile: input.profile,
4337
4632
  sourceSet: input.sourceSet,
4338
4633
  definitions,
@@ -4652,7 +4947,7 @@ function unknownSelection(selection, artifacts) {
4652
4947
  message: `No model of this package serves ${selected}.`,
4653
4948
  expected: available.length === 0 ? "a package with a model" : listed,
4654
4949
  received: selected,
4655
- repair: available.length === 0 ? "Add a document model to the package, or register its code-first source in definitionSources." : `Inspect one of: ${listed}.`
4950
+ repair: available.length === 0 ? "Add a document model to the package: a stored <name>/<name>.json, or a code-first <name>/index.ts under the models directory." : `Inspect one of: ${listed}.`
4656
4951
  });
4657
4952
  }
4658
4953
  /**
@@ -4668,7 +4963,7 @@ function inspectProjectDefinitions(project, options = {}) {
4668
4963
  const diagnostics = sortedUniqueDiagnostics([...project.diagnostics, ...selection === void 0 ? [] : selected.length === 0 ? [unknownSelection(selection, artifacts)] : logicalCollisionDiagnostics(project.sourceSet, selected)]);
4669
4964
  return {
4670
4965
  kind: "powerhouse.definition-inspection",
4671
- formatVersion: 1,
4966
+ formatVersion: 2,
4672
4967
  status: definitionStatus({
4673
4968
  ...project.skipReason !== void 0 && { skipReason: project.skipReason },
4674
4969
  definitions: artifacts,
@@ -4681,38 +4976,328 @@ function inspectProjectDefinitions(project, options = {}) {
4681
4976
  };
4682
4977
  }
4683
4978
  //#endregion
4684
- //#region src/definition/tooling/schema-first/project-scalars.ts
4685
- /** Where codegen reads a package's `defineScalar` exports from. */
4686
- const PROJECT_SCALARS_SPECIFIER = "./scalars/index.ts";
4687
- /** The scalars `scalars/index.ts` exports, imported like the selected sources. */
4688
- async function loadProjectScalars(request) {
4689
- const { loader, packageRoot, configFile, packageRevision, signal } = request;
4690
- if (!existsSync(join(packageRoot, "scalars", "index.ts"))) return {
4691
- definitions: [],
4692
- diagnostics: []
4979
+ //#region src/definition/tooling/project/unregistered-definitions.ts
4980
+ const DECLARATION = {
4981
+ module: /^document-model(?:\/|$)/,
4982
+ factory: "defineDocumentModel(?:Family)?"
4983
+ };
4984
+ const NAMED_IMPORT = /\bimport\s*\{([^}]*)\}\s*from\s*"#(\d+)"/g;
4985
+ const NAMESPACE_IMPORT = /\bimport\s*\*\s*as\s+([\w$]+)\s*from\s*"#(\d+)"/g;
4986
+ function startsRegExp(code) {
4987
+ const before = code.slice(-64).trimEnd();
4988
+ return before === "" || /[(,=:[!&|?{};+\-*%<>~^}]$/.test(before) || /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(before);
4989
+ }
4990
+ function lexCodeAndStrings(text) {
4991
+ let code = "";
4992
+ const strings = [];
4993
+ const literal = (contents) => {
4994
+ code += `"#${strings.length}"`;
4995
+ strings.push(contents);
4693
4996
  };
4694
- const imported = await loader.importPackageModule({
4695
- configFile,
4696
- packageRevision,
4697
- ...signal !== void 0 && { signal },
4698
- specifier: PROJECT_SCALARS_SPECIFIER
4699
- });
4700
- if (!imported.ok) return {
4701
- definitions: [],
4702
- diagnostics: imported.diagnostics
4997
+ let braces = 0;
4998
+ const templates = [];
4999
+ let i = 0;
5000
+ const skipQuoted = (end) => {
5001
+ while (i < text.length && !end(i)) i += text[i] === "\\" ? 2 : 1;
4703
5002
  };
5003
+ while (i < text.length) {
5004
+ const char = text[i];
5005
+ if (char === "/" && text[i + 1] === "/") {
5006
+ i = text.indexOf("\n", i);
5007
+ if (i === -1) i = text.length;
5008
+ } else if (char === "/" && text[i + 1] === "*") {
5009
+ const end = text.indexOf("*/", i + 2);
5010
+ i = end === -1 ? text.length : end + 2;
5011
+ code += " ";
5012
+ } else if (char === "/" && startsRegExp(code)) {
5013
+ i += 1;
5014
+ let inClass = false;
5015
+ while (i < text.length && text[i] !== "\n") {
5016
+ if (text[i] === "\\") i += 1;
5017
+ else if (text[i] === "[") inClass = true;
5018
+ else if (text[i] === "]") inClass = false;
5019
+ else if (text[i] === "/" && !inClass) break;
5020
+ i += 1;
5021
+ }
5022
+ i += 1;
5023
+ while (/[a-z]/.test(text[i] ?? "")) i += 1;
5024
+ code += " ";
5025
+ } else if (char === "\"" || char === "'") {
5026
+ const start = i += 1;
5027
+ skipQuoted((at) => text[at] === char || text[at] === "\n");
5028
+ literal(text.slice(start, i));
5029
+ i += 1;
5030
+ } else if (char === "`" || char === "}" && templates.at(-1) === braces) {
5031
+ const whole = char === "`";
5032
+ if (!whole) templates.pop();
5033
+ const start = i += 1;
5034
+ skipQuoted((at) => text[at] === "`" || text[at] === "$" && text[at + 1] === "{");
5035
+ const closed = text[i] === "`";
5036
+ literal(whole && closed ? text.slice(start, i) : "");
5037
+ if (closed) i += 1;
5038
+ else {
5039
+ templates.push(braces);
5040
+ i += 2;
5041
+ }
5042
+ } else {
5043
+ if (char === "{") braces += 1;
5044
+ if (char === "}") braces -= 1;
5045
+ code += char;
5046
+ i += 1;
5047
+ }
5048
+ }
4704
5049
  return {
4705
- definitions: Object.entries(imported.namespace).flatMap(([exportName, value]) => isScalarDefinition(value) && value.name === exportName ? [value] : []).sort((left, right) => compareCodeUnits(left.name, right.name)),
4706
- diagnostics: []
5050
+ code,
5051
+ strings
4707
5052
  };
4708
5053
  }
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) {
5054
+ /** `type as e` imports a value named `type`. */
5055
+ function valueBindings(clause) {
5056
+ return clause.split(",").map((part) => part.trim()).filter((part) => part !== "" && !/^type\s+(?!as\b)/.test(part)).map((part) => {
5057
+ const [imported, local = imported] = part.split(/\s+as\s+/);
5058
+ return {
5059
+ imported,
5060
+ local
5061
+ };
5062
+ });
5063
+ }
5064
+ function isSourceFile(name) {
5065
+ return DEFINITION_SOURCE_EXTENSION.test(name) && !/\.d\.m?ts$/.test(name);
5066
+ }
5067
+ function isTestFile(name) {
5068
+ return /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/.test(name);
5069
+ }
5070
+ /**
5071
+ * Sorted, with symlinks followed. An entry whose real path cannot be read, or
5072
+ * leaves the package, is not the package's and is skipped; a directory that
5073
+ * cannot be listed goes to `unreadable`.
5074
+ */
5075
+ function packageEntries(path, packageRootIdentity, unreadable) {
5076
+ let names;
5077
+ try {
5078
+ names = readdirSync(path);
5079
+ } catch (error) {
5080
+ unreadable.push({
5081
+ path,
5082
+ error
5083
+ });
5084
+ return [];
5085
+ }
5086
+ return names.filter((name) => name !== "node_modules" && !name.startsWith(".")).sort(compareCodeUnits).flatMap((name) => {
5087
+ const child = join(path, name);
5088
+ try {
5089
+ const real = realpathSync.native(child);
5090
+ if (pathWithin(packageRootIdentity, real) === null) return [];
5091
+ return [{
5092
+ name,
5093
+ path: child,
5094
+ real,
5095
+ isDirectory: statSync(real).isDirectory()
5096
+ }];
5097
+ } catch {
5098
+ return [];
5099
+ }
5100
+ });
5101
+ }
5102
+ /** `visited` holds real directories, so a symlink cycle ends. */
5103
+ function sourceFilesUnder(directory, packageRootIdentity, visited, unreadable) {
5104
+ if (visited.has(directory.real)) return [];
5105
+ visited.add(directory.real);
5106
+ return packageEntries(directory.path, packageRootIdentity, unreadable).flatMap((entry) => {
5107
+ if (entry.isDirectory) return entry.name === "__tests__" ? [] : sourceFilesUnder(entry, packageRootIdentity, visited, unreadable);
5108
+ return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];
5109
+ });
5110
+ }
5111
+ /**
5112
+ * The object literal's own `id` when its source spells it as a plain string.
5113
+ * A spread can override it and an escape changes its spelling, so either
5114
+ * leaves it unknown.
5115
+ */
5116
+ function topLevelId(code, strings, open) {
5117
+ let depth = 0;
5118
+ let id;
5119
+ for (let i = open; i < code.length; i += 1) {
5120
+ const char = code[i];
5121
+ if ("{([".includes(char)) depth += 1;
5122
+ else if ("})]".includes(char)) {
5123
+ depth -= 1;
5124
+ if (depth === 0) break;
5125
+ } else if (depth === 1 && code.startsWith("...", i)) return;
5126
+ else if (depth === 1 && !/[\w$]/.test(code[i - 1] ?? "")) {
5127
+ const rest = code.slice(i, i + 16);
5128
+ const quoted = /^"#(\d+)"\s*:\s*/.exec(rest);
5129
+ const key = /^id\s*:\s*/.exec(rest) ?? (quoted !== null && strings[+quoted[1]] === "id" ? quoted : null);
5130
+ if (key !== null) {
5131
+ const value = /^"#(\d+)"/.exec(code.slice(i + key[0].length));
5132
+ id = value === null ? void 0 : strings[+value[1]];
5133
+ }
5134
+ }
5135
+ }
5136
+ return id === void 0 || id === "" || id.includes("\\") ? void 0 : id;
5137
+ }
5138
+ function declarations(code, strings) {
5139
+ const { module, factory } = DECLARATION;
5140
+ const isFactory = new RegExp(`^${factory}$`);
5141
+ 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 }) => ({
5142
+ callee: escapeRegExp(local),
5143
+ family: imported !== "defineDocumentModel"
5144
+ }))), ...[...code.matchAll(NAMESPACE_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).flatMap(([, namespace]) => [false, true].map((family) => ({
5145
+ callee: `${escapeRegExp(namespace)}\\s*\\.\\s*defineDocumentModel${family ? "Family" : ""}`,
5146
+ family
5147
+ })))];
5148
+ let declares = false;
5149
+ const ids = [];
5150
+ for (const { callee, family } of callees) {
5151
+ const calls = new RegExp(`(?<![\\w$.])${callee}\\s*(?:<[^;()]*>\\s*)?\\((?:\\s*\\{)?`, "g");
5152
+ for (const call of code.matchAll(calls)) {
5153
+ declares = true;
5154
+ const id = family || !call[0].endsWith("{") ? void 0 : topLevelId(code, strings, call.index + call[0].length - 1);
5155
+ if (id !== void 0) ids.push(id);
5156
+ }
5157
+ }
5158
+ return {
5159
+ declares,
5160
+ ids
5161
+ };
5162
+ }
5163
+ function escapeRegExp(name) {
5164
+ return name.replaceAll("$", "\\$");
5165
+ }
5166
+ function packagePath(root, path) {
5167
+ return `./${relative(root, path).split(sep).join("/")}`;
5168
+ }
5169
+ function realPathOrSelf(path) {
5170
+ try {
5171
+ return realpathSync.native(path);
5172
+ } catch {
5173
+ return path;
5174
+ }
5175
+ }
5176
+ /** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */
5177
+ function modelUnit(packageRoot, packageRootIdentity, directory, unreadable) {
5178
+ const declaring = [];
5179
+ for (const entry of sourceFilesUnder(directory, packageRootIdentity, /* @__PURE__ */ new Set(), unreadable)) {
5180
+ let text;
5181
+ try {
5182
+ text = readFileSync(entry.real, "utf8");
5183
+ } catch (error) {
5184
+ unreadable.push({
5185
+ path: entry.path,
5186
+ error
5187
+ });
5188
+ continue;
5189
+ }
5190
+ const { code, strings } = lexCodeAndStrings(text);
5191
+ const found = declarations(code, strings);
5192
+ if (found.declares) declaring.push({
5193
+ entry,
5194
+ ids: found.ids
5195
+ });
5196
+ }
5197
+ const index = join(directory.path, "index.ts");
5198
+ const suggested = declaring.find(({ entry }) => entry.path === index) ?? declaring.at(0);
5199
+ if (suggested === void 0) return void 0;
5200
+ return {
5201
+ kind: "document-model",
5202
+ unit: `${packagePath(packageRoot, directory.path)}/`,
5203
+ specifier: packagePath(packageRoot, suggested.entry.path),
5204
+ declaring: declaring.map(({ entry }) => entry.real),
5205
+ ids: declaring.flatMap(({ ids }) => ids)
5206
+ };
5207
+ }
5208
+ function unreadableDiagnostic(packageRoot, { path, error }) {
5209
+ return toolingDiagnostics.create({
5210
+ code: "PH-IMPORT-FAILED",
5211
+ source: { specifier: packagePath(packageRoot, path) },
5212
+ path: [],
5213
+ 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 model entry exports.",
5214
+ expected: "a readable file or directory",
5215
+ received: describeThrown(error),
5216
+ repair: "Fix the permissions of the path, or move it out of the document models directory."
5217
+ });
5218
+ }
5219
+ /**
5220
+ * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model
5221
+ * that no entry module's import reached, or that an entry reached without
5222
+ * exporting the model's literal id. An entry that did not import reaches
5223
+ * files no one can name, so the scan then reports nothing.
5224
+ */
5225
+ function findUnregisteredDefinitions(request) {
5226
+ const { packageRoot, documentModelsDir, sources, importedFiles, loadedDocumentTypes, storedUnits = /* @__PURE__ */ new Set() } = request;
5227
+ const imported = sources.map(({ specifier }) => importedFiles(specifier));
5228
+ if (imported.some((files) => files.length === 0)) return {
5229
+ unregistered: [],
5230
+ diagnostics: []
5231
+ };
5232
+ const reached = new Set(imported.flat().map(realPathOrSelf));
5233
+ const packageRootIdentity = realPathOrSelf(packageRoot);
5234
+ const unreadable = [];
5235
+ const directories = packageEntries(documentModelsDir, packageRootIdentity, []).filter(({ isDirectory }) => isDirectory);
5236
+ const units = directories.flatMap((entry) => modelUnit(packageRoot, packageRootIdentity, entry, unreadable) ?? []);
5237
+ const modelDirectories = new Set(directories.map(({ path }) => path));
5238
+ return {
5239
+ unregistered: units.flatMap(({ kind, unit, specifier, declaring, ids }) => {
5240
+ const isReached = declaring.some((file) => reached.has(file));
5241
+ if (isReached && ids.every((id) => loadedDocumentTypes.has(id))) return [];
5242
+ return [{
5243
+ kind,
5244
+ unit,
5245
+ specifier,
5246
+ reason: storedUnits.has(unit) ? "stored-directory" : isReached ? "not-exported" : "unreached"
5247
+ }];
5248
+ }),
5249
+ diagnostics: unreadable.filter(({ path }) => !modelDirectories.has(path)).map((entry) => unreadableDiagnostic(packageRoot, entry))
5250
+ };
5251
+ }
5252
+ /**
5253
+ * @experimental The package-relative files under `directory` that declare a
5254
+ * code-first document model, read from source text without running them.
5255
+ * Codegen refuses to write a stored model over them.
5256
+ */
5257
+ function codeFirstDeclarationFiles(packageRoot, directory) {
5258
+ const packageRootIdentity = realPathOrSelf(packageRoot);
5259
+ const real = realPathOrSelf(directory);
5260
+ if (pathWithin(packageRootIdentity, real) === null) return [];
5261
+ return (modelUnit(packageRoot, packageRootIdentity, {
5262
+ name: "",
5263
+ path: directory,
5264
+ real,
5265
+ isDirectory: true
5266
+ }, [])?.declaring ?? []).map((file) => packagePath(packageRootIdentity, file));
5267
+ }
5268
+ //#endregion
5269
+ //#region src/definition/tooling/schema-first/project-scalars.ts
5270
+ /** Where codegen reads a package's `defineScalar` exports from. */
5271
+ const PROJECT_SCALARS_SPECIFIER = "./scalars/index.ts";
5272
+ /** The scalars `scalars/index.ts` exports, imported like the selected sources. */
5273
+ async function loadProjectScalars(request) {
5274
+ const { loader, packageRoot, configFile, packageRevision, signal } = request;
5275
+ if (!existsSync(join(packageRoot, "scalars", "index.ts"))) return {
5276
+ definitions: [],
5277
+ diagnostics: []
5278
+ };
5279
+ const imported = await loader.importPackageModule({
5280
+ configFile,
5281
+ packageRevision,
5282
+ ...signal !== void 0 && { signal },
5283
+ specifier: PROJECT_SCALARS_SPECIFIER
5284
+ });
5285
+ if (!imported.ok) return {
5286
+ definitions: [],
5287
+ diagnostics: imported.diagnostics
5288
+ };
5289
+ return {
5290
+ definitions: Object.entries(imported.namespace).flatMap(([exportName, value]) => isScalarDefinition(value) && value.name === exportName ? [value] : []).sort((left, right) => compareCodeUnits(left.name, right.name)),
5291
+ diagnostics: []
5292
+ };
5293
+ }
5294
+ //#endregion
5295
+ //#region src/definition/compiler/initial-value.ts
5296
+ function serializeAndValidateInitialValue(root, value) {
5297
+ let serialized;
5298
+ try {
5299
+ serialized = JSON.stringify(value);
5300
+ } catch (error) {
4716
5301
  return {
4717
5302
  ok: false,
4718
5303
  reason: "not-serializable",
@@ -5311,7 +5896,7 @@ function enumValues(input) {
5311
5896
  });
5312
5897
  }));
5313
5898
  }
5314
- function namedType(node) {
5899
+ function namedType$1(node) {
5315
5900
  const descriptor = {
5316
5901
  ...node,
5317
5902
  role: NAMED_TYPE_ROLE,
@@ -5365,13 +5950,13 @@ function implementedInterfaces(config) {
5365
5950
  return Object.freeze([...implemented]);
5366
5951
  }
5367
5952
  function objectType(name, options) {
5368
- return namedType({
5953
+ return namedType$1({
5369
5954
  kind: "object",
5370
5955
  ...implementingMembers(name, options)
5371
5956
  });
5372
5957
  }
5373
5958
  function interfaceType(name, options) {
5374
- return namedType({
5959
+ return namedType$1({
5375
5960
  kind: "interface",
5376
5961
  ...implementingMembers(name, options)
5377
5962
  });
@@ -5454,7 +6039,7 @@ const ph = scalarFactoryGuard({
5454
6039
  enum(name, options) {
5455
6040
  const validName = assertAuthoredName(name, ["name"]);
5456
6041
  const config = snapshotDescriptorOptions(options, ["values", "description"], ["options"]);
5457
- return namedType({
6042
+ return namedType$1({
5458
6043
  kind: "enum",
5459
6044
  name: validName,
5460
6045
  description: stringOption(config, "description", ["options"]),
@@ -5467,7 +6052,7 @@ const ph = scalarFactoryGuard({
5467
6052
  const [nameOrOptions, maybeOptions] = args;
5468
6053
  const name = typeof nameOrOptions === "string" ? assertAuthoredName(nameOrOptions, ["name"]) : null;
5469
6054
  const config = snapshotDescriptorOptions(typeof nameOrOptions === "string" ? maybeOptions : nameOrOptions, ["fields", "description"], ["options"]);
5470
- return namedType({
6055
+ return namedType$1({
5471
6056
  kind: "input",
5472
6057
  name,
5473
6058
  description: stringOption(config, "description", ["options"]),
@@ -5509,7 +6094,7 @@ const ph = scalarFactoryGuard({
5509
6094
  });
5510
6095
  seen.add(memberName);
5511
6096
  });
5512
- return namedType({
6097
+ return namedType$1({
5513
6098
  kind: "union",
5514
6099
  name: validName,
5515
6100
  description: stringOption(config, "description", ["options"]),
@@ -6154,37 +6739,35 @@ function outsidePackage(specifier) {
6154
6739
  });
6155
6740
  }
6156
6741
  /**
6157
- * A missing models directory holds no models; any other read failure is
6158
- * reported. A symlinked model directory or file counts when its real path
6159
- * stays in the package.
6742
+ * The stored specifications discovery listed. A symlinked file counts when
6743
+ * its real path stays in the package; anything but a readable file is
6744
+ * reported, never skipped, because discovery already gave the directory to
6745
+ * a schema-first model.
6160
6746
  */
6161
- function storedModelFiles(packageRoot, documentModelsDir) {
6162
- let names;
6747
+ function storedModelFiles(packageRoot, stored) {
6163
6748
  let packageRootIdentity;
6164
6749
  try {
6165
6750
  packageRootIdentity = realpathSync.native(packageRoot);
6166
- names = readdirSync(documentModelsDir).sort(compareCodeUnits);
6167
6751
  } catch (error) {
6168
6752
  return {
6169
6753
  files: [],
6170
- diagnostics: error.code === "ENOENT" ? [] : [unreadable(packageRoot, documentModelsDir, "document models directory", error)]
6754
+ diagnostics: [unreadable(packageRoot, packageRoot, "package root", error)]
6171
6755
  };
6172
6756
  }
6173
6757
  const files = [];
6174
6758
  const diagnostics = [];
6175
- for (const name of names) {
6176
- const directory = join(documentModelsDir, name);
6177
- const file = join(directory, `${name}.json`);
6759
+ for (const { specifier } of stored) {
6760
+ const file = join(packageRoot, ...specifier.slice(2).split("/"));
6178
6761
  let real;
6179
6762
  try {
6180
- if (!statSync(directory, { throwIfNoEntry: false })?.isDirectory() || !statSync(file, { throwIfNoEntry: false })?.isFile()) continue;
6763
+ if (!statSync(file).isFile()) throw new Error(`${specifier} is not a file.`);
6181
6764
  real = realpathSync.native(file);
6182
6765
  } catch (error) {
6183
- diagnostics.push(unreadable(packageRoot, directory, "document model directory", error));
6766
+ diagnostics.push(unreadable(packageRoot, file, "stored document model file", error));
6184
6767
  continue;
6185
6768
  }
6186
6769
  if (pathWithin(packageRootIdentity, real) !== null) files.push(file);
6187
- else diagnostics.push(outsidePackage(packageSpecifier(packageRoot, file)));
6770
+ else diagnostics.push(outsidePackage(specifier));
6188
6771
  }
6189
6772
  return {
6190
6773
  files,
@@ -6259,19 +6842,13 @@ function adaptStoredModelFile(file, source, scalars) {
6259
6842
  };
6260
6843
  }
6261
6844
  /**
6262
- * Normalizes every `<documentModelsDir>/<name>/<name>.json` a schema-first
6263
- * package stores, with the project scalars `scalars/index.ts` exports. A
6264
- * directory or file that cannot be read, or a file that cannot be adapted,
6265
- * is a diagnostic.
6845
+ * Normalizes every `<documentModelsDir>/<name>/<name>.json` discovery
6846
+ * listed, with the project scalars `scalars/index.ts` exports. A file that
6847
+ * cannot be read or adapted is a diagnostic.
6266
6848
  */
6267
6849
  const readStoredDocumentModels = async (input) => {
6268
- const { packageRoot, documentModelsDir } = input;
6269
- if (documentModelsDir === void 0) return {
6270
- artifacts: [],
6271
- diagnostics: [],
6272
- relocations: /* @__PURE__ */ new Map()
6273
- };
6274
- const { files, diagnostics } = storedModelFiles(packageRoot, documentModelsDir);
6850
+ const { packageRoot, loaded } = input;
6851
+ const { files, diagnostics } = storedModelFiles(packageRoot, loaded.sourceSet.stored);
6275
6852
  if (files.length === 0) return {
6276
6853
  artifacts: [],
6277
6854
  diagnostics,
@@ -6296,424 +6873,1121 @@ const readStoredDocumentModels = async (input) => {
6296
6873
  };
6297
6874
  };
6298
6875
  //#endregion
6299
- //#region src/definition/tooling/project/unregistered-definitions.ts
6300
- const DECLARATION = {
6301
- module: /^document-model(?:\/|$)/,
6302
- factory: "defineDocumentModel(?:Family)?"
6876
+ //#region src/definition/tooling/project/project-definitions.ts
6877
+ /** Code-first sources are authored in normalized coordinates, so they need no relocation. */
6878
+ const adaptSelectedModules = ({ loaded }) => {
6879
+ const results = loaded.documentModels.map(({ value, source }) => {
6880
+ const result = adaptCodeFirstDocumentModelSource(value, source);
6881
+ return {
6882
+ artifacts: result.artifacts,
6883
+ diagnostics: result.diagnostics.map((diagnostic) => diagnostic.source === void 0 ? {
6884
+ ...diagnostic,
6885
+ source
6886
+ } : diagnostic)
6887
+ };
6888
+ });
6889
+ return {
6890
+ artifacts: results.flatMap(({ artifacts }) => artifacts),
6891
+ diagnostics: results.flatMap(({ diagnostics }) => diagnostics),
6892
+ relocations: /* @__PURE__ */ new Map()
6893
+ };
6303
6894
  };
6304
- const NAMED_IMPORT = /\bimport\s*\{([^}]*)\}\s*from\s*"#(\d+)"/g;
6305
- const NAMESPACE_IMPORT = /\bimport\s*\*\s*as\s+([\w$]+)\s*from\s*"#(\d+)"/g;
6306
- function startsRegExp(code) {
6307
- const before = code.slice(-64).trimEnd();
6308
- return before === "" || /[(,=:[!&|?{};+\-*%<>~^}]$/.test(before) || /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(before);
6895
+ /** The readers a project loads with unless a caller passes its own: code-first modules, then stored specifications. */
6896
+ const defaultDefinitionProducers = Object.freeze([adaptSelectedModules, readStoredDocumentModels]);
6897
+ /** Tool and Node messages can quote the machine path a package lives at. */
6898
+ function packageRelative(diagnostics, packageRoot) {
6899
+ let real = packageRoot;
6900
+ try {
6901
+ real = realpathSync.native(packageRoot);
6902
+ } catch {}
6903
+ const roots = [.../* @__PURE__ */ new Set([packageRoot, real])].sort((left, right) => right.length - left.length).flatMap((root) => [pathToFileURL(root).href, root]);
6904
+ const rewrite = (text) => roots.reduce((result, root) => result.replaceAll(root, "."), text);
6905
+ return diagnostics.map((diagnostic) => ({
6906
+ ...diagnostic,
6907
+ message: rewrite(diagnostic.message),
6908
+ repair: rewrite(diagnostic.repair),
6909
+ ...diagnostic.expected !== void 0 && { expected: rewrite(diagnostic.expected) },
6910
+ ...diagnostic.received !== void 0 && { received: rewrite(diagnostic.received) },
6911
+ ...diagnostic.related !== void 0 && { related: diagnostic.related.map((location) => ({
6912
+ ...location,
6913
+ message: rewrite(location.message)
6914
+ })) }
6915
+ }));
6309
6916
  }
6310
- function lexCodeAndStrings(text) {
6311
- let code = "";
6312
- const strings = [];
6313
- const literal = (contents) => {
6314
- code += `"#${strings.length}"`;
6315
- strings.push(contents);
6917
+ /**
6918
+ * @experimental Loads the code-first model directories discovery finds and
6919
+ * the package's stored schema-first models, and scans for code-first
6920
+ * declarations no entry module reaches. Artifacts and diagnostics are
6921
+ * sorted and package relative. `producers` replaces the default readers.
6922
+ * `importedFiles` names the absolute paths of every module the loader's
6923
+ * import of a discovered specifier evaluated, so reach follows whatever the
6924
+ * importer resolved. Experimental while code-first projects are introduced.
6925
+ */
6926
+ async function loadProjectDefinitions(request) {
6927
+ const { loader, producers = defaultDefinitionProducers, importedFiles, ...load } = request;
6928
+ const loaded = await loader.normalizeDefinitionSources(load);
6929
+ request.signal?.throwIfAborted();
6930
+ const { packageRoot } = loaded;
6931
+ const modelsDir = loaded.documentModelsDir;
6932
+ const input = {
6933
+ ...load,
6934
+ loader,
6935
+ packageRoot,
6936
+ loaded,
6937
+ ...modelsDir !== void 0 && { documentModelsDir: modelsDir }
6316
6938
  };
6317
- let braces = 0;
6318
- const templates = [];
6319
- let i = 0;
6320
- const skipQuoted = (end) => {
6321
- while (i < text.length && !end(i)) i += text[i] === "\\" ? 2 : 1;
6939
+ const produced = [];
6940
+ for (const producer of producers) produced.push(await producer(input));
6941
+ request.signal?.throwIfAborted();
6942
+ const selectionKnown = !loaded.diagnostics.some(({ phase, severity }) => phase === "configuration" && severity === "error");
6943
+ const artifacts = produced.flatMap((result) => result.artifacts).sort(compareArtifacts);
6944
+ const scan = selectionKnown && modelsDir !== void 0 ? findUnregisteredDefinitions({
6945
+ packageRoot,
6946
+ documentModelsDir: modelsDir,
6947
+ sources: loaded.sourceSet.sources,
6948
+ importedFiles,
6949
+ storedUnits: new Set(loaded.sourceSet.stored.map(({ specifier }) => specifier.replace(/[^/]+$/, ""))),
6950
+ loadedDocumentTypes: /* @__PURE__ */ new Set([...loaded.documentModels.map(({ value }) => value.documentModel.global.id), ...loaded.diagnostics.flatMap(({ definition }) => definition?.kind === "document-model" ? [definition.key] : [])])
6951
+ }) : {
6952
+ unregistered: [],
6953
+ diagnostics: []
6322
6954
  };
6323
- while (i < text.length) {
6324
- const char = text[i];
6325
- if (char === "/" && text[i + 1] === "/") {
6326
- i = text.indexOf("\n", i);
6327
- if (i === -1) i = text.length;
6328
- } else if (char === "/" && text[i + 1] === "*") {
6329
- const end = text.indexOf("*/", i + 2);
6330
- i = end === -1 ? text.length : end + 2;
6331
- code += " ";
6332
- } else if (char === "/" && startsRegExp(code)) {
6333
- i += 1;
6334
- let inClass = false;
6335
- while (i < text.length && text[i] !== "\n") {
6336
- if (text[i] === "\\") i += 1;
6337
- else if (text[i] === "[") inClass = true;
6338
- else if (text[i] === "]") inClass = false;
6339
- else if (text[i] === "/" && !inClass) break;
6340
- i += 1;
6341
- }
6342
- i += 1;
6343
- while (/[a-z]/.test(text[i] ?? "")) i += 1;
6344
- code += " ";
6345
- } else if (char === "\"" || char === "'") {
6346
- const start = i += 1;
6347
- skipQuoted((at) => text[at] === char || text[at] === "\n");
6348
- literal(text.slice(start, i));
6349
- i += 1;
6350
- } else if (char === "`" || char === "}" && templates.at(-1) === braces) {
6351
- const whole = char === "`";
6352
- if (!whole) templates.pop();
6353
- const start = i += 1;
6354
- skipQuoted((at) => text[at] === "`" || text[at] === "$" && text[at + 1] === "{");
6355
- const closed = text[i] === "`";
6356
- literal(whole && closed ? text.slice(start, i) : "");
6357
- if (closed) i += 1;
6358
- else {
6359
- templates.push(braces);
6360
- i += 2;
6361
- }
6362
- } else {
6363
- if (char === "{") braces += 1;
6364
- if (char === "}") braces -= 1;
6365
- code += char;
6366
- i += 1;
6367
- }
6368
- }
6369
6955
  return {
6370
- code,
6371
- strings
6956
+ packageRoot,
6957
+ sourceSet: loaded.sourceSet,
6958
+ ...artifacts.length === 0 && { skipReason: "no-document-models" },
6959
+ artifacts,
6960
+ relocations: new Map(produced.flatMap(({ relocations }) => [...relocations])),
6961
+ diagnostics: sortedUniqueDiagnostics(packageRelative([
6962
+ ...loaded.diagnostics,
6963
+ ...produced.flatMap(({ diagnostics }) => diagnostics),
6964
+ ...scan.diagnostics
6965
+ ], packageRoot)),
6966
+ unregistered: scan.unregistered
6372
6967
  };
6373
6968
  }
6374
- /** `type as e` imports a value named `type`. */
6375
- function valueBindings(clause) {
6376
- return clause.split(",").map((part) => part.trim()).filter((part) => part !== "" && !/^type\s+(?!as\b)/.test(part)).map((part) => {
6377
- const [imported, local = imported] = part.split(/\s+as\s+/);
6378
- return {
6379
- imported,
6380
- local
6969
+ //#endregion
6970
+ //#region src/definition/compiler/graphql-nodes.ts
6971
+ const nameNode = (value) => ({
6972
+ kind: "Name",
6973
+ value
6974
+ });
6975
+ const namedType = (name) => ({
6976
+ kind: "NamedType",
6977
+ name: nameNode(name)
6978
+ });
6979
+ const stringValue = (value, block = false) => ({
6980
+ kind: "StringValue",
6981
+ value,
6982
+ block
6983
+ });
6984
+ function description(value, form = "printed") {
6985
+ return value === null ? {} : { description: stringValue(value, form === "printed" && blockStringable(value)) };
6986
+ }
6987
+ function typeNode(type) {
6988
+ const base = type.kind === "list" ? {
6989
+ kind: "ListType",
6990
+ type: typeNode(type.item)
6991
+ } : namedType(type.name);
6992
+ return type.required ? {
6993
+ kind: "NonNullType",
6994
+ type: base
6995
+ } : base;
6996
+ }
6997
+ function numberValue(value) {
6998
+ if (!Number.isFinite(value)) throw new TypeError(`A GraphQL value must be finite, received ${String(value)}.`);
6999
+ const printed = JSON.stringify(value);
7000
+ return /[.eE]/.test(printed) ? {
7001
+ kind: "FloatValue",
7002
+ value: printed
7003
+ } : {
7004
+ kind: "IntValue",
7005
+ value: printed
7006
+ };
7007
+ }
7008
+ function literalValue(value) {
7009
+ if (value === null) return { kind: "NullValue" };
7010
+ if (typeof value === "boolean") return {
7011
+ kind: "BooleanValue",
7012
+ value
7013
+ };
7014
+ if (typeof value === "number") return numberValue(value);
7015
+ if (typeof value === "string") return stringValue(value);
7016
+ if (Array.isArray(value)) return {
7017
+ kind: "ListValue",
7018
+ values: value.map(literalValue)
7019
+ };
7020
+ return objectValue(value, (member) => literalValue(member));
7021
+ }
7022
+ function objectValue(value, member) {
7023
+ return {
7024
+ kind: "ObjectValue",
7025
+ fields: Object.entries(value).map(([key, entry]) => ({
7026
+ kind: "ObjectField",
7027
+ name: nameNode(key),
7028
+ value: member(entry, key)
7029
+ }))
7030
+ };
7031
+ }
7032
+ function enumMember(definition, value) {
7033
+ return definition.values.some((candidate) => candidate.name === value);
7034
+ }
7035
+ function typedValue(value, type, inventory) {
7036
+ if (value === null) return { kind: "NullValue" };
7037
+ if (type.kind === "list") return Array.isArray(value) ? {
7038
+ kind: "ListValue",
7039
+ values: value.map((item) => typedValue(item, type.item, inventory))
7040
+ } : typedValue(value, type.item, inventory);
7041
+ if (type.kind === "scalar") return literalValue(value);
7042
+ const definition = inventory.get(type.name);
7043
+ if (definition?.kind === "enum") return typeof value === "string" && enumMember(definition, value) ? {
7044
+ kind: "EnumValue",
7045
+ value
7046
+ } : literalValue(value);
7047
+ if (definition?.kind !== "input" || typeof value !== "object" || Array.isArray(value)) return literalValue(value);
7048
+ const fields = new Map(definition.fields.map((field) => [field.name, field]));
7049
+ return objectValue(value, (member, key) => {
7050
+ const field = fields.get(key);
7051
+ return field === void 0 ? literalValue(member) : typedValue(member, field.type, inventory);
7052
+ });
7053
+ }
7054
+ function directiveNodes(deprecated, directives) {
7055
+ const used = (directives ?? []).map((directive) => ({
7056
+ kind: "Directive",
7057
+ name: nameNode(directive.name),
7058
+ arguments: directive.arguments.map((argument) => ({
7059
+ kind: "Argument",
7060
+ name: nameNode(argument.name),
7061
+ value: literalValue(argument.value)
7062
+ }))
7063
+ }));
7064
+ if (deprecated === null) return used;
7065
+ return [{
7066
+ kind: "Directive",
7067
+ name: nameNode("deprecated"),
7068
+ arguments: [{
7069
+ kind: "Argument",
7070
+ name: nameNode("reason"),
7071
+ value: stringValue(deprecated)
7072
+ }]
7073
+ }, ...used];
7074
+ }
7075
+ function inputValueNode(field, inventory, form) {
7076
+ return {
7077
+ kind: "InputValueDefinition",
7078
+ ...description(field.description, form),
7079
+ name: nameNode(field.name),
7080
+ type: typeNode(field.type),
7081
+ ...Object.hasOwn(field, "defaultValue") && { defaultValue: typedValue(field.defaultValue, field.type, inventory) },
7082
+ directives: directiveNodes(field.deprecated, field.directives)
7083
+ };
7084
+ }
7085
+ const EMPTY_INPUT_FIELD = {
7086
+ kind: "InputValueDefinition",
7087
+ name: nameNode(EMPTY_INPUT_FIELD_NAME),
7088
+ type: namedType("Boolean"),
7089
+ directives: []
7090
+ };
7091
+ function fieldNodes(fields, inventory) {
7092
+ return fields.map((field) => ({
7093
+ kind: "FieldDefinition",
7094
+ ...description(field.description),
7095
+ name: nameNode(field.name),
7096
+ arguments: (field.args ?? []).map((argument) => inputValueNode(argument, inventory, "argument-inline")),
7097
+ type: typeNode(field.type),
7098
+ directives: directiveNodes(field.deprecated, field.directives)
7099
+ }));
7100
+ }
7101
+ function definitionNode(definition, inventory) {
7102
+ const named = {
7103
+ ...description(definition.description),
7104
+ name: nameNode(definition.name),
7105
+ directives: []
7106
+ };
7107
+ switch (definition.kind) {
7108
+ case "enum": return {
7109
+ kind: "EnumTypeDefinition",
7110
+ ...named,
7111
+ values: definition.values.map((value) => ({
7112
+ kind: "EnumValueDefinition",
7113
+ ...description(value.description),
7114
+ name: nameNode(value.name),
7115
+ directives: directiveNodes(value.deprecated, value.directives)
7116
+ }))
6381
7117
  };
7118
+ case "object":
7119
+ case "interface": return {
7120
+ kind: definition.kind === "object" ? "ObjectTypeDefinition" : "InterfaceTypeDefinition",
7121
+ ...named,
7122
+ interfaces: (definition.implements ?? []).map(namedType),
7123
+ fields: fieldNodes(definition.fields, inventory)
7124
+ };
7125
+ case "input": return {
7126
+ kind: "InputObjectTypeDefinition",
7127
+ ...named,
7128
+ fields: definition.fields.length === 0 ? [EMPTY_INPUT_FIELD] : definition.fields.map((field) => inputValueNode(field, inventory, "printed"))
7129
+ };
7130
+ case "union": return {
7131
+ kind: "UnionTypeDefinition",
7132
+ ...named,
7133
+ types: definition.members.map(namedType)
7134
+ };
7135
+ }
7136
+ }
7137
+ //#endregion
7138
+ //#region src/definition/compiler/graphql-projection.ts
7139
+ function isPackageScalar(scalar) {
7140
+ return scalar.implementation.startsWith("package#");
7141
+ }
7142
+ /**
7143
+ * Projects a specification into the GraphQL documents its stored SDL
7144
+ * segments parse to: `print(segment.document)` equals
7145
+ * `print(parse(storedSegment))` for the state schemas and each operation's
7146
+ * `schema` that `materialize` stores.
7147
+ */
7148
+ function projectDocumentModelGraphQL(definition, specification) {
7149
+ const { types } = specification;
7150
+ const inventory = new Map(types.map((type) => [type.name, type]));
7151
+ const document = (definitions) => ({
7152
+ kind: "Document",
7153
+ definitions: definitions.map((type) => definitionNode(type, inventory))
6382
7154
  });
7155
+ const globalRoot = specification.state.global.root.name;
7156
+ const localRoot = specification.state.local.root?.name ?? null;
7157
+ const operationKey = (moduleKey, key) => `${moduleKey}/${key}`;
7158
+ const segments = assignStoredSegments({
7159
+ types,
7160
+ globalRoot,
7161
+ localRoot,
7162
+ operations: specification.modules.flatMap((module) => module.operations.map((operation) => ({
7163
+ key: operationKey(module.key, operation.key),
7164
+ input: operation.input
7165
+ })))
7166
+ });
7167
+ const packageScalars = specification.scalars.filter(isPackageScalar);
7168
+ const global = document(segments.global);
7169
+ return {
7170
+ graphQLName: definition.model.graphQLName,
7171
+ global: {
7172
+ root: globalRoot,
7173
+ document: {
7174
+ kind: "Document",
7175
+ definitions: [...packageScalars.map(({ name }) => name).sort(compareCodeUnits).map((name) => ({
7176
+ kind: "ScalarTypeDefinition",
7177
+ name: nameNode(name),
7178
+ directives: []
7179
+ })), ...global.definitions]
7180
+ }
7181
+ },
7182
+ local: localRoot === null ? null : {
7183
+ root: localRoot,
7184
+ document: document(segments.local)
7185
+ },
7186
+ modules: specification.modules.map((module) => ({
7187
+ key: module.key,
7188
+ name: module.name,
7189
+ operations: module.operations.map((operation) => ({
7190
+ key: operation.key,
7191
+ name: operation.name ?? operation.actionType,
7192
+ actionType: operation.actionType,
7193
+ creatorKey: operation.creatorKey,
7194
+ scope: operation.scope,
7195
+ input: operation.input === null ? null : document(segments.operations.get(operationKey(module.key, operation.key)) ?? [operation.input])
7196
+ }))
7197
+ })),
7198
+ packageScalars
7199
+ };
6383
7200
  }
6384
- function isSourceFile(name) {
6385
- return DEFINITION_SOURCE_EXTENSION.test(name) && !/\.d\.m?ts$/.test(name);
7201
+ //#endregion
7202
+ //#region src/definition/subgraph/projection.ts
7203
+ const ROOT_TYPES$1 = {
7204
+ query: "Query",
7205
+ mutation: "Mutation",
7206
+ subscription: "Subscription"
7207
+ };
7208
+ function subgraphRootTypes(definition) {
7209
+ return [
7210
+ "query",
7211
+ "mutation",
7212
+ "subscription"
7213
+ ].flatMap((kind) => {
7214
+ const fields = definition.entries.flatMap((entry) => entry.kind === kind ? [{
7215
+ key: entry.key,
7216
+ name: entry.fieldName,
7217
+ description: entry.description,
7218
+ deprecated: entry.deprecated,
7219
+ args: entry.args,
7220
+ type: entry.returns
7221
+ }] : []);
7222
+ return fields.length === 0 ? [] : [{
7223
+ kind: "object",
7224
+ name: ROOT_TYPES$1[kind],
7225
+ description: null,
7226
+ fields
7227
+ }];
7228
+ });
6386
7229
  }
6387
- function isTestFile(name) {
6388
- return /\.(?:test|spec)\.(?:[jt]sx?|m[jt]s)$/.test(name);
7230
+ /**
7231
+ * @experimental The GraphQL document a subgraph definition serves, without
7232
+ * locations, in the definition's print order. A typed definition declares
7233
+ * the catalog and project scalars it uses as `scalar` definitions.
7234
+ */
7235
+ function projectSubgraphGraphQL(definition) {
7236
+ if (definition.schemaKind === "graphql-ast-compat") return definition.document;
7237
+ const roots = subgraphRootTypes(definition);
7238
+ const inventory = new Map([...definition.types, ...roots].map((type) => [type.name, type]));
7239
+ const scalars = new Set(definition.scalars.map(({ name }) => name));
7240
+ return {
7241
+ kind: "Document",
7242
+ definitions: definition.definitionOrder.flatMap((name) => {
7243
+ if (scalars.has(name)) return [{
7244
+ kind: "ScalarTypeDefinition",
7245
+ name: nameNode(name),
7246
+ directives: []
7247
+ }];
7248
+ const type = inventory.get(name);
7249
+ if (type === void 0) throw new TypeError(`definitionOrder names ${name}, which the subgraph definition does not declare.`);
7250
+ return [definitionNode(type, inventory)];
7251
+ })
7252
+ };
6389
7253
  }
7254
+ //#endregion
7255
+ //#region src/definition/tooling/subgraph/claims.ts
7256
+ const ROOT_TYPES = /* @__PURE__ */ new Set([
7257
+ "Query",
7258
+ "Mutation",
7259
+ "Subscription"
7260
+ ]);
7261
+ const TYPE_NODE = /^(?:Object|Interface|Union|Enum|InputObject)Type(?:Definition|Extension)$/;
7262
+ /** Member lists whose order does not change what a type defines. */
7263
+ const NAMED_MEMBERS = /* @__PURE__ */ new Set([
7264
+ "fields",
7265
+ "arguments",
7266
+ "interfaces",
7267
+ "values",
7268
+ "types"
7269
+ ]);
7270
+ const nameOf = (node) => {
7271
+ const name = node?.name?.value;
7272
+ return typeof name === "string" ? name : void 0;
7273
+ };
6390
7274
  /**
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`.
7275
+ * Drops locations, descriptions, the block flag of strings and empty
7276
+ * members, and sorts named members, so equal definitions compare equal
7277
+ * whichever AST printed them.
6394
7278
  */
6395
- function packageEntries(path, packageRootIdentity, unreadable) {
6396
- let names;
7279
+ function normalized(value, key) {
7280
+ if (Array.isArray(value)) {
7281
+ const items = value.map((item) => normalized(item));
7282
+ return key !== void 0 && NAMED_MEMBERS.has(key) ? items.sort((left, right) => compareCodeUnits(nameOf(left) ?? "", nameOf(right) ?? "")) : items;
7283
+ }
7284
+ if (value === null || typeof value !== "object") return value;
7285
+ return Object.fromEntries(Object.entries(value).filter(([member, inner]) => member !== "loc" && member !== "description" && member !== "block" && inner !== void 0 && !(Array.isArray(inner) && inner.length === 0)).map(([member, inner]) => [member, normalized(inner, member)]));
7286
+ }
7287
+ const normalizedText = (node) => canonicalJson(normalized(node));
7288
+ function merged(nodes) {
7289
+ if (nodes.length === 1) return nodes[0];
7290
+ const definitions = nodes.filter(({ kind }) => kind.endsWith("Definition"));
7291
+ if (definitions.length !== 1) return void 0;
7292
+ const [definition] = definitions;
7293
+ const extensionKind = definition.kind.replace(/Definition$/, "Extension");
7294
+ const result = { ...definition };
7295
+ for (const node of nodes) {
7296
+ if (node === definition) continue;
7297
+ if (node.kind !== extensionKind) return void 0;
7298
+ for (const member of [
7299
+ "fields",
7300
+ "interfaces",
7301
+ "values",
7302
+ "types",
7303
+ "directives"
7304
+ ]) {
7305
+ const extra = node[member];
7306
+ if (Array.isArray(extra)) result[member] = [...result[member] ?? [], ...extra];
7307
+ }
7308
+ }
7309
+ return result;
7310
+ }
7311
+ function subgraphClaims(document) {
7312
+ const types = /* @__PURE__ */ new Map();
7313
+ const claims = /* @__PURE__ */ new Map();
7314
+ for (const definition of document.definitions) {
7315
+ const name = nameOf(definition);
7316
+ if (name === void 0 || !TYPE_NODE.test(definition.kind)) continue;
7317
+ if (ROOT_TYPES.has(name)) {
7318
+ const fields = definition.fields;
7319
+ if (!Array.isArray(fields)) continue;
7320
+ for (const field of fields) {
7321
+ const claim = `${name}.${nameOf(field)}`;
7322
+ const text = normalizedText(field);
7323
+ const previous = claims.get(claim);
7324
+ claims.set(claim, previous === void 0 ? text : `${previous}\n${text}`);
7325
+ }
7326
+ continue;
7327
+ }
7328
+ types.set(name, [...types.get(name) ?? [], definition]);
7329
+ }
7330
+ for (const [name, nodes] of types) {
7331
+ const node = merged(nodes);
7332
+ claims.set(name, node === void 0 ? nodes.map(normalizedText).sort(compareCodeUnits).join("\n") : normalizedText(node));
7333
+ }
7334
+ return claims;
7335
+ }
7336
+ const isRootFieldClaim = (claim) => claim.includes(".");
7337
+ /** The claims `later` loses to `earlier`: every shared root field, and every type defined differently. */
7338
+ function conflictingClaims(earlier, later) {
7339
+ return [...later].filter(([claim, text]) => {
7340
+ const owned = earlier.get(claim);
7341
+ return owned !== void 0 && (isRootFieldClaim(claim) || owned !== text);
7342
+ }).map(([claim]) => claim);
7343
+ }
7344
+ //#endregion
7345
+ //#region src/definition/tooling/subgraph/diagnostic-codes.ts
7346
+ const subgraphToolingDiagnostics = defineDiagnosticCatalog({
7347
+ "PH-SG-DESCRIBE-FAILED": {
7348
+ severity: "error",
7349
+ phase: "import",
7350
+ meaning: "A code-first subgraph class threw from describe() or returned something that is not a description"
7351
+ },
7352
+ "PH-SG-PROTOCOL-UNSUPPORTED": {
7353
+ severity: "error",
7354
+ phase: "package",
7355
+ meaning: "A subgraph class carries a protocol version this release does not read, or a malformed protocol"
7356
+ },
7357
+ "PH-SG-NAME-MISSING": {
7358
+ severity: "error",
7359
+ phase: "package",
7360
+ meaning: "A code-first subgraph class declares no subgraphName and no other export extends it"
7361
+ },
7362
+ "PH-SG-DUPLICATE-NAME": {
7363
+ severity: "error",
7364
+ phase: "package",
7365
+ meaning: "Two code-first subgraphs of one package share a name"
7366
+ },
7367
+ "PH-SG-TYPE-CONFLICT": {
7368
+ severity: "error",
7369
+ phase: "composition",
7370
+ meaning: "Two code-first subgraphs serve one root field, or one type name with different definitions"
7371
+ },
7372
+ "PH-SG-DOCUMENT-MODEL-TYPE-CONFLICT": {
7373
+ severity: "error",
7374
+ phase: "composition",
7375
+ meaning: "A code-first subgraph declares a type that a document model of the package generates"
7376
+ },
7377
+ "PH-SG-NAME-RESERVED": {
7378
+ severity: "error",
7379
+ phase: "package",
7380
+ meaning: "A code-first subgraph has the name of a built-in subgraph or of a document model's subgraph, so a host refuses it"
7381
+ },
7382
+ "PH-SG-HOST-TYPE-CONFLICT": {
7383
+ severity: "error",
7384
+ phase: "composition",
7385
+ meaning: "A code-first subgraph declares a type or root field that a host's built-in subgraphs or base document models own, so a host refuses it"
7386
+ },
7387
+ "PH-SG-SCALAR-UNREGISTERED": {
7388
+ severity: "error",
7389
+ phase: "package",
7390
+ meaning: "A code-first subgraph uses a package scalar that scalars/index.ts does not export under its name"
7391
+ },
7392
+ "PH-SG-SCHEMA-FIRST-CONFLICT": {
7393
+ severity: "warning",
7394
+ phase: "composition",
7395
+ meaning: "A code-first subgraph and a schema-first subgraph claim one name, root field or differently defined type"
7396
+ },
7397
+ "PH-SG-SCHEMA-FIRST-UNCHECKED": {
7398
+ severity: "warning",
7399
+ phase: "composition",
7400
+ meaning: "The SDL of a schema-first subgraph could not be read from its source text, so its conflicts were not checked"
7401
+ }
7402
+ }, toolingDiagnostics);
7403
+ //#endregion
7404
+ //#region src/definition/tooling/subgraph/schema-first/sdl-conflicts.ts
7405
+ const TEMPLATE = /\b(?:gql|graphql)\s*`((?:\\[\s\S]|[^`\\])*)`/g;
7406
+ const RELATIVE_IMPORT = /\bfrom\s*["']\.\.?\//;
7407
+ function sdlText(source) {
7408
+ if (source.text === null) return { reason: "the subgraph has no schema.graphql, schema.ts or index.ts" };
7409
+ if (source.language === "graphql") return { sdl: source.text };
7410
+ const templates = [...source.text.matchAll(TEMPLATE)].map((match) => match[1]);
7411
+ if (templates.some((template) => template.includes("${"))) return { reason: "its gql template interpolates values" };
7412
+ if (templates.length === 0) return { reason: RELATIVE_IMPORT.test(source.text) ? "its SDL is imported from another module" : "it holds no gql template" };
7413
+ return { sdl: templates.join("\n") };
7414
+ }
7415
+ function readSchemaFirstSdl(source) {
7416
+ const text = sdlText(source);
7417
+ if ("reason" in text) return {
7418
+ kind: "unchecked",
7419
+ reason: text.reason
7420
+ };
7421
+ let graphql;
6397
7422
  try {
6398
- names = readdirSync(path);
7423
+ graphql = loadGraphQL();
6399
7424
  } catch (error) {
6400
- unreadable.push({
6401
- path,
6402
- error
6403
- });
6404
- return [];
7425
+ return {
7426
+ kind: "unchecked",
7427
+ reason: error instanceof Error ? error.message : String(error)
7428
+ };
7429
+ }
7430
+ try {
7431
+ return {
7432
+ kind: "read",
7433
+ claims: subgraphClaims(graphql.parse(text.sdl, { noLocation: true }))
7434
+ };
7435
+ } catch (error) {
7436
+ return {
7437
+ kind: "unchecked",
7438
+ reason: `its SDL does not parse: ${error instanceof Error ? error.message : String(error)}`
7439
+ };
6405
7440
  }
6406
- return names.filter((name) => name !== "node_modules" && !name.startsWith(".")).sort(compareCodeUnits).flatMap((name) => {
6407
- const child = join(path, name);
6408
- try {
6409
- const real = realpathSync.native(child);
6410
- if (pathWithin(packageRootIdentity, real) === null) return [];
6411
- return [{
6412
- name,
6413
- path: child,
6414
- real,
6415
- isDirectory: statSync(real).isDirectory()
6416
- }];
6417
- } catch {
6418
- return [];
6419
- }
6420
- });
6421
7441
  }
6422
- /** `visited` holds real directories, so a symlink cycle ends. */
6423
- function sourceFilesUnder(directory, packageRootIdentity, visited, unreadable) {
6424
- if (visited.has(directory.real)) return [];
6425
- visited.add(directory.real);
6426
- return packageEntries(directory.path, packageRootIdentity, unreadable).flatMap((entry) => {
6427
- if (entry.isDirectory) return entry.name === "__tests__" ? [] : sourceFilesUnder(entry, packageRootIdentity, visited, unreadable);
6428
- return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];
6429
- });
7442
+ function describeClaim(claim) {
7443
+ return isRootFieldClaim(claim) ? `root field ${claim}` : `type ${claim}`;
6430
7444
  }
6431
7445
  /**
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.
7446
+ * Advisory warnings for a project with code-first and schema-first
7447
+ * subgraphs: a shared name, a shared root field, or a type defined
7448
+ * differently. The host keeps deciding at runtime; nothing here is an
7449
+ * error. SDL that cannot be read from text is reported as not checked.
6435
7450
  */
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
- }
7451
+ function schemaFirstSdlConflicts(input) {
7452
+ if (input.codeFirst.length === 0) return [];
7453
+ const codeFirst = input.codeFirst.map((subgraph) => ({
7454
+ subgraph,
7455
+ claims: subgraphClaims(projectSubgraphGraphQL(subgraph.definition))
7456
+ }));
7457
+ const diagnostics = [];
7458
+ for (const schemaFirstSubgraph of input.schemaFirst) {
7459
+ const named = codeFirst.find(({ subgraph }) => schemaFirstSubgraph.name !== null && subgraph.name === schemaFirstSubgraph.name);
7460
+ if (named !== void 0) diagnostics.push(subgraphToolingDiagnostics.create({
7461
+ code: "PH-SG-SCHEMA-FIRST-CONFLICT",
7462
+ source: schemaFirstSubgraph.source,
7463
+ definition: {
7464
+ kind: "subgraph",
7465
+ key: named.subgraph.name
7466
+ },
7467
+ path: [],
7468
+ message: `The schema-first subgraph in ${schemaFirstSubgraph.unit} and a code-first subgraph are both named ${named.subgraph.name}; a host serves one of them.`,
7469
+ expected: "one subgraph per name",
7470
+ received: named.subgraph.name,
7471
+ repair: "Rename one of the subgraphs.",
7472
+ related: [{
7473
+ source: named.subgraph.source,
7474
+ path: [],
7475
+ message: "The code-first subgraph with this name."
7476
+ }]
7477
+ }));
7478
+ const read = readSchemaFirstSdl(schemaFirstSubgraph);
7479
+ if (read.kind === "unchecked") {
7480
+ diagnostics.push(subgraphToolingDiagnostics.create({
7481
+ code: "PH-SG-SCHEMA-FIRST-UNCHECKED",
7482
+ source: schemaFirstSubgraph.source,
7483
+ path: [],
7484
+ message: `The schema-first subgraph in ${schemaFirstSubgraph.unit} was not checked against the code-first subgraphs: ${read.reason}.`,
7485
+ expected: "SDL in a schema.graphql file or a gql template without interpolation",
7486
+ received: read.reason,
7487
+ repair: "Nothing is required. To have its conflicts checked, keep its SDL in one gql template or a schema.graphql file."
7488
+ }));
7489
+ continue;
6454
7490
  }
7491
+ for (const { subgraph, claims } of codeFirst) for (const claim of conflictingClaims(read.claims, claims)) diagnostics.push(subgraphToolingDiagnostics.create({
7492
+ code: "PH-SG-SCHEMA-FIRST-CONFLICT",
7493
+ source: subgraph.source,
7494
+ definition: {
7495
+ kind: "subgraph",
7496
+ key: subgraph.name
7497
+ },
7498
+ path: [],
7499
+ message: `Code-first subgraph ${subgraph.name} and the schema-first subgraph in ${schemaFirstSubgraph.unit} both claim ${describeClaim(claim)}; the host serves the claim from one of them only.`,
7500
+ expected: isRootFieldClaim(claim) ? "each root field served by one subgraph" : "one definition per type name",
7501
+ received: claim,
7502
+ repair: isRootFieldClaim(claim) ? "Rename the root field in one of the subgraphs." : "Rename the type in one subgraph, or define it identically in both.",
7503
+ related: [{
7504
+ source: schemaFirstSubgraph.source,
7505
+ path: [],
7506
+ message: `The schema-first subgraph claims ${claim} here.`
7507
+ }]
7508
+ }));
6455
7509
  }
6456
- return id === void 0 || id === "" || id.includes("\\") ? void 0 : id;
7510
+ return diagnostics;
6457
7511
  }
6458
- function declarations(code, strings) {
6459
- const { module, factory } = DECLARATION;
6460
- const isFactory = new RegExp(`^${factory}$`);
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);
7512
+ //#endregion
7513
+ //#region src/definition/tooling/subgraph/checks.ts
7514
+ function claimPath(subgraph, claim) {
7515
+ const { definition } = subgraph;
7516
+ if (isRootFieldClaim(claim)) {
7517
+ const index = definition.entries.findIndex((entry) => (entry.kind === "query" || entry.kind === "mutation" || entry.kind === "subscription") && `${ROOT_TYPES$1[entry.kind]}.${entry.fieldName}` === claim);
7518
+ return index === -1 ? [] : ["entries", index];
7519
+ }
7520
+ const index = definition.types.findIndex(({ name }) => name === claim);
7521
+ return index === -1 ? [] : ["types", index];
7522
+ }
7523
+ const descriptionsCheck = {
7524
+ name: "subgraph-descriptions",
7525
+ run: ({ subgraphs }) => subgraphs.diagnostics
7526
+ };
7527
+ const namesCheck = {
7528
+ name: "subgraph-names",
7529
+ run: ({ subgraphs }) => {
7530
+ const first = /* @__PURE__ */ new Map();
7531
+ const diagnostics = [];
7532
+ for (const subgraph of subgraphs.codeFirst) {
7533
+ const known = first.get(subgraph.name);
7534
+ if (known === void 0) {
7535
+ first.set(subgraph.name, subgraph);
7536
+ continue;
7537
+ }
7538
+ diagnostics.push(subgraphToolingDiagnostics.create({
7539
+ code: "PH-SG-DUPLICATE-NAME",
7540
+ source: subgraph.source,
7541
+ definition: {
7542
+ kind: "subgraph",
7543
+ key: subgraph.name
7544
+ },
7545
+ path: ["name"],
7546
+ message: `Two code-first subgraphs are named ${subgraph.name}; a host serves only one of them.`,
7547
+ expected: "one subgraph per name",
7548
+ received: subgraph.name,
7549
+ repair: "Give each subgraph class its own subgraphName.",
7550
+ related: [{
7551
+ source: known.source,
7552
+ path: ["name"],
7553
+ message: `The other subgraph named ${subgraph.name}.`
7554
+ }]
7555
+ }));
6477
7556
  }
7557
+ return diagnostics;
7558
+ }
7559
+ };
7560
+ const typeConflictsCheck = {
7561
+ name: "subgraph-type-conflicts",
7562
+ run: ({ subgraphs }) => {
7563
+ const claimed = subgraphs.codeFirst.map((subgraph) => ({
7564
+ subgraph,
7565
+ claims: subgraphClaims(projectSubgraphGraphQL(subgraph.definition))
7566
+ }));
7567
+ const diagnostics = [];
7568
+ claimed.forEach(({ subgraph, claims }, index) => {
7569
+ for (const earlier of claimed.slice(0, index)) for (const claim of conflictingClaims(earlier.claims, claims)) diagnostics.push(subgraphToolingDiagnostics.create({
7570
+ code: "PH-SG-TYPE-CONFLICT",
7571
+ source: subgraph.source,
7572
+ definition: {
7573
+ kind: "subgraph",
7574
+ key: subgraph.name
7575
+ },
7576
+ path: claimPath(subgraph, claim),
7577
+ message: isRootFieldClaim(claim) ? `Code-first subgraphs ${earlier.subgraph.name} and ${subgraph.name} both serve root field ${claim}.` : `Code-first subgraphs ${earlier.subgraph.name} and ${subgraph.name} define type ${claim} differently.`,
7578
+ expected: isRootFieldClaim(claim) ? "each root field served by one subgraph" : "one definition per type name",
7579
+ received: claim,
7580
+ repair: isRootFieldClaim(claim) ? "Rename the root field in one of the subgraphs." : "Share one ph descriptor for the type between both subgraphs, or rename one of them.",
7581
+ related: [{
7582
+ source: earlier.subgraph.source,
7583
+ path: claimPath(earlier.subgraph, claim),
7584
+ message: `${earlier.subgraph.name} claims ${claim} here.`
7585
+ }]
7586
+ }));
7587
+ });
7588
+ return diagnostics;
6478
7589
  }
6479
- return {
6480
- declares,
6481
- ids
6482
- };
6483
- }
6484
- function escapeRegExp(name) {
6485
- return name.replaceAll("$", "\\$");
6486
- }
6487
- function packagePath(root, path) {
6488
- return `./${relative(root, path).split(sep).join("/")}`;
6489
- }
6490
- function realPathOrSelf(path) {
7590
+ };
7591
+ /**
7592
+ * The names a host generates for a model's GraphQL types: the document type
7593
+ * under the model's PascalCase name, and each state output type under
7594
+ * `<Name>_<Type>`. Mirrors reactor-api's generated schema.
7595
+ */
7596
+ function generatedTypeNames(artifact) {
7597
+ const served = servedSpecification(artifact);
7598
+ if (served === void 0) return [];
7599
+ const { model } = artifact.definition;
7600
+ const prefix = deriveDocumentModelNames({
7601
+ id: model.documentType,
7602
+ name: model.name.replaceAll("/", " ")
7603
+ }).graphQLName;
7604
+ let projection;
6491
7605
  try {
6492
- return realpathSync.native(path);
7606
+ projection = projectDocumentModelGraphQL(artifact.definition, served.specification);
6493
7607
  } catch {
6494
- return path;
7608
+ return [prefix];
7609
+ }
7610
+ return [prefix, ...[...projection.global.document.definitions, ...projection.local?.document.definitions ?? []].flatMap((node) => node.kind === "ObjectTypeDefinition" || node.kind === "InterfaceTypeDefinition" || node.kind === "UnionTypeDefinition" || node.kind === "EnumTypeDefinition" ? [`${prefix}_${node.name.value}`] : [])];
7611
+ }
7612
+ const documentModelTypesCheck = {
7613
+ name: "subgraph-document-model-types",
7614
+ run: ({ subgraphs, artifacts }) => {
7615
+ if (subgraphs.codeFirst.length === 0) return [];
7616
+ const owners = /* @__PURE__ */ new Map();
7617
+ for (const artifact of artifacts) for (const name of generatedTypeNames(artifact)) if (!owners.has(name)) owners.set(name, artifact);
7618
+ return subgraphs.codeFirst.flatMap((subgraph) => subgraph.definition.types.flatMap((type, index) => {
7619
+ const owner = owners.get(type.name);
7620
+ if (owner === void 0) return [];
7621
+ return [subgraphToolingDiagnostics.create({
7622
+ code: "PH-SG-DOCUMENT-MODEL-TYPE-CONFLICT",
7623
+ source: subgraph.source,
7624
+ definition: {
7625
+ kind: "subgraph",
7626
+ key: subgraph.name
7627
+ },
7628
+ path: ["types", index],
7629
+ message: `Code-first subgraph ${subgraph.name} declares type ${type.name}, which document model ${owner.documentType} generates; a host refuses the subgraph.`,
7630
+ expected: "a type name no document model of the package generates",
7631
+ received: type.name,
7632
+ repair: `Rename the subgraph's ${type.name}.`,
7633
+ related: [{
7634
+ source: owner.source,
7635
+ path: [],
7636
+ message: `${owner.documentType} generates ${type.name}.`
7637
+ }]
7638
+ })];
7639
+ }));
6495
7640
  }
6496
- }
6497
- /** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */
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
7641
+ };
7642
+ const packageScalarsCheck = {
7643
+ name: "subgraph-package-scalars",
7644
+ run: ({ subgraphs }) => {
7645
+ const exported = subgraphs.packageScalars;
7646
+ if (exported === void 0) return [];
7647
+ return subgraphs.codeFirst.flatMap((subgraph) => subgraph.definition.scalars.flatMap((scalar, index) => scalar.implementation.startsWith("package#") && !exported.includes(scalar.name) ? [subgraphToolingDiagnostics.create({
7648
+ code: "PH-SG-SCALAR-UNREGISTERED",
7649
+ source: subgraph.source,
7650
+ definition: {
7651
+ kind: "subgraph",
7652
+ key: subgraph.name
7653
+ },
7654
+ path: ["scalars", index],
7655
+ message: `Code-first subgraph ${subgraph.name} uses package scalar ${scalar.name}, which scalars/index.ts does not export; a host cannot register it.`,
7656
+ expected: exported.length === 0 ? "a scalars/index.ts export of the scalar" : exported.join(", "),
7657
+ received: scalar.name,
7658
+ repair: `Export ${scalar.name} from scalars/index.ts under its own name: export const ${scalar.name} = defineScalar({ name: "${scalar.name}", ... }).`
7659
+ })] : []));
7660
+ }
7661
+ };
7662
+ const NAME_HOLDER = {
7663
+ core: "a built-in subgraph",
7664
+ "document model": "a document model's subgraph"
7665
+ };
7666
+ /**
7667
+ * @experimental The checks `ph model check` adds when a project has a
7668
+ * code-first subgraph. A caller registers them with
7669
+ * `[...documentModelChecks, ...subgraphChecks]` and a
7670
+ * {@link SubgraphChecksInput}.
7671
+ */
7672
+ const subgraphChecks = Object.freeze([
7673
+ descriptionsCheck,
7674
+ namesCheck,
7675
+ typeConflictsCheck,
7676
+ documentModelTypesCheck,
7677
+ packageScalarsCheck,
7678
+ {
7679
+ name: "subgraph-host-admission",
7680
+ run: ({ subgraphs, artifacts }) => {
7681
+ if (subgraphs.hostConflicts.length === 0) return [];
7682
+ const generated = new Set(artifacts.flatMap(generatedTypeNames));
7683
+ return subgraphs.codeFirst.flatMap((subgraph) => {
7684
+ const conflict = subgraphs.hostConflicts.find((candidate) => candidate.subgraph === subgraph.name);
7685
+ if (conflict === void 0) return [];
7686
+ const definition = {
7687
+ kind: "subgraph",
7688
+ key: subgraph.name
7689
+ };
7690
+ return [...conflict.nameHeldBy === void 0 ? [] : [subgraphToolingDiagnostics.create({
7691
+ code: "PH-SG-NAME-RESERVED",
7692
+ source: subgraph.source,
7693
+ definition,
7694
+ path: [],
7695
+ message: `Code-first subgraph ${subgraph.name} has the name of ${NAME_HOLDER[conflict.nameHeldBy]}; a host refuses the subgraph.`,
7696
+ expected: "a subgraph name no built-in or document-model subgraph uses",
7697
+ received: subgraph.name,
7698
+ repair: `Rename the subgraph's static subgraphName, for example to "${subgraph.name}-api".`
7699
+ })], ...conflict.claims.filter(({ claim }) => !generated.has(claim)).map(({ claim, owner }) => subgraphToolingDiagnostics.create({
7700
+ code: "PH-SG-HOST-TYPE-CONFLICT",
7701
+ source: subgraph.source,
7702
+ definition,
7703
+ path: claimPath(subgraph, claim),
7704
+ message: `Code-first subgraph ${subgraph.name} declares ${claim}, which the host's ${owner} subgraph owns; a host leaves the subgraph out.`,
7705
+ expected: `a name the host's ${owner} subgraph does not own`,
7706
+ received: claim,
7707
+ repair: `Rename ${claim} in the subgraph's schema.`
7708
+ }))];
6508
7709
  });
6509
- continue;
6510
7710
  }
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
- });
7711
+ },
7712
+ {
7713
+ name: "subgraph-schema-first-sdl",
7714
+ run: ({ subgraphs }) => schemaFirstSdlConflicts(subgraphs)
6517
7715
  }
6518
- const index = join(directory.path, "index.ts");
6519
- const suggested = declaring.find(({ entry }) => entry.path === index) ?? declaring.at(0);
6520
- if (suggested === void 0) return void 0;
6521
- return {
6522
- kind: "document-model",
6523
- unit: `${packagePath(packageRoot, directory.path)}/`,
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 ?? [])
6527
- };
7716
+ ]);
7717
+ //#endregion
7718
+ //#region src/definition/tooling/subgraph/input.ts
7719
+ /** A host registers a package scalar by the export bound under the scalar's own name. */
7720
+ function exportedScalarNames(scalars) {
7721
+ return Object.entries(scalars).flatMap(([exportName, value]) => isScalarDefinition(value) && value.name === exportName ? [exportName] : []).sort(compareCodeUnits);
6528
7722
  }
6529
- function unreadableDiagnostic(packageRoot, { path, error }) {
6530
- return toolingDiagnostics.create({
7723
+ function importFailed({ specifier, reason }) {
7724
+ return subgraphToolingDiagnostics.create({
6531
7725
  code: "PH-IMPORT-FAILED",
6532
- source: { specifier: packagePath(packageRoot, path) },
7726
+ source: { specifier },
6533
7727
  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."
7728
+ message: `${specifier} could not be imported, so the subgraph checks that read it did not run.`,
7729
+ expected: "an importable TypeScript module",
7730
+ received: reason,
7731
+ repair: "Fix this module or one of its imports, then check again."
6538
7732
  });
6539
7733
  }
6540
7734
  /**
6541
- * Each `<documentModelsDir>/<name>/` whose sources declare a code-first model
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
6544
- * import reaches files no one can name, so the scan then reports nothing.
7735
+ * @experimental Builds the subgraph check input and the inventory entries
7736
+ * once, for the check, inspection and release callers to share. `scalars`
7737
+ * is the namespace of `scalars/index.ts`: `null` when the package has none,
7738
+ * absent when the caller did not read it. `importFailures` names the
7739
+ * modules the caller could not import. `hostConflicts` is the caller's replay
7740
+ * of a host's admission of the code-first subgraphs.
6545
7741
  */
6546
- function findUnregisteredDefinitions(request) {
6547
- const { packageRoot, documentModelsDir, sources, importedFiles, loadedDocumentTypes } = request;
6548
- const imported = sources.map(({ specifier }) => importedFiles(specifier));
6549
- if (imported.some((files) => files.length === 0)) return {
6550
- unregistered: [],
6551
- diagnostics: []
7742
+ function subgraphCheckInput(request) {
7743
+ const { definitions, scalars } = request;
7744
+ return {
7745
+ input: {
7746
+ codeFirst: definitions.subgraphs,
7747
+ schemaFirst: request.schemaFirst ?? [],
7748
+ packageScalars: scalars === void 0 ? void 0 : scalars === null ? [] : exportedScalarNames(scalars),
7749
+ diagnostics: [...(request.importFailures ?? []).map(importFailed), ...definitions.diagnostics],
7750
+ hostConflicts: request.hostConflicts ?? []
7751
+ },
7752
+ inventory: definitions.subgraphs.map(({ name, source, definition }) => ({
7753
+ kind: "subgraph",
7754
+ key: name,
7755
+ digest: canonicalDigest(definition),
7756
+ source
7757
+ }))
6552
7758
  };
6553
- const reached = new Set(imported.flat().map(realPathOrSelf));
6554
- const packageRootIdentity = realPathOrSelf(packageRoot);
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));
7759
+ }
7760
+ //#endregion
7761
+ //#region src/definition/tooling/subgraph/inspection.ts
7762
+ function coordinates(entries) {
7763
+ return entries.map((entry) => {
7764
+ switch (entry.kind) {
7765
+ case "query":
7766
+ case "mutation":
7767
+ case "subscription": return `${ROOT_TYPES$1[entry.kind]}.${entry.fieldName}`;
7768
+ case "computed-field": return `${entry.typeName}.${entry.fieldName}`;
7769
+ case "resolve-type":
7770
+ case "is-type-of": return entry.typeName;
7771
+ }
7772
+ });
7773
+ }
7774
+ /**
7775
+ * @experimental Adds the project's subgraphs to an inspection report: a
7776
+ * `subgraphs` section, the subgraph diagnostics, and a status that counts
7777
+ * them. A project whose only definitions are subgraphs is not skipped.
7778
+ */
7779
+ function withSubgraphInspection(project, report, subgraphs) {
7780
+ const diagnostics = sortedUniqueDiagnostics([...report.diagnostics, ...subgraphs.diagnostics]);
6559
7781
  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
- }];
7782
+ ...report,
7783
+ status: definitionStatus({
7784
+ ...project.skipReason !== void 0 && { skipReason: project.skipReason },
7785
+ definitions: [...project.artifacts, ...subgraphs.codeFirst],
7786
+ diagnostics
6569
7787
  }),
6570
- diagnostics: unreadable.filter(({ path }) => !modelDirectories.has(path)).map((entry) => unreadableDiagnostic(packageRoot, entry))
7788
+ diagnostics,
7789
+ subgraphs: [...subgraphs.codeFirst.map(({ name, source, definition }) => ({
7790
+ style: "code-first",
7791
+ name,
7792
+ source,
7793
+ digest: canonicalDigest(definition),
7794
+ hasSubscriptions: definition.hasSubscriptions,
7795
+ entries: coordinates(definition.entries),
7796
+ types: definition.types.map((type) => type.name),
7797
+ scalars: definition.scalars.map(({ name, implementation }) => ({
7798
+ name,
7799
+ implementation
7800
+ }))
7801
+ })), ...subgraphs.schemaFirst.map(({ name, source }) => ({
7802
+ style: "schema-first",
7803
+ name,
7804
+ source
7805
+ }))]
6571
7806
  };
6572
7807
  }
6573
7808
  //#endregion
6574
- //#region src/definition/tooling/project/project-definitions.ts
6575
- const DEFAULT_DOCUMENT_MODELS_DIR = "./document-models";
6576
- /** Code-first sources are authored in normalized coordinates, so they need no relocation. */
6577
- const adaptSelectedModules = ({ loaded }) => {
6578
- const results = loaded.documentModels.map(({ value, source }) => {
6579
- const result = adaptCodeFirstDocumentModelSource(value, source);
6580
- return {
6581
- artifacts: result.artifacts,
6582
- diagnostics: result.diagnostics.map((diagnostic) => diagnostic.source === void 0 ? {
6583
- ...diagnostic,
6584
- source
6585
- } : diagnostic)
6586
- };
6587
- });
7809
+ //#region src/definition/subgraph/protocol.ts
7810
+ /**
7811
+ * @experimental The static member that marks a code-first subgraph class.
7812
+ * `Symbol.for` makes it the same key in every copy of the package; the
7813
+ * protocol's `version` says which contract the class speaks.
7814
+ */
7815
+ const SUBGRAPH_PROTOCOL = Symbol.for("powerhouse.subgraph.protocol");
7816
+ /**
7817
+ * @experimental Reads the protocol of a subgraph export. It reads only the
7818
+ * static `SUBGRAPH_PROTOCOL` member of a function: it never constructs the
7819
+ * class or calls the protocol.
7820
+ */
7821
+ function readSubgraphProtocol(value) {
7822
+ if (typeof value !== "function") return { kind: "schema-first" };
7823
+ const protocol = value[SUBGRAPH_PROTOCOL];
7824
+ if (protocol === void 0) return { kind: "schema-first" };
7825
+ if (protocol === null || typeof protocol !== "object") return {
7826
+ kind: "unsupported",
7827
+ version: void 0
7828
+ };
7829
+ const candidate = protocol;
7830
+ if (candidate.version === 1 && typeof candidate.describe === "function" && typeof candidate.validate === "function") return {
7831
+ kind: "code-first",
7832
+ protocol
7833
+ };
6588
7834
  return {
6589
- artifacts: results.flatMap(({ artifacts }) => artifacts),
6590
- diagnostics: results.flatMap(({ diagnostics }) => diagnostics),
6591
- relocations: /* @__PURE__ */ new Map()
7835
+ kind: "unsupported",
7836
+ version: candidate.version
6592
7837
  };
6593
- };
6594
- /** The readers a project loads with unless a caller passes its own; the one place an authoring mode is named. */
6595
- const defaultDefinitionProducers = Object.freeze([adaptSelectedModules, readStoredDocumentModels]);
6596
- /** A path that cannot be inspected is left to the readers, which report it. */
6597
- function namesNonDirectory(path) {
6598
- try {
6599
- return statSync(path, { throwIfNoEntry: false })?.isDirectory() === false;
6600
- } catch {
6601
- return false;
7838
+ }
7839
+ //#endregion
7840
+ //#region src/definition/tooling/subgraph/read.ts
7841
+ const DEFAULT_SPECIFIER = "./subgraphs/index.ts";
7842
+ /** An ES module namespace lists its exports by name; Vite's runner lists them in statement order. */
7843
+ function entriesByName(record) {
7844
+ const keys = Object.keys(record);
7845
+ if (Object.prototype.toString.call(record) === "[object Module]") keys.sort();
7846
+ return keys.map((key) => [key, record[key]]);
7847
+ }
7848
+ /**
7849
+ * Every function a module exports, directly or as a value of an exported
7850
+ * object, as the host's subgraph extraction reaches them. A value reached
7851
+ * twice keeps its first path.
7852
+ */
7853
+ function candidatesOf(exports) {
7854
+ const found = /* @__PURE__ */ new Map();
7855
+ const add = (value, exportPath) => {
7856
+ if (typeof value !== "function" || found.has(value)) return;
7857
+ found.set(value, {
7858
+ value,
7859
+ exportPath
7860
+ });
7861
+ };
7862
+ for (const [key, value] of entriesByName(exports)) {
7863
+ add(value, [key]);
7864
+ if (value !== null && typeof value === "object") for (const [innerKey, inner] of entriesByName(value)) add(inner, [key, innerKey]);
6602
7865
  }
7866
+ return [...found.values()];
6603
7867
  }
6604
- /** The configured models directory, or why it cannot be scanned. */
6605
- function documentModelsDirectory(packageRoot, configFile) {
6606
- const config = readConfigObject(resolve(configFile));
6607
- if (!config.ok) return { diagnostics: [] };
6608
- const configured = config.value.documentModelsDir ?? DEFAULT_DOCUMENT_MODELS_DIR;
6609
- if (typeof configured !== "string" || configured.trim() === "") return { diagnostics: [toolingDiagnostics.create({
6610
- code: "PH-CONFIG-SOURCE-INVALID",
6611
- path: ["documentModelsDir"],
6612
- message: "documentModelsDir is not a directory path.",
6613
- expected: "a package-relative path such as ./document-models",
6614
- received: JSON.stringify(configured),
6615
- repair: "Set documentModelsDir to a package-relative directory, or remove it to use ./document-models."
6616
- })] };
6617
- const path = resolve(packageRoot, configured);
6618
- let inside = pathWithin(packageRoot, path) !== null;
7868
+ function extendsClass(derived, base) {
7869
+ for (let current = Object.getPrototypeOf(derived); current !== null && current !== void 0; current = Object.getPrototypeOf(current)) if (current === base) return true;
7870
+ return false;
7871
+ }
7872
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
7873
+ /** A description from another copy of document-model, checked before use. */
7874
+ function isDescription(value) {
7875
+ if (value === null || typeof value !== "object") return false;
7876
+ const description = value;
7877
+ return Array.isArray(description.diagnostics) && (description.name === void 0 || typeof description.name === "string") && (description.definition === void 0 || description.definition !== null && typeof description.definition === "object");
7878
+ }
7879
+ function describeFailed(source, received, message) {
7880
+ return subgraphToolingDiagnostics.create({
7881
+ code: "PH-SG-DESCRIBE-FAILED",
7882
+ source,
7883
+ path: [],
7884
+ message,
7885
+ expected: "a description with diagnostics, and a name and definition",
7886
+ received,
7887
+ repair: "Keep the subgraph's static members free of side effects: describe() compiles getSchema() and must not throw."
7888
+ });
7889
+ }
7890
+ function describe(protocol, source, label) {
7891
+ let description;
6619
7892
  try {
6620
- inside &&= pathWithin(realpathSync.native(packageRoot), realPathThroughExistingParent(path)) !== null;
6621
- } catch {
6622
- inside = false;
7893
+ description = protocol.describe();
7894
+ } catch (error) {
7895
+ return {
7896
+ kind: "failed",
7897
+ diagnostic: describeFailed(source, "a thrown error", `describe() of ${label} threw: ${errorMessage(error)}`)
7898
+ };
6623
7899
  }
6624
- if (!inside) return { diagnostics: [toolingDiagnostics.create({
6625
- code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
6626
- path: ["documentModelsDir"],
6627
- message: "documentModelsDir leaves the package root, so its models are not this package's.",
6628
- expected: "a directory inside the package",
6629
- received: configured,
6630
- repair: "Point documentModelsDir at a directory inside the package."
6631
- })] };
6632
- if (namesNonDirectory(path)) return { diagnostics: [toolingDiagnostics.create({
6633
- code: "PH-CONFIG-SOURCE-INVALID",
6634
- path: ["documentModelsDir"],
6635
- message: "documentModelsDir names a file, not a directory.",
6636
- expected: "a package-relative directory such as ./document-models",
6637
- received: configured,
6638
- repair: "Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models."
6639
- })] };
7900
+ if (!isDescription(description)) return {
7901
+ kind: "failed",
7902
+ diagnostic: describeFailed(source, describeReceived(description), `describe() of ${label} returned no subgraph description.`)
7903
+ };
6640
7904
  return {
6641
- path,
6642
- diagnostics: []
7905
+ kind: "described",
7906
+ description
6643
7907
  };
6644
7908
  }
6645
- /** Tool and Node messages can quote the machine path a package lives at. */
6646
- function packageRelative(diagnostics, packageRoot) {
6647
- let real = packageRoot;
6648
- try {
6649
- real = realpathSync.native(packageRoot);
6650
- } catch {}
6651
- const roots = [.../* @__PURE__ */ new Set([packageRoot, real])].sort((left, right) => right.length - left.length).flatMap((root) => [pathToFileURL(root).href, root]);
6652
- const rewrite = (text) => roots.reduce((result, root) => result.replaceAll(root, "."), text);
6653
- return diagnostics.map((diagnostic) => ({
6654
- ...diagnostic,
6655
- message: rewrite(diagnostic.message),
6656
- repair: rewrite(diagnostic.repair),
6657
- ...diagnostic.expected !== void 0 && { expected: rewrite(diagnostic.expected) },
6658
- ...diagnostic.received !== void 0 && { received: rewrite(diagnostic.received) },
6659
- ...diagnostic.related !== void 0 && { related: diagnostic.related.map((location) => ({
6660
- ...location,
6661
- message: rewrite(location.message)
6662
- })) }
6663
- }));
6664
- }
6665
7909
  /**
6666
- * @experimental Loads the selected code-first sources and the package's stored
6667
- * schema-first models, and scans for code-first declarations no source
6668
- * reaches. Artifacts and diagnostics are sorted and package relative.
6669
- * `producers` replaces the default readers. `importedFiles` names the
6670
- * absolute paths of every module the loader's import of a selected
6671
- * specifier evaluated, so reach follows whatever the importer resolved.
6672
- * Experimental while code-first projects are introduced.
7910
+ * @experimental Reads the code-first subgraph classes a module exports, as
7911
+ * the host's extraction reaches them: each export, and each value of an
7912
+ * exported object. It calls each class's protocol `describe()` and never
7913
+ * constructs a class, so a constructor that needs a database or environment
7914
+ * does not run. Schema-first classes and other values are left out. A
7915
+ * code-first class without a name is a base: it is skipped when another
7916
+ * export extends it, and reported when none does.
6673
7917
  */
6674
- async function loadProjectDefinitions(request) {
6675
- const { loader, producers = defaultDefinitionProducers, importedFiles, ...load } = request;
6676
- const loaded = await loader.normalizeDefinitionSources(load);
6677
- request.signal?.throwIfAborted();
6678
- const { packageRoot } = loaded;
6679
- const directory = documentModelsDirectory(packageRoot, request.configFile);
6680
- const modelsDir = directory.path;
6681
- const input = {
6682
- ...load,
6683
- loader,
6684
- packageRoot,
6685
- loaded,
6686
- ...modelsDir !== void 0 && { documentModelsDir: modelsDir }
6687
- };
6688
- const produced = [];
6689
- for (const producer of producers) produced.push(await producer(input));
6690
- request.signal?.throwIfAborted();
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
- };
7918
+ function readSubgraphDefinitions(exports, options = {}) {
7919
+ const specifier = options.specifier ?? DEFAULT_SPECIFIER;
7920
+ const codeFirst = [];
7921
+ const diagnostics = [];
7922
+ for (const candidate of candidatesOf(exports)) {
7923
+ const source = {
7924
+ specifier,
7925
+ exportPath: candidate.exportPath
7926
+ };
7927
+ const label = candidate.exportPath.join(".");
7928
+ let read;
7929
+ try {
7930
+ read = readSubgraphProtocol(candidate.value);
7931
+ } catch (error) {
7932
+ diagnostics.push(describeFailed(source, "a thrown error", `Reading the subgraph protocol of ${label} threw: ${errorMessage(error)}`));
7933
+ continue;
7934
+ }
7935
+ if (read.kind === "code-first") codeFirst.push({
7936
+ ...candidate,
7937
+ protocol: read.protocol
7938
+ });
7939
+ else if (read.kind === "unsupported") diagnostics.push(subgraphToolingDiagnostics.create({
7940
+ code: "PH-SG-PROTOCOL-UNSUPPORTED",
7941
+ source,
7942
+ path: [],
7943
+ message: `${label} carries subgraph protocol version ${String(read.version)}, and this release reads version 1.`,
7944
+ expected: "protocol version 1",
7945
+ received: String(read.version),
7946
+ repair: "Build the package against the @powerhousedao/reactor-api release this ph-cli belongs to, or update ph-cli."
7947
+ }));
7948
+ }
7949
+ const subgraphs = [];
7950
+ for (const candidate of codeFirst) {
7951
+ const source = {
7952
+ specifier,
7953
+ exportPath: candidate.exportPath
7954
+ };
7955
+ const label = candidate.exportPath.join(".");
7956
+ const described = describe(candidate.protocol, source, label);
7957
+ if (described.kind === "failed") {
7958
+ diagnostics.push(described.diagnostic);
7959
+ continue;
7960
+ }
7961
+ const { name, definition } = described.description;
7962
+ if (name === void 0) {
7963
+ if (codeFirst.some(({ value }) => extendsClass(value, candidate.value))) continue;
7964
+ diagnostics.push(subgraphToolingDiagnostics.create({
7965
+ code: "PH-SG-NAME-MISSING",
7966
+ source,
7967
+ path: [],
7968
+ message: `${label} has no static subgraphName, and no other export extends it.`,
7969
+ expected: "a static subgraphName, or a subclass that declares one",
7970
+ received: "no subgraphName",
7971
+ repair: "Declare static readonly subgraphName on the class, or export only the subclasses that extend it."
7972
+ }));
7973
+ continue;
7974
+ }
7975
+ for (const diagnostic of described.description.diagnostics) diagnostics.push(diagnostic.source === void 0 ? {
7976
+ ...diagnostic,
7977
+ source
7978
+ } : diagnostic);
7979
+ if (definition?.schemaKind === "typed") subgraphs.push({
7980
+ name,
7981
+ source,
7982
+ definition
7983
+ });
7984
+ }
6701
7985
  return {
6702
- packageRoot,
6703
- sourceSet: loaded.sourceSet,
6704
- ...loaded.status === "skipped" && { skipReason: loaded.skipReason },
6705
- artifacts: produced.flatMap(({ artifacts }) => artifacts).sort(compareArtifacts),
6706
- relocations: new Map(produced.flatMap(({ relocations }) => [...relocations])),
6707
- diagnostics: sortedUniqueDiagnostics(packageRelative([
6708
- ...loaded.diagnostics,
6709
- ...directory.diagnostics,
6710
- ...produced.flatMap(({ diagnostics }) => diagnostics),
6711
- ...scan.diagnostics
6712
- ], packageRoot)),
6713
- unregistered: scan.unregistered
7986
+ subgraphs,
7987
+ diagnostics
6714
7988
  };
6715
7989
  }
6716
7990
  //#endregion
6717
- export { DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, checkProjectDefinitions, documentModelChecks, formatDefinitionDiagnostic, formatDefinitionSource, inspectProjectDefinitions, loadProjectDefinitions, releaseChecks, resolveDefinitionSelection };
7991
+ export { DEFAULT_DOCUMENT_MODELS_DIR, DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, checkProjectDefinitions, codeFirstDeclarationFiles, discoverDocumentModelDirectories, documentModelChecks, findUnregisteredDefinitions, formatDefinitionDiagnostic, formatDefinitionSource, inspectProjectDefinitions, loadProjectDefinitions, readSubgraphDefinitions, releaseChecks, resolveDefinitionSelection, resolveDocumentModelsDir, subgraphCheckInput, subgraphChecks, unregisteredDefinitionDiagnostics, withSubgraphInspection };
6718
7992
 
6719
7993
  //# sourceMappingURL=tooling.mjs.map