@powerhousedao/ph-cli 6.2.3-dev.101 → 6.2.3-dev.102

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.
Files changed (72) hide show
  1. package/dist/{build-CojYJHNn.mjs → build-D9Zjxsfj.mjs} +63 -11
  2. package/dist/build-D9Zjxsfj.mjs.map +1 -0
  3. package/dist/build-DkPj-Gz1.mjs +4 -0
  4. package/dist/{check-BBd5xzUi.mjs → check-NJ07yjW8.mjs} +3 -3
  5. package/dist/{check-DWvobZrP.mjs → check-S29MtxQp.mjs} +32 -11
  6. package/dist/check-S29MtxQp.mjs.map +1 -0
  7. package/dist/cli.mjs +3 -3
  8. package/dist/{connect-build-B9Btboix.mjs → connect-build-DvFdfDP-.mjs} +4 -4
  9. package/dist/{connect-build-B9Btboix.mjs.map → connect-build-DvFdfDP-.mjs.map} +1 -1
  10. package/dist/definitions-worker.d.mts.map +1 -1
  11. package/dist/definitions-worker.mjs +5 -5
  12. package/dist/definitions-worker.mjs.map +1 -1
  13. package/dist/{evidence-Dchpoogs.mjs → evidence-CavwC5YV.mjs} +23 -9
  14. package/dist/evidence-CavwC5YV.mjs.map +1 -0
  15. package/dist/{generate-all-_7S0Iii2.mjs → generate-all-cgygbYEX.mjs} +5 -5
  16. package/dist/generate-all-cgygbYEX.mjs.map +1 -0
  17. package/dist/{generate-document-model-DCjzz3Sa.mjs → generate-document-model-OQPfeHs-.mjs} +25 -21
  18. package/dist/generate-document-model-OQPfeHs-.mjs.map +1 -0
  19. package/dist/{generate-editor-DdoapkEK.mjs → generate-editor-DBj_Pxwa.mjs} +7 -7
  20. package/dist/generate-editor-DBj_Pxwa.mjs.map +1 -0
  21. package/dist/{generate-subgraph-CrHbYK91.mjs → generate-subgraph-DJZCr0Tk.mjs} +34 -12
  22. package/dist/generate-subgraph-DJZCr0Tk.mjs.map +1 -0
  23. package/dist/{get-version-DUG29IeG.mjs → get-version-CeMBGufv.mjs} +4 -4
  24. package/dist/{get-version-DUG29IeG.mjs.map → get-version-CeMBGufv.mjs.map} +1 -1
  25. package/dist/{inspect-BpVHe9vz.mjs → inspect-CulIpVsF.mjs} +13 -7
  26. package/dist/inspect-CulIpVsF.mjs.map +1 -0
  27. package/dist/{mcp-DEBeM-ZV.mjs → mcp-HSikd5iv.mjs} +4 -4
  28. package/dist/{mcp-DEBeM-ZV.mjs.map → mcp-HSikd5iv.mjs.map} +1 -1
  29. package/dist/migrate-subgraphs-Cm7DDcDd.mjs +214 -0
  30. package/dist/migrate-subgraphs-Cm7DDcDd.mjs.map +1 -0
  31. package/dist/module-dir-1avCXsBi.mjs +2 -2
  32. package/dist/module-dir-1avCXsBi.mjs.map +1 -1
  33. package/dist/{ph-cli-commands-BG9deyv9.mjs → ph-cli-commands-CX927REY.mjs} +43 -22
  34. package/dist/ph-cli-commands-CX927REY.mjs.map +1 -0
  35. package/dist/ph-cli-commands-SrvFNgNF.mjs +4 -0
  36. package/dist/render-3M3DwFzO.mjs +4 -0
  37. package/dist/{render-BO-Nwn2H.mjs → render-SVfj3m8A.mjs} +19 -13
  38. package/dist/render-SVfj3m8A.mjs.map +1 -0
  39. package/dist/{run-DEKE4MJY.mjs → run--de_-WAz.mjs} +5 -4
  40. package/dist/run--de_-WAz.mjs.map +1 -0
  41. package/dist/{run-DP3fNgPv.mjs → run-LRGy7zGo.mjs} +3 -3
  42. package/dist/runners/connect.mjs +1 -1
  43. package/dist/runners/switchboard.mjs +1 -1
  44. package/dist/subgraph-gate-BJ2PWXVY.mjs +26 -0
  45. package/dist/subgraph-gate-BJ2PWXVY.mjs.map +1 -0
  46. package/dist/subgraph-gate-j9ywj6KA.mjs +4 -0
  47. package/dist/subgraphs-7OYWwP-C.mjs +134 -0
  48. package/dist/subgraphs-7OYWwP-C.mjs.map +1 -0
  49. package/dist/{switchboard-migrate-Docb8Cjv.mjs → switchboard-migrate-BqSdKJ7u.mjs} +3 -4
  50. package/dist/switchboard-migrate-BqSdKJ7u.mjs.map +1 -0
  51. package/dist/{verify-CT24vch8.mjs → verify-BrMeKdLA.mjs} +4 -4
  52. package/dist/{verify-CT24vch8.mjs.map → verify-BrMeKdLA.mjs.map} +1 -1
  53. package/dist/{vetra-DSFzAl_1.mjs → vetra-DjNt0-L6.mjs} +4 -4
  54. package/dist/{vetra-DSFzAl_1.mjs.map → vetra-DjNt0-L6.mjs.map} +1 -1
  55. package/package.json +16 -16
  56. package/dist/authoring-mode-DWbbsuWh.mjs +0 -23
  57. package/dist/authoring-mode-DWbbsuWh.mjs.map +0 -1
  58. package/dist/build-CojYJHNn.mjs.map +0 -1
  59. package/dist/build-CsUTeki9.mjs +0 -4
  60. package/dist/check-DWvobZrP.mjs.map +0 -1
  61. package/dist/evidence-Dchpoogs.mjs.map +0 -1
  62. package/dist/generate-all-_7S0Iii2.mjs.map +0 -1
  63. package/dist/generate-document-model-DCjzz3Sa.mjs.map +0 -1
  64. package/dist/generate-editor-DdoapkEK.mjs.map +0 -1
  65. package/dist/generate-subgraph-CrHbYK91.mjs.map +0 -1
  66. package/dist/inspect-BpVHe9vz.mjs.map +0 -1
  67. package/dist/ph-cli-commands-BG9deyv9.mjs.map +0 -1
  68. package/dist/ph-cli-commands-Dn56Erg5.mjs +0 -4
  69. package/dist/render-BO-Nwn2H.mjs.map +0 -1
  70. package/dist/render-DdieUjtg.mjs +0 -4
  71. package/dist/run-DEKE4MJY.mjs.map +0 -1
  72. package/dist/switchboard-migrate-Docb8Cjv.mjs.map +0 -1
@@ -1,9 +1,9 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4535eeb7-fe12-5c56-bd4a-286b6b513227")}catch(e){}}();
3
- import { n as selectProjectModelGeneration } from "./authoring-mode-DWbbsuWh.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0204e193-cfc3-57bd-8acf-bc46414176a5")}catch(e){}}();
4
3
  import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
5
4
  import { existsSync } from "node:fs";
6
5
  import { join } from "node:path";
6
+ import { modelGeneration } from "@powerhousedao/codegen";
7
7
  import { buildTsMorphProject, getEditorMetadata } from "@powerhousedao/codegen/utils";
8
8
  import { extractEditorDocuments, generateEditorFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
9
9
  //#region src/services/generate-editor.ts
@@ -23,7 +23,7 @@ async function startGenerateEditor(args, projectDir) {
23
23
  }
24
24
  const report = [];
25
25
  if (all) {
26
- const { editors, unreadableDirs } = await selectProjectModelGeneration(projectDir).generateAllEditors(project);
26
+ const { editors, unreadableDirs } = await modelGeneration.generateAllEditors(project);
27
27
  if (editors.length === 0 && unreadableDirs.length === 0) report.push("No document editors found in editors/.");
28
28
  for (const editor of editors) report.push(`Regenerated editor "${editor.name}" in editors/${editor.dirName}`);
29
29
  for (const dirName of unreadableDirs) console.warn(`Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's editors.`);
@@ -32,7 +32,7 @@ async function startGenerateEditor(args, projectDir) {
32
32
  await generateEditorFromDocument(doc, project);
33
33
  } else if (name) {
34
34
  if (!documentType) throw new Error("Please specify a document type for the new editor to generate.");
35
- await selectProjectModelGeneration(projectDir).generateEditor({
35
+ await modelGeneration.generateEditor({
36
36
  editorName: name,
37
37
  documentTypes: [documentType]
38
38
  }, project);
@@ -43,7 +43,7 @@ async function startGenerateEditor(args, projectDir) {
43
43
  if (!editorArgs) throw new Error(`Could not read editors/${dirName}/module.ts: expected ${MODULE_FILE_EXPECTATION}.`);
44
44
  if (editorArgs.documentTypes.includes("powerhouse/document-drive")) throw new Error(`editors/${dirName} is a drive app, not a document editor. Use \`ph-cli generate app --dir ${dirName}\` instead.`);
45
45
  const { name: editorName, id: editorId, dirName: editorDirName, documentTypes } = editorArgs;
46
- await selectProjectModelGeneration(projectDir).generateEditor({
46
+ await modelGeneration.generateEditor({
47
47
  editorName,
48
48
  editorId,
49
49
  editorDirName,
@@ -60,5 +60,5 @@ async function startGenerateEditor(args, projectDir) {
60
60
  //#endregion
61
61
  export { startGenerateEditor };
62
62
 
63
- //# sourceMappingURL=generate-editor-DdoapkEK.mjs.map
64
- //# debugId=4535eeb7-fe12-5c56-bd4a-286b6b513227
63
+ //# sourceMappingURL=generate-editor-DBj_Pxwa.mjs.map
64
+ //# debugId=0204e193-cfc3-57bd-8acf-bc46414176a5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-editor-DBj_Pxwa.mjs","sources":["../src/services/generate-editor.ts"],"sourcesContent":["import { modelGeneration } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n getEditorMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport {\n extractEditorDocuments,\n generateEditorFromDocument,\n getDocument,\n saveSpec,\n} from \"@powerhousedao/vetra/codegen\";\nimport type { DocumentEditorDocument } from \"@powerhousedao/vetra/document-models/document-editor\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateEditorArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\n\nconst MODULE_FILE_EXPECTATION =\n \"an EditorModule with string literals for config.id, config.name and documentTypes\";\n\nexport async function startGenerateEditor(\n args: GenerateEditorArgs,\n projectDir: string,\n) {\n const { name, documentType, document, dir, all, extract, debug } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n if (extract) {\n const docs = extractEditorDocuments(project);\n if (docs.length === 0) {\n console.log(\"No document editors found in editors/.\");\n }\n for (const doc of docs) {\n const path = await saveSpec(doc, projectDir);\n console.log(`Wrote ${path}`);\n }\n return;\n }\n const report: string[] = [];\n if (all) {\n const { editors, unreadableDirs } =\n await modelGeneration.generateAllEditors(project);\n if (editors.length === 0 && unreadableDirs.length === 0) {\n report.push(\"No document editors found in editors/.\");\n }\n for (const editor of editors) {\n report.push(\n `Regenerated editor \"${editor.name}\" in editors/${editor.dirName}`,\n );\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's editors.`,\n );\n }\n } else if (document) {\n const doc = (await getDocument(document)) as DocumentEditorDocument;\n await generateEditorFromDocument(doc, project);\n } else if (name) {\n if (!documentType) {\n throw new Error(\n \"Please specify a document type for the new editor to generate.\",\n );\n }\n await modelGeneration.generateEditor(\n { editorName: name, documentTypes: [documentType] },\n project,\n );\n } else if (dir) {\n const dirName = resolveModuleDirName(\n projectDir,\n \"editors\",\n dir,\n \"my-editor\",\n );\n if (!existsSync(join(projectDir, \"editors\", dirName, \"module.ts\"))) {\n throw new Error(`editors/${dirName} has no module.ts.`);\n }\n const editorArgs = getEditorMetadata(project, dirName);\n if (!editorArgs) {\n throw new Error(\n `Could not read editors/${dirName}/module.ts: expected ${MODULE_FILE_EXPECTATION}.`,\n );\n }\n if (editorArgs.documentTypes.includes(\"powerhouse/document-drive\")) {\n throw new Error(\n `editors/${dirName} is a drive app, not a document editor. Use \\`ph-cli generate app --dir ${dirName}\\` instead.`,\n );\n }\n const {\n name: editorName,\n id: editorId,\n dirName: editorDirName,\n documentTypes,\n } = editorArgs;\n await modelGeneration.generateEditor(\n {\n editorName,\n editorId,\n editorDirName,\n documentTypes,\n },\n project,\n );\n report.push(\n `Regenerated editor \"${editorName}\" in editors/${editorDirName}`,\n );\n } else {\n console.log(\n \"Please specify one of `name`, `document`, `dir`, `all`, or `extract`.\",\n );\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAiBA,MAAM,0BACJ;AAEF,eAAsB,oBACpB,MACA,YACA;C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F;EAEF,IAAI,WAAW,cAAc,SAAS,2BAA2B,GAC/D,MAAM,IAAI,MACR,WAAW,QAAQ,0EAA0E,QAAQ,YACvG;EAEF,MAAM,EACJ,MAAM,YACN,IAAI,UACJ,SAAS,eACT,kBACE;EACJ,MAAM,gBAAgB,eACpB;GACE;GACA;GACA;GACA;EACF,GACA,OACF;EACA,OAAO,KACL,uBAAuB,WAAW,eAAe,eACnD;CACF,OAAO;EACL,QAAQ,IACN,uEACF;EACA;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ,QACjB,QAAQ,IAAI,IAAI;AAEpB","debug_id":"0204e193-cfc3-57bd-8acf-bc46414176a5"}
@@ -1,19 +1,32 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2e0f1963-117b-5df1-a61a-61579e3ef622")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="57f37708-e436-5415-9747-38ee27ce7f15")}catch(e){}}();
3
3
  import { t as installAddedDependencies$1 } from "./install-added-dependencies-DnZFR3aE.mjs";
4
4
  import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-BOHBmThq.mjs";
5
5
  import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
6
6
  import { existsSync } from "node:fs";
7
7
  import { join } from "node:path";
8
- import { detectFeatures, generateAllSubgraphs, generateSubgraph, syncFeatureDependencies } from "@powerhousedao/codegen";
9
- import { buildTsMorphProject, getSubgraphMetadata } from "@powerhousedao/codegen/utils";
8
+ import { detectFeatures, generateAllSubgraphs, generateSubgraph, generateSubgraphDir, syncFeatureDependencies } from "@powerhousedao/codegen";
9
+ import { buildTsMorphProject, subgraphDirStyle } from "@powerhousedao/codegen/utils";
10
10
  import { extractSubgraphDocuments, findSubgraphNameConflict, generateSubgraphFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
11
+ import { kebabCase } from "change-case";
11
12
  //#region src/services/generate-subgraph.ts
12
- const INDEX_FILE_EXPECTATION = "a class extending BaseSubgraph with a string literal `name`";
13
+ const INDEX_FILE_EXPECTATION = {
14
+ "schema-first": "a class extending BaseSubgraph with a string literal `name`",
15
+ "code-first": "a class extending Subgraph with a string literal `static subgraphName`"
16
+ };
13
17
  async function assertSubgraphNameFree(projectDir, name) {
14
18
  const conflict = await findSubgraphNameConflict(projectDir, name);
15
19
  if (conflict) throw new Error(conflict);
16
20
  }
21
+ /** The notice for `--code-first` on an existing schema-first subgraph, which
22
+ * is then left unchanged. */
23
+ function codeFirstOnSchemaFirst(args, projectDir, name) {
24
+ if (!args.codeFirst) return void 0;
25
+ const subgraphsDir = join(projectDir, "subgraphs");
26
+ const dirName = kebabCase(name);
27
+ if (!existsSync(join(subgraphsDir, dirName, "index.ts")) || subgraphDirStyle(subgraphsDir, dirName) !== "schema-first") return void 0;
28
+ return `subgraphs/${dirName} is schema-first; --code-first only applies to new subgraphs. To convert it, run ph migrate --subgraph ${dirName}.`;
29
+ }
17
30
  async function startGenerateSubgraph(args, projectDir) {
18
31
  const { name, document, dir, all, extract, debug } = args;
19
32
  if (debug) console.log({ args });
@@ -32,20 +45,29 @@ async function startGenerateSubgraph(args, projectDir) {
32
45
  const { subgraphNames, unreadableDirs } = await generateAllSubgraphs(project);
33
46
  if (subgraphNames.length === 0 && unreadableDirs.length === 0) report.push("No subgraphs found in subgraphs/.");
34
47
  for (const subgraphName of subgraphNames) report.push(`Regenerated subgraph "${subgraphName}"`);
35
- for (const dirName of unreadableDirs) console.warn(`Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION}. Kept the manifest's subgraphs.`);
48
+ for (const dirName of unreadableDirs) console.warn(`Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION[subgraphDirStyle(join(projectDir, "subgraphs"), dirName)]}. Kept the manifest's subgraphs.`);
36
49
  } else if (document) {
37
50
  const doc = await getDocument(document);
51
+ const notice = codeFirstOnSchemaFirst(args, projectDir, doc.state.global.name);
52
+ if (notice) {
53
+ console.log(notice);
54
+ return;
55
+ }
38
56
  await assertSubgraphNameFree(projectDir, doc.state.global.name);
39
- await generateSubgraphFromDocument(doc, project);
57
+ await generateSubgraphFromDocument(doc, project, { codeFirst: args.codeFirst });
40
58
  } else if (name) {
59
+ const notice = codeFirstOnSchemaFirst(args, projectDir, name);
60
+ if (notice) {
61
+ console.log(notice);
62
+ return;
63
+ }
41
64
  await assertSubgraphNameFree(projectDir, name);
42
- await generateSubgraph(name, project);
65
+ await generateSubgraph(name, project, { codeFirst: args.codeFirst });
43
66
  } else if (dir) {
44
67
  const dirName = resolveModuleDirName(projectDir, "subgraphs", dir, "my-subgraph");
45
68
  if (!existsSync(join(projectDir, "subgraphs", dirName, "index.ts"))) throw new Error(`subgraphs/${dirName} has no index.ts.`);
46
- const { subgraphName } = getSubgraphMetadata(project, dirName);
47
- if (!subgraphName) throw new Error(`Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION}.`);
48
- await generateSubgraph(subgraphName, project);
69
+ const { subgraphName, style } = await generateSubgraphDir(dirName, project);
70
+ if (!subgraphName) throw new Error(`Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION[style]}.`);
49
71
  report.push(`Regenerated subgraph "${subgraphName}"`);
50
72
  } else {
51
73
  console.log("Please specify one of `name`, `document`, `dir`, `all`, or `extract`.");
@@ -60,5 +82,5 @@ async function startGenerateSubgraph(args, projectDir) {
60
82
  //#endregion
61
83
  export { startGenerateSubgraph };
62
84
 
63
- //# sourceMappingURL=generate-subgraph-CrHbYK91.mjs.map
64
- //# debugId=2e0f1963-117b-5df1-a61a-61579e3ef622
85
+ //# sourceMappingURL=generate-subgraph-DJZCr0Tk.mjs.map
86
+ //# debugId=57f37708-e436-5415-9747-38ee27ce7f15
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-subgraph-DJZCr0Tk.mjs","sources":["../src/services/generate-subgraph.ts"],"sourcesContent":["import {\n detectFeatures,\n generateAllSubgraphs,\n generateSubgraph,\n generateSubgraphDir,\n syncFeatureDependencies,\n} from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n subgraphDirStyle,\n type SubgraphStyle,\n} from \"@powerhousedao/codegen/utils\";\nimport {\n extractSubgraphDocuments,\n findSubgraphNameConflict,\n generateSubgraphFromDocument,\n getDocument,\n saveSpec,\n} from \"@powerhousedao/vetra/codegen\";\nimport type { SubgraphModuleDocument } from \"@powerhousedao/vetra/document-models/subgraph-module\";\nimport { kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateSubgraphArgs } from \"../types.js\";\nimport { installAddedDependencies } from \"../utils/install-added-dependencies.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\n\nconst INDEX_FILE_EXPECTATION = {\n \"schema-first\": \"a class extending BaseSubgraph with a string literal `name`\",\n \"code-first\":\n \"a class extending Subgraph with a string literal `static subgraphName`\",\n} satisfies Record<SubgraphStyle, string>;\n\nasync function assertSubgraphNameFree(projectDir: string, name: string) {\n const conflict = await findSubgraphNameConflict(projectDir, name);\n if (conflict) throw new Error(conflict);\n}\n\n/** The notice for `--code-first` on an existing schema-first subgraph, which\n * is then left unchanged. */\nfunction codeFirstOnSchemaFirst(\n args: GenerateSubgraphArgs,\n projectDir: string,\n name: string,\n): string | undefined {\n if (!args.codeFirst) return undefined;\n const subgraphsDir = join(projectDir, \"subgraphs\");\n const dirName = kebabCase(name);\n if (\n !existsSync(join(subgraphsDir, dirName, \"index.ts\")) ||\n subgraphDirStyle(subgraphsDir, dirName) !== \"schema-first\"\n )\n return undefined;\n return `subgraphs/${dirName} is schema-first; --code-first only applies to new subgraphs. To convert it, run ph migrate --subgraph ${dirName}.`;\n}\n\nexport async function startGenerateSubgraph(\n args: GenerateSubgraphArgs,\n projectDir: string,\n) {\n const { name, document, dir, all, extract, debug } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n if (extract) {\n const docs = extractSubgraphDocuments(project);\n if (docs.length === 0) {\n console.log(\"No subgraphs found in subgraphs/.\");\n }\n for (const doc of docs) {\n const path = await saveSpec(doc, projectDir);\n console.log(`Wrote ${path}`);\n }\n return;\n }\n const report: string[] = [];\n if (all) {\n const { subgraphNames, unreadableDirs } =\n await generateAllSubgraphs(project);\n if (subgraphNames.length === 0 && unreadableDirs.length === 0) {\n report.push(\"No subgraphs found in subgraphs/.\");\n }\n for (const subgraphName of subgraphNames) {\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION[subgraphDirStyle(join(projectDir, \"subgraphs\"), dirName)]}. Kept the manifest's subgraphs.`,\n );\n }\n } else if (document) {\n const doc = (await getDocument(document)) as SubgraphModuleDocument;\n const notice = codeFirstOnSchemaFirst(\n args,\n projectDir,\n doc.state.global.name,\n );\n if (notice) {\n console.log(notice);\n return;\n }\n await assertSubgraphNameFree(projectDir, doc.state.global.name);\n await generateSubgraphFromDocument(doc, project, {\n codeFirst: args.codeFirst,\n });\n } else if (name) {\n const notice = codeFirstOnSchemaFirst(args, projectDir, name);\n if (notice) {\n console.log(notice);\n return;\n }\n await assertSubgraphNameFree(projectDir, name);\n await generateSubgraph(name, project, { codeFirst: args.codeFirst });\n } else if (dir) {\n const dirName = resolveModuleDirName(\n projectDir,\n \"subgraphs\",\n dir,\n \"my-subgraph\",\n );\n if (!existsSync(join(projectDir, \"subgraphs\", dirName, \"index.ts\"))) {\n throw new Error(`subgraphs/${dirName} has no index.ts.`);\n }\n const { subgraphName, style } = await generateSubgraphDir(dirName, project);\n if (!subgraphName) {\n throw new Error(\n `Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION[style]}.`,\n );\n }\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n } else {\n console.log(\n \"Please specify one of `name`, `document`, `dir`, `all`, or `extract`.\",\n );\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n await warnSubgraphTypeConflicts(projectDir);\n const added = await syncFeatureDependencies(\n detectFeatures(projectDir),\n projectDir,\n );\n await installAddedDependencies(added, projectDir, args.skipInstall);\n}\n"],"names":["installAddedDependencies"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,yBAAyB;CAC7B,gBAAgB;CAChB,cACE;AACJ;AAEA,eAAe,uBAAuB,YAAoB,MAAc;CACtE,MAAM,WAAW,MAAM,yBAAyB,YAAY,IAAI;CAChE,IAAI,UAAU,MAAM,IAAI,MAAM,QAAQ;AACxC;;;AAIA,SAAS,uBACP,MACA,YACA,MACoB;CACpB,IAAI,CAAC,KAAK,WAAW,OAAO,KAAA;CAC5B,MAAM,eAAe,KAAK,YAAY,WAAW;CACjD,MAAM,UAAU,UAAU,IAAI;CAC9B,IACE,CAAC,WAAW,KAAK,cAAc,SAAS,UAAU,CAAC,KACnD,iBAAiB,cAAc,OAAO,MAAM,gBAE5C,OAAO,KAAA;CACT,OAAO,aAAa,QAAQ,yGAAyG,QAAQ;AAC/I;AAEA,eAAsB,sBACpB,MACA,YACA;CACA,MAAM,EAAE,MAAM,UAAU,KAAK,KAAK,SAAS,UAAU;CACrD,IAAI,OACF,QAAQ,IAAI,EAAE,KAAK,CAAC;CAEtB,MAAM,UAAU,oBAAoB,UAAU;CAC9C,IAAI,SAAS;EACX,MAAM,OAAO,yBAAyB,OAAO;EAC7C,IAAI,KAAK,WAAW,GAClB,QAAQ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AC1E,IAAI,CAAC,cACH,MAAM,IAAI,MACR,4BAA4B,QAAQ,sBAAsB,uBAAuB,OAAO,EAC1F;EAEF,OAAO,KAAK,yBAAyB,aAAa,EAAE;CACtD,OAAO;EACL,QAAQ,IACN,uEACF;EACA;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ,QACjB,QAAQ,IAAI,IAAI;CAElB,MAAM,0BAA0B,UAAU;CAC1C,MAAM,QAAQ,MAAM,wBAClB,eAAe,UAAU,GACzB,UACF;CACA,MAAMA,2BAAyB,OAAO,YAAY,KAAK,WAAW;AACpE","debug_id":"57f37708-e436-5415-9747-38ee27ce7f15"}
@@ -1,11 +1,11 @@
1
1
  //#region src/get-version.ts
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f25cfbf6-537a-5280-a00b-ad31759a15ba")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="edd65af7-d4f7-5209-8d50-72b4026d771a")}catch(e){}}();
4
4
  function getVersion() {
5
- return "6.2.3-dev.101";
5
+ return "6.2.3-dev.102";
6
6
  }
7
7
  //#endregion
8
8
  export { getVersion as t };
9
9
 
10
- //# sourceMappingURL=get-version-DUG29IeG.mjs.map
11
- //# debugId=f25cfbf6-537a-5280-a00b-ad31759a15ba
10
+ //# sourceMappingURL=get-version-CeMBGufv.mjs.map
11
+ //# debugId=edd65af7-d4f7-5209-8d50-72b4026d771a
@@ -1 +1 @@
1
- {"version":3,"file":"get-version-DUG29IeG.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"f25cfbf6-537a-5280-a00b-ad31759a15ba"}
1
+ {"version":3,"file":"get-version-CeMBGufv.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"edd65af7-d4f7-5209-8d50-72b4026d771a"}
@@ -1,8 +1,9 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="314382e5-15cc-5ea1-b698-6dd4459c7e51")}catch(e){}}();
3
- import { n as processStreams, r as runModelCommand } from "./run-DEKE4MJY.mjs";
4
- import { n as renderInspectionReport } from "./render-BO-Nwn2H.mjs";
5
- import { inspectProjectDefinitions } from "document-model/tooling";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b5cb1a95-360f-5775-943b-344d627fa2c2")}catch(e){}}();
3
+ import { t as readProjectSubgraphs } from "./subgraphs-7OYWwP-C.mjs";
4
+ import { n as processStreams, r as runModelCommand } from "./run--de_-WAz.mjs";
5
+ import { n as renderInspectionReport } from "./render-SVfj3m8A.mjs";
6
+ import { inspectProjectDefinitions, withSubgraphInspection } from "document-model/tooling";
6
7
  //#region src/services/model/inspect.ts
7
8
  /** `<documentType>@<version>`; a document type may itself contain `@`. */
8
9
  function parseModelSelector(selector) {
@@ -35,12 +36,17 @@ async function runModelInspect(args, options = {}) {
35
36
  return await runModelCommand({
36
37
  name: "ph model inspect",
37
38
  json: args.json,
38
- read: (project) => inspectProjectDefinitions(project, selection === void 0 ? {} : { selection }),
39
+ read: async (project, modules) => {
40
+ if (selection !== void 0) return inspectProjectDefinitions(project, { selection });
41
+ const report = inspectProjectDefinitions(project);
42
+ const subgraphs = await readProjectSubgraphs(project, modules);
43
+ return subgraphs === void 0 ? report : withSubgraphInspection(project, report, subgraphs.input);
44
+ },
39
45
  render: renderInspectionReport
40
46
  }, options);
41
47
  }
42
48
  //#endregion
43
49
  export { runModelInspect };
44
50
 
45
- //# sourceMappingURL=inspect-BpVHe9vz.mjs.map
46
- //# debugId=314382e5-15cc-5ea1-b698-6dd4459c7e51
51
+ //# sourceMappingURL=inspect-CulIpVsF.mjs.map
52
+ //# debugId=b5cb1a95-360f-5775-943b-344d627fa2c2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspect-CulIpVsF.mjs","sources":["../src/services/model/inspect.ts"],"sourcesContent":["import {\n inspectProjectDefinitions,\n withSubgraphInspection,\n} from \"document-model/tooling\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderInspectionReport } from \"./render.js\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\n\ntype Selection = { readonly documentType: string; readonly version: number };\n\n/** `<documentType>@<version>`; a document type may itself contain `@`. */\nfunction parseModelSelector(\n selector: string,\n):\n | { readonly ok: true; readonly selection: Selection }\n | { readonly ok: false; readonly message: string } {\n const at = selector.lastIndexOf(\"@\");\n const documentType = at === -1 ? \"\" : selector.slice(0, at);\n const version = at === -1 ? \"\" : selector.slice(at + 1);\n if (\n documentType === \"\" ||\n !/^[1-9][0-9]*$/.test(version) ||\n !Number.isSafeInteger(Number(version))\n ) {\n return {\n ok: false,\n message: `Expected <documentType>@<version> with a positive whole version, such as acme/invoice@1. Received ${JSON.stringify(selector)}.`,\n };\n }\n return { ok: true, selection: { documentType, version: Number(version) } };\n}\n\n/** `ph model inspect [<documentType>@<version>]`. Returns the exit code. */\nexport async function runModelInspect(\n args: { readonly selector?: string; readonly json: boolean },\n options: ModelRunOptions = {},\n): Promise<number> {\n let selection: Selection | undefined;\n if (args.selector !== undefined) {\n const parsed = parseModelSelector(args.selector);\n if (!parsed.ok) {\n (options.streams ?? processStreams).err(`${parsed.message}\\n`);\n return 2;\n }\n selection = parsed.selection;\n }\n return await runModelCommand(\n {\n name: \"ph model inspect\",\n json: args.json,\n read: async (project, modules) => {\n if (selection !== undefined) {\n return inspectProjectDefinitions(project, { selection });\n }\n const report = inspectProjectDefinitions(project);\n const subgraphs = await readProjectSubgraphs(project, modules);\n return subgraphs === undefined\n ? report\n : withSubgraphInspection(project, report, subgraphs.input);\n },\n render: renderInspectionReport,\n },\n options,\n );\n}\n"],"names":[],"mappings":";;;;;;;;AAeA,SAAS,mBACP,UAGmD;CACnD,MAAM,KAAK,SAAS,YAAY,GAAG;CACnC,MAAM,eAAe,OAAO,KAAK,KAAK,SAAS,MAAM,GAAG,EAAE;CAC1D,MAAM,UAAU,OAAO,KAAK,KAAK,SAAS,MAAM,KAAK,CAAC;CACtD,IACE,iBAAiB,MACjB,CAAC,gBAAgB,KAAK,OAAO,KAC7B,CAAC,OAAO,cAAc,OAAO,OAAO,CAAC,GAErC,OAAO;EACL,IAAI;EACJ,SAAS,qGAAqG,KAAK,UAAU,QAAQ,EAAE;CACzI;CAEF,OAAO;EAAE,IAAI;EAAM,WAAW;GAAE;GAAc,SAAS,OAAO,OAAO;EAAE;CAAE;AAC3E;;AAGA,eAAsB,gBACpB,MACA,UAA2B,CAAC,GACX;CACjB,IAAI;CACJ,IAAI,KAAK,aAAa,KAAA,GAAW;EAC/B,MAAM,SAAS,mBAAmB,KAAK,QAAQ;EAC/C,IAAI,CAAC,OAAO,IAAI;GACd,CAAC,QAAQ,WAAW,eAAA,CAAgB,IAAI,GAAG,OAAO,QAAQ,GAAG;GAC7D,OAAO;EACT;EACA,YAAY,OAAO;CACrB;CACA,OAAO,MAAM,gBACX;EACE,MAAM;EACN,MAAM,KAAK;EACX,MAAM,OAAO,SAAS,YAAY;GAChC,IAAI,cAAc,KAAA,GAChB,OAAO,0BAA0B,SAAS,EAAE,UAAU,CAAC;GAEzD,MAAM,SAAS,0BAA0B,OAAO;GAChD,MAAM,YAAY,MAAM,qBAAqB,SAAS,OAAO;GAC7D,OAAO,cAAc,KAAA,IACjB,SACA,uBAAuB,SAAS,QAAQ,UAAU,KAAK;EAC7D;EACA,QAAQ;CACV,GACA,OACF;AACF","debug_id":"b5cb1a95-360f-5775-943b-344d627fa2c2"}
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="70850238-7246-5695-b3bf-6f1e3897aeca")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-DUG29IeG.mjs";
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e0dd0082-b017-5341-87a7-e23f09acf816")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-CeMBGufv.mjs";
4
4
  import { i as restartVetra, l as readVetraRuntime, n as currentPhCliVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launch-DQDZxGTV.mjs";
5
5
  import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
6
6
  import fs from "node:fs";
@@ -258,5 +258,5 @@ async function startMcpLauncher(options) {
258
258
  //#endregion
259
259
  export { startMcpLauncher };
260
260
 
261
- //# sourceMappingURL=mcp-DEBeM-ZV.mjs.map
262
- //# debugId=70850238-7246-5695-b3bf-6f1e3897aeca
261
+ //# sourceMappingURL=mcp-HSikd5iv.mjs.map
262
+ //# debugId=e0dd0082-b017-5341-87a7-e23f09acf816
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-DEBeM-ZV.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ,OAAO,KAAA;CAChC,aAAa;EACX,MAAM,IAAI,MAAM,8CAA8C;CAChE;AACF,EACF,CAAC;;AAGD,eAAe,yBAA0C;CACvD,MAAM,SAAS,MAAM,aAAa,EAAE,QAAQ,kBAAkB,CAAC;CAC/D,MAAM,CAAC,YAAY,cAAc,kBAAkB,iBAAiB;CACpE,MAAM,OAAO,QAAQ,UAAU;CAC/B,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAU,SAAS,WAAW;CAAE,CAAC;CACnE,MAAM,OAAO,QAAQ,UAAU;CAC/B,OAAO;AACT;AAEA,SAAS,UAAU,SAAiC;CAClD,OAAO;EAAE,SAAS;EAAM,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;CAAE;AACrE;;AAGA,SAAS,kBAAkB,OAAyB;CAClD,IAAI,iBAAiB,qBACnB,OAAO,MAAM,SAAS,OAAO,MAAM,SAAS;CAE9C,KAAK,IAAI,IA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D,MAAM,sBAAsB,QAAQ,MAAM,CAC5C;CACA,OAAO,kBAAkB,4BAA4B,YACnD,MAAM,aAAa,QAAQ,MAAM,CACnC;CACA,OAAO,kBAAkB,uBAAuB,OAAO,SAAS,UAAU;EAExE,MAAM,QAAQ,QAAQ,OAAO,OAAO;EACpC,IAAI,WAAW;EACf,MAAM,cAAwB,YAAY;GACxC,IAAI,UAAU,KAAA,GAAW;IACvB,QAAQ,MAAM,YAAY,SAAS;IACnC;GACF;GACA,MACG,iBAAiB;IAChB,QAAQ;IACR,QAAQ;KAAE,eAAe;KAAO,UAAU,EAAE;KAAU;IAAQ;GAChE,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EACnB;EACA,IAAI;GACF,IAAI,QAAQ,OAAO,SAAA,gBAA6B;IAC9C,MAAM,OAAO,UAAU,MAAM,SAAS,QAAQ,UAAU,CAAC;IACzD,OAAO;KACL,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"70850238-7246-5695-b3bf-6f1e3897aeca"}
1
+ {"version":3,"file":"mcp-HSikd5iv.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ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IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"e0dd0082-b017-5341-87a7-e23f09acf816"}
@@ -0,0 +1,214 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1ae0747c-986c-5046-bc12-b3248019d612")}catch(e){}}();
3
+ import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { migrateSubgraph, sortedSchemaText } from "@powerhousedao/codegen";
6
+ import { readSubgraphDefinitions } from "document-model/tooling";
7
+ import { projectSubgraphGraphQL } from "document-model";
8
+ import { ViteTypeScriptSourceImportAdapter, subgraphDirStyles, uncachedDefinitionSourceRevision } from "@powerhousedao/codegen/utils";
9
+ //#region src/services/migrate-subgraphs.ts
10
+ /** A module that hangs on a top-level await must not hang `ph migrate`. */
11
+ const IMPORT_TIMEOUT_MS = 6e4;
12
+ const SCALARS_ENTRY = "scalars/index.ts";
13
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|graphql)$/;
14
+ /**
15
+ * `ph migrate --subgraphs`: converts schema-first subgraphs into code-first
16
+ * ones. Each written directory is loaded as `ph model check` loads it and
17
+ * must serve the schema it served before; otherwise its files are restored.
18
+ * Without named directories, a directory whose `index.ts` holds no class is
19
+ * skipped. Returns the exit code: 0 when every requested subgraph converted
20
+ * or was already code-first, 1 otherwise.
21
+ */
22
+ async function migrateSubgraphs(options) {
23
+ const out = options.out ?? ((text) => void process.stdout.write(text));
24
+ const { projectDir, dryRun } = options;
25
+ const styles = new Map(subgraphDirStyles(join(projectDir, "subgraphs")).map(({ dirName, style }) => [dirName, style]));
26
+ let failed = false;
27
+ let schemaFirst = 0;
28
+ const named = options.dirs.length > 0;
29
+ const requested = named ? options.dirs : [...styles.keys()];
30
+ const converted = [];
31
+ const importer = new ViteTypeScriptSourceImportAdapter();
32
+ const revision = uncachedDefinitionSourceRevision();
33
+ try {
34
+ for (const dirName of requested) {
35
+ const label = `subgraphs/${dirName}`;
36
+ const style = styles.get(dirName);
37
+ if (style === void 0) {
38
+ out(`${label}: not found. Name a directory of subgraphs/ that has an index.ts.\n`);
39
+ failed = true;
40
+ continue;
41
+ }
42
+ if (style === "code-first") {
43
+ out(`${label}: already code-first\n`);
44
+ continue;
45
+ }
46
+ const originals = readDirectory(projectDir, dirName);
47
+ const migration = await migrateSubgraph({
48
+ dirName,
49
+ files: new Map([...originals].map(([path, bytes]) => [path, bytes.toString("utf8")]))
50
+ });
51
+ if (migration.kind === "no-subgraph-class" && !named) {
52
+ out(`${label}: no subgraph class, skipped\n`);
53
+ continue;
54
+ }
55
+ schemaFirst++;
56
+ if (migration.kind !== "converted") {
57
+ out(refusalText(label, migration));
58
+ failed = true;
59
+ continue;
60
+ }
61
+ if (dryRun) {
62
+ out(`${label}: would convert ${migration.className} to code-first\n`);
63
+ for (const file of migration.files) out(unifiedDiff(file));
64
+ continue;
65
+ }
66
+ writeFiles(projectDir, migration.files);
67
+ const verification = await verify(projectDir, migration, importer, revision);
68
+ if (!verification.ok) {
69
+ restoreFiles(projectDir, migration.files, originals);
70
+ out(`${label}: not converted; its files are restored. ${verification.reason}\n`);
71
+ failed = true;
72
+ continue;
73
+ }
74
+ converted.push(dirName);
75
+ out(`${label}: converted ${migration.className} to code-first; it serves the same schema\n`);
76
+ if (migration.sdlFile.endsWith("/schema.graphql")) out(`${migration.sdlFile} is no longer used; the schema is now in ${label}/schema.ts. It was kept, and you can delete it.\n`);
77
+ }
78
+ } finally {
79
+ await importer.disposeRevision();
80
+ }
81
+ if (!named && schemaFirst === 0) out("No schema-first subgraphs to convert.\n");
82
+ return failed ? 1 : 0;
83
+ }
84
+ /** The directory's files and `scalars/index.ts`, by project-relative path. */
85
+ function readDirectory(projectDir, dirName) {
86
+ const files = /* @__PURE__ */ new Map();
87
+ const dir = join(projectDir, "subgraphs", dirName);
88
+ for (const entry of readdirSync(dir, {
89
+ recursive: true,
90
+ withFileTypes: true
91
+ })) {
92
+ if (!entry.isFile() || !SOURCE_FILE.test(entry.name)) continue;
93
+ const path = join(entry.parentPath, entry.name);
94
+ files.set(path.slice(projectDir.length + 1).replaceAll("\\", "/"), readFileSync(path));
95
+ }
96
+ const scalars = join(projectDir, SCALARS_ENTRY);
97
+ if (existsSync(scalars)) files.set(SCALARS_ENTRY, readFileSync(scalars));
98
+ return files;
99
+ }
100
+ function writeFiles(projectDir, files) {
101
+ for (const file of files) writeFileSync(join(projectDir, file.path), file.after);
102
+ }
103
+ function restoreFiles(projectDir, files, originals) {
104
+ for (const file of files) {
105
+ const original = originals.get(file.path);
106
+ if (original === void 0) rmSync(join(projectDir, file.path), { force: true });
107
+ else writeFileSync(join(projectDir, file.path), original);
108
+ }
109
+ }
110
+ async function withTimeout(work, timeoutMs) {
111
+ let timer;
112
+ const timeout = new Promise((_, reject) => {
113
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`it did not finish loading within ${timeoutMs / 1e3} seconds`)), timeoutMs);
114
+ timer.unref();
115
+ });
116
+ try {
117
+ return await Promise.race([work, timeout]);
118
+ } finally {
119
+ clearTimeout(timer);
120
+ }
121
+ }
122
+ /** Loads the written class without constructing it and compares the schema it serves. */
123
+ async function verify(projectDir, migration, importer, revision) {
124
+ const specifier = `./subgraphs/${migration.dirName}/index.ts`;
125
+ let namespace;
126
+ try {
127
+ namespace = await withTimeout(importer.importModule({
128
+ packageRoot: projectDir,
129
+ specifier,
130
+ packageRevision: revision
131
+ }), IMPORT_TIMEOUT_MS);
132
+ } catch (error) {
133
+ return {
134
+ ok: false,
135
+ reason: `The converted module does not load: ${(error instanceof Error ? error.message : String(error)).replaceAll(projectDir, ".")}`
136
+ };
137
+ }
138
+ const { subgraphs, diagnostics } = readSubgraphDefinitions(namespace, { specifier });
139
+ const errors = diagnostics.filter(({ severity }) => severity === "error");
140
+ if (errors.length > 0) return {
141
+ ok: false,
142
+ reason: `The converted subgraph does not compile:\n${errors.map(({ message, repair }) => ` ${message} ${repair}`).join("\n")}`
143
+ };
144
+ const subgraph = subgraphs.find(({ name }) => name === migration.subgraphName);
145
+ if (subgraph === void 0) return {
146
+ ok: false,
147
+ reason: `${specifier} exports no code-first subgraph named ${migration.subgraphName}.`
148
+ };
149
+ const served = sortedSchemaText(projectSubgraphGraphQL(subgraph.definition));
150
+ if (served === migration.sdl) return { ok: true };
151
+ return {
152
+ ok: false,
153
+ reason: `The converted subgraph serves a different schema:\n${unifiedDiff({
154
+ path: "schema",
155
+ before: migration.sdl,
156
+ after: served
157
+ })}`
158
+ };
159
+ }
160
+ function refusalText(label, migration) {
161
+ return `${label}: not converted\n${migration.refusals.map(({ file, line, reason, repair }) => ` ${file}:${line}: ${reason}\n ${repair}\n`).join("")}`;
162
+ }
163
+ /** The line edits from `before` to `after`, by longest common subsequence. */
164
+ function lineEdits(before, after) {
165
+ const common = Array.from({ length: before.length + 1 }, () => new Array(after.length + 1).fill(0));
166
+ for (let i = before.length - 1; i >= 0; i--) for (let j = after.length - 1; j >= 0; j--) common[i][j] = before[i] === after[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
167
+ const lines = [];
168
+ let i = 0;
169
+ let j = 0;
170
+ while (i < before.length || j < after.length) if (i < before.length && j < after.length && before[i] === after[j]) {
171
+ lines.push({
172
+ kind: " ",
173
+ text: before[i++]
174
+ });
175
+ j++;
176
+ } else if (i < before.length && (j === after.length || common[i + 1][j] >= common[i][j + 1])) lines.push({
177
+ kind: "-",
178
+ text: before[i++]
179
+ });
180
+ else lines.push({
181
+ kind: "+",
182
+ text: after[j++]
183
+ });
184
+ return lines;
185
+ }
186
+ const CONTEXT = 3;
187
+ /** A unified diff of one file; a new file diffs against /dev/null. */
188
+ function unifiedDiff(file) {
189
+ const split = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
190
+ const lines = lineEdits(split(file.before ?? ""), split(file.after));
191
+ const changed = lines.flatMap((line, index) => line.kind === " " ? [] : [index]);
192
+ if (changed.length === 0) return "";
193
+ const hunks = [];
194
+ for (const index of changed) {
195
+ const start = Math.max(0, index - CONTEXT);
196
+ const end = Math.min(lines.length, index + CONTEXT + 1);
197
+ const last = hunks.at(-1);
198
+ if (last !== void 0 && start <= last[1]) last[1] = end;
199
+ else hunks.push([start, end]);
200
+ }
201
+ return `--- ${file.before === null ? "/dev/null" : `a/${file.path}`}\n+++ b/${file.path}\n` + hunks.map(([start, end]) => {
202
+ const lineBefore = (kind) => lines.slice(0, start).filter((line) => line.kind !== kind).length;
203
+ const slice = lines.slice(start, end);
204
+ const count = (kind) => slice.filter((line) => line.kind !== kind).length;
205
+ const oldCount = count("+");
206
+ const newCount = count("-");
207
+ return `@@ -${oldCount === 0 ? lineBefore("+") : lineBefore("+") + 1},${oldCount} +${newCount === 0 ? lineBefore("-") : lineBefore("-") + 1},${newCount} @@\n${slice.map((line) => `${line.kind}${line.text}`).join("\n")}\n`;
208
+ }).join("");
209
+ }
210
+ //#endregion
211
+ export { migrateSubgraphs };
212
+
213
+ //# sourceMappingURL=migrate-subgraphs-Cm7DDcDd.mjs.map
214
+ //# debugId=1ae0747c-986c-5046-bc12-b3248019d612
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate-subgraphs-Cm7DDcDd.mjs","sources":["../src/services/migrate-subgraphs.ts"],"sourcesContent":["import {\n migrateSubgraph,\n sortedSchemaText,\n type SubgraphMigration,\n type SubgraphMigrationFile,\n} from \"@powerhousedao/codegen\";\nimport {\n subgraphDirStyles,\n uncachedDefinitionSourceRevision,\n ViteTypeScriptSourceImportAdapter,\n} from \"@powerhousedao/codegen/utils\";\nimport { projectSubgraphGraphQL } from \"document-model\";\nimport { readSubgraphDefinitions } from \"document-model/tooling\";\nimport type { DocumentNode } from \"graphql\";\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** A module that hangs on a top-level await must not hang `ph migrate`. */\nconst IMPORT_TIMEOUT_MS = 60_000;\nconst SCALARS_ENTRY = \"scalars/index.ts\";\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?|graphql)$/;\n\nexport type MigrateSubgraphsOptions = {\n readonly projectDir: string;\n /** The `subgraphs/` directories to convert; empty converts every schema-first one. */\n readonly dirs: readonly string[];\n readonly dryRun: boolean;\n readonly out?: (text: string) => void;\n};\n\ntype Verification =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * `ph migrate --subgraphs`: converts schema-first subgraphs into code-first\n * ones. Each written directory is loaded as `ph model check` loads it and\n * must serve the schema it served before; otherwise its files are restored.\n * Without named directories, a directory whose `index.ts` holds no class is\n * skipped. Returns the exit code: 0 when every requested subgraph converted\n * or was already code-first, 1 otherwise.\n */\nexport async function migrateSubgraphs(\n options: MigrateSubgraphsOptions,\n): Promise<0 | 1> {\n const out =\n options.out ?? ((text: string) => void process.stdout.write(text));\n const { projectDir, dryRun } = options;\n const styles = new Map(\n subgraphDirStyles(join(projectDir, \"subgraphs\")).map(\n ({ dirName, style }) => [dirName, style] as const,\n ),\n );\n let failed = false;\n let schemaFirst = 0;\n const named = options.dirs.length > 0;\n const requested = named ? options.dirs : [...styles.keys()];\n const converted: string[] = [];\n const importer = new ViteTypeScriptSourceImportAdapter();\n const revision = uncachedDefinitionSourceRevision();\n try {\n for (const dirName of requested) {\n const label = `subgraphs/${dirName}`;\n const style = styles.get(dirName);\n if (style === undefined) {\n out(\n `${label}: not found. Name a directory of subgraphs/ that has an index.ts.\\n`,\n );\n failed = true;\n continue;\n }\n if (style === \"code-first\") {\n out(`${label}: already code-first\\n`);\n continue;\n }\n const originals = readDirectory(projectDir, dirName);\n const migration = await migrateSubgraph({\n dirName,\n files: new Map(\n [...originals].map(([path, bytes]) => [path, bytes.toString(\"utf8\")]),\n ),\n });\n if (migration.kind === \"no-subgraph-class\" && !named) {\n out(`${label}: no subgraph class, skipped\\n`);\n continue;\n }\n schemaFirst++;\n if (migration.kind !== \"converted\") {\n out(refusalText(label, migration));\n failed = true;\n continue;\n }\n if (dryRun) {\n out(`${label}: would convert ${migration.className} to code-first\\n`);\n for (const file of migration.files) out(unifiedDiff(file));\n continue;\n }\n writeFiles(projectDir, migration.files);\n const verification = await verify(\n projectDir,\n migration,\n importer,\n revision,\n );\n if (!verification.ok) {\n restoreFiles(projectDir, migration.files, originals);\n out(\n `${label}: not converted; its files are restored. ${verification.reason}\\n`,\n );\n failed = true;\n continue;\n }\n converted.push(dirName);\n out(\n `${label}: converted ${migration.className} to code-first; it serves the same schema\\n`,\n );\n if (migration.sdlFile.endsWith(\"/schema.graphql\")) {\n out(\n `${migration.sdlFile} is no longer used; the schema is now in ${label}/schema.ts. It was kept, and you can delete it.\\n`,\n );\n }\n }\n } finally {\n await importer.disposeRevision();\n }\n if (!named && schemaFirst === 0) {\n out(\"No schema-first subgraphs to convert.\\n\");\n }\n return failed ? 1 : 0;\n}\n\n/** The directory's files and `scalars/index.ts`, by project-relative path. */\nfunction readDirectory(\n projectDir: string,\n dirName: string,\n): ReadonlyMap<string, Buffer> {\n const files = new Map<string, Buffer>();\n const dir = join(projectDir, \"subgraphs\", dirName);\n for (const entry of readdirSync(dir, {\n recursive: true,\n withFileTypes: true,\n })) {\n if (!entry.isFile() || !SOURCE_FILE.test(entry.name)) continue;\n const path = join(entry.parentPath, entry.name);\n files.set(\n path.slice(projectDir.length + 1).replaceAll(\"\\\\\", \"/\"),\n readFileSync(path),\n );\n }\n const scalars = join(projectDir, SCALARS_ENTRY);\n if (existsSync(scalars)) files.set(SCALARS_ENTRY, readFileSync(scalars));\n return files;\n}\n\nfunction writeFiles(\n projectDir: string,\n files: readonly SubgraphMigrationFile[],\n) {\n for (const file of files)\n writeFileSync(join(projectDir, file.path), file.after);\n}\n\nfunction restoreFiles(\n projectDir: string,\n files: readonly SubgraphMigrationFile[],\n originals: ReadonlyMap<string, Buffer>,\n) {\n for (const file of files) {\n const original = originals.get(file.path);\n if (original === undefined)\n rmSync(join(projectDir, file.path), { force: true });\n else writeFileSync(join(projectDir, file.path), original);\n }\n}\n\nasync function withTimeout<T>(work: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `it did not finish loading within ${timeoutMs / 1000} seconds`,\n ),\n ),\n timeoutMs,\n );\n timer.unref();\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Loads the written class without constructing it and compares the schema it serves. */\nasync function verify(\n projectDir: string,\n migration: Extract<SubgraphMigration, { kind: \"converted\" }>,\n importer: ViteTypeScriptSourceImportAdapter,\n revision: ReturnType<typeof uncachedDefinitionSourceRevision>,\n): Promise<Verification> {\n const specifier = `./subgraphs/${migration.dirName}/index.ts` as const;\n let namespace: Readonly<Record<string, unknown>>;\n try {\n namespace = await withTimeout(\n importer.importModule({\n packageRoot: projectDir,\n specifier,\n packageRevision: revision,\n }),\n IMPORT_TIMEOUT_MS,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n reason: `The converted module does not load: ${message.replaceAll(projectDir, \".\")}`,\n };\n }\n const { subgraphs, diagnostics } = readSubgraphDefinitions(namespace, {\n specifier,\n });\n const errors = diagnostics.filter(({ severity }) => severity === \"error\");\n if (errors.length > 0) {\n return {\n ok: false,\n reason: `The converted subgraph does not compile:\\n${errors.map(({ message, repair }) => ` ${message} ${repair}`).join(\"\\n\")}`,\n };\n }\n const subgraph = subgraphs.find(\n ({ name }) => name === migration.subgraphName,\n );\n if (subgraph === undefined) {\n return {\n ok: false,\n reason: `${specifier} exports no code-first subgraph named ${migration.subgraphName}.`,\n };\n }\n const served = sortedSchemaText(\n projectSubgraphGraphQL(subgraph.definition) as unknown as DocumentNode,\n );\n if (served === migration.sdl) return { ok: true };\n return {\n ok: false,\n reason: `The converted subgraph serves a different schema:\\n${unifiedDiff({\n path: \"schema\",\n before: migration.sdl,\n after: served,\n })}`,\n };\n}\n\nfunction refusalText(\n label: string,\n migration: Extract<\n SubgraphMigration,\n { kind: \"refused\" | \"no-subgraph-class\" }\n >,\n): string {\n return `${label}: not converted\\n${migration.refusals\n .map(\n ({ file, line, reason, repair }) =>\n ` ${file}:${line}: ${reason}\\n ${repair}\\n`,\n )\n .join(\"\")}`;\n}\n\ntype Line = { readonly kind: \" \" | \"-\" | \"+\"; readonly text: string };\n\n/** The line edits from `before` to `after`, by longest common subsequence. */\nfunction lineEdits(\n before: readonly string[],\n after: readonly string[],\n): Line[] {\n const common: number[][] = Array.from({ length: before.length + 1 }, () =>\n new Array<number>(after.length + 1).fill(0),\n );\n for (let i = before.length - 1; i >= 0; i--) {\n for (let j = after.length - 1; j >= 0; j--) {\n common[i][j] =\n before[i] === after[j]\n ? common[i + 1][j + 1] + 1\n : Math.max(common[i + 1][j], common[i][j + 1]);\n }\n }\n const lines: Line[] = [];\n let i = 0;\n let j = 0;\n while (i < before.length || j < after.length) {\n if (i < before.length && j < after.length && before[i] === after[j]) {\n lines.push({ kind: \" \", text: before[i++] });\n j++;\n } else if (\n i < before.length &&\n (j === after.length || common[i + 1][j] >= common[i][j + 1])\n ) {\n lines.push({ kind: \"-\", text: before[i++] });\n } else {\n lines.push({ kind: \"+\", text: after[j++] });\n }\n }\n return lines;\n}\n\nconst CONTEXT = 3;\n\n/** A unified diff of one file; a new file diffs against /dev/null. */\nexport function unifiedDiff(file: {\n readonly path: string;\n readonly before: string | null;\n readonly after: string;\n}): string {\n const split = (text: string) =>\n text === \"\" ? [] : text.replace(/\\n$/, \"\").split(\"\\n\");\n const lines = lineEdits(split(file.before ?? \"\"), split(file.after));\n const changed = lines.flatMap((line, index) =>\n line.kind === \" \" ? [] : [index],\n );\n if (changed.length === 0) return \"\";\n const hunks: [number, number][] = [];\n for (const index of changed) {\n const start = Math.max(0, index - CONTEXT);\n const end = Math.min(lines.length, index + CONTEXT + 1);\n const last = hunks.at(-1);\n if (last !== undefined && start <= last[1]) last[1] = end;\n else hunks.push([start, end]);\n }\n const header = `--- ${file.before === null ? \"/dev/null\" : `a/${file.path}`}\\n+++ b/${file.path}\\n`;\n return (\n header +\n hunks\n .map(([start, end]) => {\n const lineBefore = (kind: Line[\"kind\"]) =>\n lines.slice(0, start).filter((line) => line.kind !== kind).length;\n const slice = lines.slice(start, end);\n const count = (kind: Line[\"kind\"]) =>\n slice.filter((line) => line.kind !== kind).length;\n const oldCount = count(\"+\");\n const newCount = count(\"-\");\n const oldStart = oldCount === 0 ? lineBefore(\"+\") : lineBefore(\"+\") + 1;\n const newStart = newCount === 0 ? lineBefore(\"-\") : lineBefore(\"-\") + 1;\n return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@\\n${slice\n .map((line) => `${line.kind}${line.text}`)\n .join(\"\\n\")}\\n`;\n })\n .join(\"\")\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AAwBA,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,cAAc;;;;;;;;;AAsBpB,eAAsB,iBACpB,SACgB;CAChB,MAAM,MACJ,QAAQ,SAAS,SAAiB,KAAK,QAAQ,OAAO,MAAM,IAAI;CAClE,MAAM,EAAE,YAAY,WAAW;CAC/B,MAAM,SAAS,IAAI,IACjB,kBAAkB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KAAK,MAAM,CAAC,CACzC,KAAK,IAAI,EAAE;CAChB,CAAC,CAAC,CACD,KAAK,EAAE;AAEd","debug_id":"1ae0747c-986c-5046-bc12-b3248019d612"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b019bb65-d519-5dd7-bf0e-4c90f1c91ce5")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="72241c79-c8a9-5678-bb08-4b16f4fb3810")}catch(e){}}();
3
3
  import { existsSync, statSync } from "node:fs";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  //#region src/utils/module-dir.ts
@@ -14,4 +14,4 @@ function resolveModuleDirName(projectDir, modulesDir, dir, example) {
14
14
  export { resolveModuleDirName as t };
15
15
 
16
16
  //# sourceMappingURL=module-dir-1avCXsBi.mjs.map
17
- //# debugId=b019bb65-d519-5dd7-bf0e-4c90f1c91ce5
17
+ //# debugId=72241c79-c8a9-5678-bb08-4b16f4fb3810