@powerhousedao/ph-cli 6.4.0-next.5 → 6.4.0-next.6

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 (39) hide show
  1. package/dist/{build-CBKlv5E3.mjs → build-CGnPJwut.mjs} +4 -4
  2. package/dist/{build-CBKlv5E3.mjs.map → build-CGnPJwut.mjs.map} +1 -1
  3. package/dist/build-mTLB2w-Q.mjs +4 -0
  4. package/dist/{check-DhFd9tO8.mjs → check-Ch1obo1o.mjs} +3 -3
  5. package/dist/{check-Cx_AeBQe.mjs → check-DQnWxQCS.mjs} +4 -4
  6. package/dist/{check-Cx_AeBQe.mjs.map → check-DQnWxQCS.mjs.map} +1 -1
  7. package/dist/cli.mjs +4 -4
  8. package/dist/{connect-build-DpGUrtct.mjs → connect-build-CQgSyKm1.mjs} +7 -9
  9. package/dist/connect-build-CQgSyKm1.mjs.map +1 -0
  10. package/dist/{connect-studio-BPZOcwUM.mjs → connect-studio-SH4U0Cpm.mjs} +4 -4
  11. package/dist/{connect-studio-BPZOcwUM.mjs.map → connect-studio-SH4U0Cpm.mjs.map} +1 -1
  12. package/dist/definitions-worker.mjs +1 -1
  13. package/dist/{get-version-CTP__ORu.mjs → get-version-Cz5WJkpH.mjs} +4 -4
  14. package/dist/{get-version-CTP__ORu.mjs.map → get-version-Cz5WJkpH.mjs.map} +1 -1
  15. package/dist/{mcp-gcG7SW9L.mjs → mcp-Cx2HhCsK.mjs} +4 -4
  16. package/dist/{mcp-gcG7SW9L.mjs.map → mcp-Cx2HhCsK.mjs.map} +1 -1
  17. package/dist/{migrate-BaWZhorc.mjs → migrate-BzPAS4zM.mjs} +4 -4
  18. package/dist/{migrate-BaWZhorc.mjs.map → migrate-BzPAS4zM.mjs.map} +1 -1
  19. package/dist/{migrate-document-models-DYmkJzq3.mjs → migrate-document-models-BcrQKkDB.mjs} +4 -4
  20. package/dist/{migrate-document-models-DYmkJzq3.mjs.map → migrate-document-models-BcrQKkDB.mjs.map} +1 -1
  21. package/dist/migrate-subgraphs-ChQdt6w7.mjs +4 -0
  22. package/dist/{migrate-subgraphs-BUgTeHcm.mjs → migrate-subgraphs-Dw5UFCQ3.mjs} +5 -5
  23. package/dist/{migrate-subgraphs-BUgTeHcm.mjs.map → migrate-subgraphs-Dw5UFCQ3.mjs.map} +1 -1
  24. package/dist/ph-cli-commands-BcDloXsM.mjs +4 -0
  25. package/dist/{ph-cli-commands-B5VkGW99.mjs → ph-cli-commands-CGR5p3vg.mjs} +11 -11
  26. package/dist/{ph-cli-commands-B5VkGW99.mjs.map → ph-cli-commands-CGR5p3vg.mjs.map} +1 -1
  27. package/dist/runners/connect.mjs +2 -2
  28. package/dist/runners/switchboard.mjs +1 -1
  29. package/dist/{verify-BLn76w09.mjs → verify-B3CKpYI8.mjs} +4 -4
  30. package/dist/{verify-BLn76w09.mjs.map → verify-B3CKpYI8.mjs.map} +1 -1
  31. package/dist/{vetra-gateway-D30pZgha.mjs → vetra-gateway-BZJEJiGT.mjs} +4 -4
  32. package/dist/{vetra-gateway-D30pZgha.mjs.map → vetra-gateway-BZJEJiGT.mjs.map} +1 -1
  33. package/dist/vetra-gateway-CeWIXaAl.mjs +4 -0
  34. package/package.json +17 -17
  35. package/dist/build-Dr1lnv4h.mjs +0 -4
  36. package/dist/connect-build-DpGUrtct.mjs.map +0 -1
  37. package/dist/migrate-subgraphs-ChhXynqd.mjs +0 -4
  38. package/dist/ph-cli-commands-CGXSo1wx.mjs +0 -4
  39. package/dist/vetra-gateway-DE5Hc0Fp.mjs +0 -4
@@ -0,0 +1,4 @@
1
+ import { t as runBuild } from "./build-CGnPJwut.mjs";
2
+ export { runBuild };
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]="2e83ca4e-08fe-52af-8a17-0eea48d3594a")}catch(e){}}();
4
+ //# debugId=2e83ca4e-08fe-52af-8a17-0eea48d3594a
@@ -1,4 +1,4 @@
1
- import { n as runModelCheck, t as definitionChecks } from "./check-Cx_AeBQe.mjs";
1
+ import { n as runModelCheck, t as definitionChecks } from "./check-DQnWxQCS.mjs";
2
2
  export { definitionChecks, runModelCheck };
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]="c6d6a007-651d-5165-b0c5-96a3cc6f3d07")}catch(e){}}();
4
- //# debugId=c6d6a007-651d-5165-b0c5-96a3cc6f3d07
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]="adf6431a-3ec0-5f09-baff-21b5e7ca3ecb")}catch(e){}}();
4
+ //# debugId=adf6431a-3ec0-5f09-baff-21b5e7ca3ecb
@@ -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]="f240d86b-7d0f-50bf-9865-bea0171d4b2d")}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]="cd2e1b1c-c85b-527b-83dd-d6b20065aea2")}catch(e){}}();
3
3
  import { t as readProjectSubgraphs } from "./subgraphs-Bm9NHTCn.mjs";
4
4
  import { n as processStreams, r as runModelCommand } from "./run-sVzTTEUx.mjs";
5
5
  import { t as renderCheckReport } from "./render-CQdi685k.mjs";
@@ -59,7 +59,7 @@ async function runModelCheck(args, options = {}) {
59
59
  */
60
60
  async function runPrepackCheck(json, options) {
61
61
  const streams = options.streams ?? processStreams;
62
- const { renderReleaseDecision, verifyRelease } = await import("./verify-BLn76w09.mjs");
62
+ const { renderReleaseDecision, verifyRelease } = await import("./verify-B3CKpYI8.mjs");
63
63
  let decision;
64
64
  try {
65
65
  decision = verifyRelease(options.projectRoot ?? process.cwd());
@@ -77,5 +77,5 @@ async function runPrepackCheck(json, options) {
77
77
  //#endregion
78
78
  export { runModelCheck as n, definitionChecks as t };
79
79
 
80
- //# sourceMappingURL=check-Cx_AeBQe.mjs.map
81
- //# debugId=f240d86b-7d0f-50bf-9865-bea0171d4b2d
80
+ //# sourceMappingURL=check-DQnWxQCS.mjs.map
81
+ //# debugId=cd2e1b1c-c85b-527b-83dd-d6b20065aea2
@@ -1 +1 @@
1
- {"version":3,"file":"check-Cx_AeBQe.mjs","sources":["../src/services/model/check.ts"],"sourcesContent":["import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport {\n checkProjectDefinitions,\n documentModelChecks,\n type ProjectDefinitions,\n subgraphChecks,\n} from \"document-model/tooling\";\nimport type { ReleaseDecision } from \"../release/approval.js\";\nimport type { ReleaseCheck } from \"../release/evidence.js\";\nimport type { ProjectModules } from \"@powerhousedao/codegen/utils\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderCheckReport } from \"./render.js\";\n\nasync function subgraphContributions(\n project: ProjectDefinitions,\n modules: ProjectModules,\n) {\n const subgraphs = await readProjectSubgraphs(project, modules);\n if (subgraphs === undefined) return undefined;\n return {\n checks: subgraphChecks,\n input: { subgraphs: subgraphs.input },\n inventory: subgraphs.inventory,\n };\n}\n\n/**\n * The edit and the release profile of the definition check, as `ph model\n * check` runs them and the definitions worker runs them for `ph build`.\n */\nexport const definitionChecks = {\n edit: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<DefinitionCheckReport> => {\n const contributions = await subgraphContributions(project, modules);\n if (contributions === undefined) return checkProjectDefinitions(project);\n return checkProjectDefinitions(\n { ...project, ...contributions.input },\n {\n checks: [...documentModelChecks, ...contributions.checks],\n definitions: contributions.inventory,\n },\n );\n },\n release: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<ReleaseCheck> => {\n const contributions = await subgraphContributions(project, modules);\n const { checkForRelease } = await import(\"../release/evidence.js\");\n return await checkForRelease(\n project,\n modules,\n contributions === undefined ? {} : { contributions },\n );\n },\n};\n\n/** `ph model check`. Returns the exit code. */\nexport async function runModelCheck(\n args: {\n readonly json: boolean;\n readonly release?: boolean;\n readonly prepack?: boolean;\n },\n options: ModelRunOptions = {},\n): Promise<number> {\n if (args.prepack) {\n if (args.release) {\n (options.streams ?? processStreams).err(\n \"ph model check could not run: --prepack and --release cannot be combined.\\n\",\n );\n return 2;\n }\n return await runPrepackCheck(args.json, options);\n }\n return await runModelCommand(\n {\n name: \"ph model check\",\n json: args.json,\n read: async (project, modules) =>\n args.release\n ? (await definitionChecks.release(project, modules)).report\n : await definitionChecks.edit(project, modules),\n render: renderCheckReport,\n },\n options,\n );\n}\n\n/**\n * `ph model check --prepack`: 0 when the release approval matches the\n * package, 1 when it does not, 2 when it cannot be checked. Loads none of\n * the package's modules.\n */\nasync function runPrepackCheck(\n json: boolean,\n options: ModelRunOptions,\n): Promise<number> {\n const streams = options.streams ?? processStreams;\n const { renderReleaseDecision, verifyRelease } =\n await import(\"../release/verify.js\");\n let decision: ReleaseDecision;\n try {\n decision = verifyRelease(options.projectRoot ?? process.cwd());\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n streams.err(`ph model check --prepack could not run: ${message}\\n`);\n return 2;\n }\n streams.out(\n `${json ? JSON.stringify({ decision: decision.decision, reasons: decision.reasons }) : renderReleaseDecision(decision)}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jB,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,EAAE,uBAAuB,kBAC7B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EACF,WAAW,cAAc,QAAQ,eAAe,QAAQ,IAAI,CAAC;CAC/D,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,IAAI,2CAA2C,QAAQ,GAAG;EAClE,OAAO;CACT;CACA,QAAQ,IACN,GAAG,OAAO,KAAK,UAAU;EAAE,UAAU,SAAS;EAAU,SAAS,SAAS;CAAQ,CAAC,IAAI,sBAAsB,QAAQ,EAAE,GACzH;CACA,OAAO,SAAS,aAAa,aAAa,IAAI;AAChD","debug_id":"f240d86b-7d0f-50bf-9865-bea0171d4b2d"}
1
+ {"version":3,"file":"check-DQnWxQCS.mjs","sources":["../src/services/model/check.ts"],"sourcesContent":["import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport {\n checkProjectDefinitions,\n documentModelChecks,\n type ProjectDefinitions,\n subgraphChecks,\n} from \"document-model/tooling\";\nimport type { ReleaseDecision } from \"../release/approval.js\";\nimport type { ReleaseCheck } from \"../release/evidence.js\";\nimport type { ProjectModules } from \"@powerhousedao/codegen/utils\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderCheckReport } from \"./render.js\";\n\nasync function subgraphContributions(\n project: ProjectDefinitions,\n modules: ProjectModules,\n) {\n const subgraphs = await readProjectSubgraphs(project, modules);\n if (subgraphs === undefined) return undefined;\n return {\n checks: subgraphChecks,\n input: { subgraphs: subgraphs.input },\n inventory: subgraphs.inventory,\n };\n}\n\n/**\n * The edit and the release profile of the definition check, as `ph model\n * check` runs them and the definitions worker runs them for `ph build`.\n */\nexport const definitionChecks = {\n edit: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<DefinitionCheckReport> => {\n const contributions = await subgraphContributions(project, modules);\n if (contributions === undefined) return checkProjectDefinitions(project);\n return checkProjectDefinitions(\n { ...project, ...contributions.input },\n {\n checks: [...documentModelChecks, ...contributions.checks],\n definitions: contributions.inventory,\n },\n );\n },\n release: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<ReleaseCheck> => {\n const contributions = await subgraphContributions(project, modules);\n const { checkForRelease } = await import(\"../release/evidence.js\");\n return await checkForRelease(\n project,\n modules,\n contributions === undefined ? {} : { contributions },\n );\n },\n};\n\n/** `ph model check`. Returns the exit code. */\nexport async function runModelCheck(\n args: {\n readonly json: boolean;\n readonly release?: boolean;\n readonly prepack?: boolean;\n },\n options: ModelRunOptions = {},\n): Promise<number> {\n if (args.prepack) {\n if (args.release) {\n (options.streams ?? processStreams).err(\n \"ph model check could not run: --prepack and --release cannot be combined.\\n\",\n );\n return 2;\n }\n return await runPrepackCheck(args.json, options);\n }\n return await runModelCommand(\n {\n name: \"ph model check\",\n json: args.json,\n read: async (project, modules) =>\n args.release\n ? (await definitionChecks.release(project, modules)).report\n : await definitionChecks.edit(project, modules),\n render: renderCheckReport,\n },\n options,\n );\n}\n\n/**\n * `ph model check --prepack`: 0 when the release approval matches the\n * package, 1 when it does not, 2 when it cannot be checked. Loads none of\n * the package's modules.\n */\nasync function runPrepackCheck(\n json: boolean,\n options: ModelRunOptions,\n): Promise<number> {\n const streams = options.streams ?? processStreams;\n const { renderReleaseDecision, verifyRelease } =\n await import(\"../release/verify.js\");\n let decision: ReleaseDecision;\n try {\n decision = verifyRelease(options.projectRoot ?? process.cwd());\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n streams.err(`ph model check --prepack could not run: ${message}\\n`);\n return 2;\n }\n streams.out(\n `${json ? JSON.stringify({ decision: decision.decision, reasons: decision.reasons }) : renderReleaseDecision(decision)}\\n`,\n );\n return decision.decision === \"approved\" ? 0 : 1;\n}\n"],"names":[],"mappings":";;;;;;;AAkBA,eAAe,sBACb,SACA,SACA;CACA,MA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WAAW,cAAc,QAAQ,eAAe,QAAQ,IAAI,CAAC;CAC/D,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,IAAI,2CAA2C,QAAQ,GAAG;EAClE,OAAO;CACT;CACA,QAAQ,IACN,GAAG,OAAO,KAAK,UAAU;EAAE,UAAU,SAAS;EAAU,SAAS,SAAS;CAAQ,CAAC,IAAI,sBAAsB,QAAQ,EAAE,GACzH;CACA,OAAO,SAAS,aAAa,aAAa,IAAI;AAChD","debug_id":"cd2e1b1c-c85b-527b-83dd-d6b20065aea2"}
package/dist/cli.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
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]="8facfdc9-9243-5252-b45c-0803036adc6d")}catch(e){}}();
4
- import { t as getVersion } from "./get-version-CTP__ORu.mjs";
5
- import { t as phCliCommands } from "./ph-cli-commands-B5VkGW99.mjs";
4
+ import { t as getVersion } from "./get-version-Cz5WJkpH.mjs";
5
+ import { t as phCliCommands } from "./ph-cli-commands-CGR5p3vg.mjs";
6
6
  import { initCliTelemetry } from "@powerhousedao/shared/clis/telemetry";
7
7
  import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
8
8
  import { run, runSafely, subcommands } from "cmd-ts";
@@ -114,7 +114,7 @@ async function main() {
114
114
  });
115
115
  let typed = process.argv.slice(2);
116
116
  if (typed[0] === "vetra" && !typed.some((arg) => arg === "--help" || arg === "-h")) {
117
- const { vetraGateway } = await import("./vetra-gateway-DE5Hc0Fp.mjs");
117
+ const { vetraGateway } = await import("./vetra-gateway-CeWIXaAl.mjs");
118
118
  const gateway = await vetraGateway(typed.slice(1));
119
119
  if ("exitCode" in gateway) process.exit(gateway.exitCode);
120
120
  typed = gateway.args;
@@ -123,7 +123,7 @@ async function main() {
123
123
  const refused = await sugarError(typed, process.cwd());
124
124
  if (refused !== void 0) throw new Error(refused);
125
125
  const { applyRunSugar, forwardRunnerArgv } = await import("./run-sugar-Dz-rpeMO.mjs");
126
- const { phCliCommands } = await import("./ph-cli-commands-CGXSo1wx.mjs");
126
+ const { phCliCommands } = await import("./ph-cli-commands-BcDloXsM.mjs");
127
127
  const sugar = applyRunSugar(typed, new Set(Object.keys(phCliCommands)), process.cwd());
128
128
  if (sugar.warning) console.warn(sugar.warning);
129
129
  const args = forwardRunnerArgv(sugar.args);
@@ -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]="24b23f0b-012b-5824-b864-3d35e6fb1d0a")}catch(e){}}();
3
- import { t as runBuild } from "./build-CBKlv5E3.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]="8d2375c2-88a4-5ee4-bec6-6b87dca37178")}catch(e){}}();
3
+ import { t as runBuild } from "./build-CGnPJwut.mjs";
4
4
  import { t as buildCliConnectOverride } from "./cli-connect-override-DKxY3lCi.mjs";
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
6
6
  import { join, resolve } from "node:path";
@@ -8,7 +8,7 @@ import { createHash } from "node:crypto";
8
8
  import { getConfig } from "@powerhousedao/shared/clis";
9
9
  import { SHARED_DEP_SPECIFIERS, SHARED_SUBPATHS, deepMerge, normalizeBasePath } from "@powerhousedao/shared/connect";
10
10
  import { gzip } from "node:zlib";
11
- import { DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, directoryContentDigest, findPackageRoot, getConnectBaseViteConfig, missingVendorEntries, ownProjectPackage, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, resolveReactorWorkerSource } from "@powerhousedao/builder-tools";
11
+ import { DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, directoryContentDigest, findPackageRoot, getConnectBaseViteConfig, missingVendorEntries, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, resolveReactorWorkerSource, workerLocalPackages } from "@powerhousedao/builder-tools";
12
12
  import { build, mergeConfig } from "vite";
13
13
  import { PRECOMPRESS_EXTENSIONS } from "@powerhousedao/ph-run/connect-serve";
14
14
  import { readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
@@ -271,13 +271,11 @@ async function prebuildReactorWorkerBundle(dirname, outDirAbs, vendor, connectOv
271
271
  * project's own types would be unavailable in worker mode.
272
272
  */
273
273
  async function prebuildLocalWorkerPackages(dirname, outDirAbs, vendor, safeVendorImports) {
274
- const configured = (getConfig(join(dirname, "powerhouse.config.json")).packages ?? []).filter((p) => p.provider === "local").map((p) => p.packageName);
275
- const own = ownProjectPackage(dirname);
276
- const localPackages = [.../* @__PURE__ */ new Set([...configured, ...own ? [own] : []])];
274
+ const config = getConfig(join(dirname, "powerhouse.config.json"));
277
275
  const errorRef = {};
278
276
  if (!await prebuildWorkerPackages({
279
277
  dirname,
280
- packages: localPackages,
278
+ packages: workerLocalPackages(dirname, config.packages),
281
279
  outDir: join(outDirAbs, "__reactor_worker__", "packages"),
282
280
  vendor: vendor ? {
283
281
  imports: vendor.imports,
@@ -318,5 +316,5 @@ function assertLocalPackagesInstalled(projectPath) {
318
316
  //#endregion
319
317
  export { runConnectBuild };
320
318
 
321
- //# sourceMappingURL=connect-build-DpGUrtct.mjs.map
322
- //# debugId=24b23f0b-012b-5824-b864-3d35e6fb1d0a
319
+ //# sourceMappingURL=connect-build-CQgSyKm1.mjs.map
320
+ //# debugId=8d2375c2-88a4-5ee4-bec6-6b87dca37178
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-build-CQgSyKm1.mjs","sources":["../src/utils/precompress.ts","../src/services/connect-build.ts"],"sourcesContent":["import { PRECOMPRESS_EXTENSIONS } from \"@powerhousedao/ph-run/connect-serve\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\n\nconst gzipAsync = promisify(gzip);\n\nexport { PRECOMPRESS_EXTENSIONS };\n\n/** A sibling is written only when it is at most this fraction of the source. */\nconst MAX_RATIO = 0.9;\n\nexport type PrecompressResult = {\n files: number;\n written: number;\n skipped: number;\n inputBytes: number;\n outputBytes: number;\n ms: number;\n};\n\nasync function findTargets(dir: string): Promise<string[]> {\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PRECOMPRESS_EXTENSIONS.some((ext) => e.name.endsWith(ext)),\n )\n .map((e) => join(e.parentPath, e.name));\n}\n\nasync function isFresh(source: string, sibling: string): Promise<boolean> {\n try {\n const [s, c] = await Promise.all([stat(source), stat(sibling)]);\n return c.mtimeMs >= s.mtimeMs;\n } catch {\n return false;\n }\n}\n\n/** Write gzip siblings for every `.wasm`/`.data` under `dir`. */\nexport async function precompressAssets(\n dir: string,\n): Promise<PrecompressResult> {\n const start = performance.now();\n const targets = await findTargets(dir);\n const result: PrecompressResult = {\n files: targets.length,\n written: 0,\n skipped: 0,\n inputBytes: 0,\n outputBytes: 0,\n ms: 0,\n };\n // Vendor and worker copies share content: compress each distinct file once.\n const byHash = new Map<string, Promise<Buffer | null>>();\n\n await Promise.all(\n targets.map(async (file) => {\n const sibling = file + \".gz\";\n if (await isFresh(file, sibling)) {\n result.skipped += 1;\n return;\n }\n const source = await readFile(file);\n result.inputBytes += source.length;\n const hash = createHash(\"sha256\").update(source).digest(\"hex\");\n let compressed = byHash.get(hash);\n if (!compressed) {\n compressed = gzipAsync(source, { level: 9 }).then((out) =>\n out.length <= source.length * MAX_RATIO ? out : null,\n );\n byHash.set(hash, compressed);\n }\n const out = await compressed;\n if (!out) {\n await rm(sibling, { force: true });\n result.skipped += 1;\n return;\n }\n await writeFile(sibling, out);\n result.written += 1;\n result.outputBytes += out.length;\n }),\n );\n\n result.ms = Math.round(performance.now() - start);\n return result;\n}\n\n/** On by default; PH_CONNECT_PRECOMPRESS=0|false disables it. */\nexport function isPrecompressEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_PRECOMPRESS ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n","import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n workerLocalPackages,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n deepMerge,\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport {\n isPrecompressEnabled,\n precompressAssets,\n} from \"../utils/precompress.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(\n args: ConnectBuildArgs,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const cli = buildCliConnectOverride(args);\n const { packageRegistryUrl } = cli;\n // A runner's host config sits under the CLI's flags.\n const connectOverride = callerOverride\n ? deepMerge(callerOverride, cli.connectOverride ?? {})\n : cli.connectOverride;\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n release: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n routes,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n\n // Runs after the PWA plugin, so the siblings never enter the precache list.\n if (isPrecompressEnabled()) {\n const r = await precompressAssets(outDirAbs);\n console.log(\n `ph connect build: precompressed ${r.files} wasm/data files ` +\n `(${r.written} .gz written, ${(r.outputBytes / 1e6).toFixed(1)} MB) in ${(r.ms / 1000).toFixed(1)}s`,\n );\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n // One core and router for Connect and packages; the route tree, config and\n // embedded subpaths stay with the app.\n \"@powerhousedao/connect-core\",\n \"@powerhousedao/connect-core/router\",\n \"@powerhousedao/connect-core/plugins\",\n \"@powerhousedao/connect-core/runtime\",\n \"@powerhousedao/connect-core/views\",\n \"@tanstack/react-router\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself.\n packages: workerLocalPackages(dirname, config.packages),\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA,MAAM,YAAY,UAAU,IAAI;;AAKhC,MAAM,YAAY;AAWlB,eAAe,YAAY,KAAgC;CAEzD,QAAO,MADe,QAAQ,KAAK;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,EAAA,CAExE,QACE,MACC,EAAE,OAAO,KACT,uBAAuB,MAAM,QAAQ,EAAE,KAAK,SAAS,GAAG,CAAC,CAC7D,CAAC,CACA,KAAK,MAAM,KAAK,EAAE,YAAY,EAAE,IAAI,CAAC;AAC1C;AAEA,eAAe,QAAQ,QAAgB,SAAmC;CACxE,IAAI;EACF,MAAM,CAAC,GAAG,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,MAAM,GAAG,KAAK,OAAO,CAAC,CAAC;EAC9D,OAAO,EAAE,WAAW,EAAE;CACxB,QAAQ;EACN,OAAO;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AAW;CAC9C,MAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"8d2375c2-88a4-5ee4-bec6-6b87dca37178"}
@@ -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]="e56cea60-d144-5b02-b0e3-335765c8a937")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-CTP__ORu.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]="0155c796-e4e5-5b70-bf70-268c24470dd5")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-Cz5WJkpH.mjs";
4
4
  import { U as resolveHostPlugins, lt as normalizePluginEntries, rt as PluginError } from "./compound-g6x_KkWp-Bs7olmlI.mjs";
5
5
  import { r as buildStudioConnectOverride } from "./cli-connect-override-DKxY3lCi.mjs";
6
6
  import { t as switchboardProxy } from "./switchboard-proxy-CGfMtENM.mjs";
@@ -210,5 +210,5 @@ async function runConnectStudio(args, customLogger, callerOverride, { routes, ca
210
210
  //#endregion
211
211
  export { runConnectStudio };
212
212
 
213
- //# sourceMappingURL=connect-studio-BPZOcwUM.mjs.map
214
- //# debugId=e56cea60-d144-5b02-b0e3-335765c8a937
213
+ //# sourceMappingURL=connect-studio-SH4U0Cpm.mjs.map
214
+ //# debugId=0155c796-e4e5-5b70-bf70-268c24470dd5
@@ -1 +1 @@
1
- {"version":3,"file":"connect-studio-BPZOcwUM.mjs","sources":["../src/services/connect-dev-plugins.ts","../src/services/dev-run.ts","../src/services/connect-studio.ts"],"sourcesContent":["import {\n normalizePluginEntries,\n PluginError,\n resolveHostPlugins,\n type ConnectDevHooks,\n type ConnectDevServerContext,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\nimport type { PluginOption } from \"vite\";\n\n/** The verb the plugins of a dev server are resolved for. */\nconst DEV_VERB = \"dev\";\n\n/**\n * The dev-server plugins every Connect dev server loads, resolved from the\n * CLI's own dependencies. A host turns one off with an entry of the same\n * module and `enabled: false` in its `runner.devPlugins`.\n */\nexport const DEFAULT_CONNECT_DEV_PLUGINS: readonly PluginEntryData[] = [\n \"@powerhousedao/devtools/connect\",\n];\n\nexport type ConnectDevPluginsOptions = {\n projectRoot: string;\n /** The host's `runner.devPlugins`, resolved from the project. */\n entries?: readonly PluginEntryData[];\n /** Where `entries` are written, for error messages. */\n where: string;\n context: ConnectDevServerContext;\n /** In place of {@link DEFAULT_CONNECT_DEV_PLUGINS}. */\n defaults?: readonly PluginEntryData[];\n};\n\ntype Resolved = Awaited<\n ReturnType<typeof resolveHostPlugins<ConnectDevHooks<PluginOption>>>\n>;\n\nconst DEFAULTS_WHERE = \"the dev server's default plugins\";\n\n/** Resolves from the CLI's own dependencies, where the default plugins are. */\nconst fromCli = (entries: readonly PluginEntryData[], where: string) =>\n resolveHostPlugins<ConnectDevHooks<PluginOption>>(\n import.meta.dirname,\n \"connect\",\n DEV_VERB,\n entries,\n where,\n );\n\n/** What the plugins' `devServer` hooks give. */\nasync function vitePluginsOf(\n resolved: Resolved,\n where: string,\n context: ConnectDevServerContext,\n): Promise<PluginOption[]> {\n const plugins: PluginOption[] = [];\n for (const { plugin, entry } of resolved) {\n const devServer = plugin.hooks?.devServer;\n const shape =\n 'A dev-server plugin default-exports `{ name, appliesTo: \"connect\", hooks: { devServer } }`, and the hook returns a list of Vite plugins.';\n if (!devServer) {\n throw new PluginError(\n `${where}: dev-server plugin \"${entry.module}\" has no devServer hook.`,\n shape,\n );\n }\n const given: unknown = await devServer(context);\n if (!Array.isArray(given)) {\n throw new PluginError(\n `${where}: the devServer hook of \"${entry.module}\" did not return a list.`,\n shape,\n );\n }\n plugins.push(...(given as PluginOption[]));\n }\n return plugins;\n}\n\n/** A default plugin is an aid, not a part of the dev server: one that cannot\n * load, or whose hook fails, is left out with a warning, and the server\n * starts without it. */\nasync function defaultPlugins(\n entries: readonly PluginEntryData[],\n context: ConnectDevServerContext,\n): Promise<PluginOption[]> {\n const plugins: PluginOption[] = [];\n for (const entry of entries) {\n try {\n const resolved = await fromCli([entry], DEFAULTS_WHERE);\n plugins.push(...(await vitePluginsOf(resolved, DEFAULTS_WHERE, context)));\n } catch (error) {\n console.warn(\n `[connect] Leaving out a default dev-server plugin: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return plugins;\n}\n\n/**\n * The Vite plugins of a Connect dev server's plugins: the default ones and\n * the host's, each asked through its `devServer` hook. Only a dev server\n * (`runConnectStudio`) asks, so what the plugins add never reaches a build.\n */\nexport async function resolveConnectDevPlugins({\n projectRoot,\n entries = [],\n where,\n context,\n defaults = DEFAULT_CONNECT_DEV_PLUGINS,\n}: ConnectDevPluginsOptions): Promise<PluginOption[]> {\n const moduleOf = (entry: PluginEntryData) =>\n normalizePluginEntries([entry], where)[0].module;\n const defaultModules = new Set(defaults.map(moduleOf));\n const named = new Set(entries.map(moduleOf));\n const isDefault = (entry: PluginEntryData) =>\n defaultModules.has(moduleOf(entry));\n\n // What a host names itself must load: a failure there stops the server.\n const hosts = [\n // A host's entry for a default plugin configures that plugin or turns it\n // off: it is still the CLI's, which a project need not depend on.\n ...(await fromCli(entries.filter(isDefault), where)),\n ...(await resolveHostPlugins<ConnectDevHooks<PluginOption>>(\n projectRoot,\n \"connect\",\n DEV_VERB,\n entries.filter((entry) => !isDefault(entry)),\n where,\n )),\n ];\n return [\n ...(await defaultPlugins(\n defaults.filter((entry) => !named.has(moduleOf(entry))),\n context,\n )),\n ...(await vitePluginsOf(hosts, where, context)),\n ];\n}\n","import type { ConnectDevRun } from \"@powerhousedao/host-core\";\nimport { getVersion } from \"../get-version.js\";\nimport { readVetraRuntime } from \"../utils/vetra-runtime.js\";\n\n/** What this process knows of the run its dev server is part of. Another\n * process's `ph vetra` in the same project is not this run. */\nexport function readDevRun(projectDir: string): ConnectDevRun {\n const record = readVetraRuntime(projectDir);\n const own = record?.pid === process.pid ? record : undefined;\n const services: Record<string, string> = {};\n if (own?.connectUrl) services.connect = own.connectUrl;\n if (own?.switchboardUrl) services.switchboard = own.switchboardUrl;\n if (own?.mcpUrl) services.mcp = own.mcpUrl;\n return {\n tool: { name: \"ph-cli\", version: getVersion() },\n startedAt: own?.startedAt ?? null,\n services,\n };\n}\n","import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport {\n resolveServedFiles,\n servedFilesStep,\n} from \"@powerhousedao/ph-run/connect-serve\";\nimport {\n localSignInStep,\n type LocalSignInOptions,\n type LocalSignInStep,\n} from \"@powerhousedao/ph-run/local-sign-in\";\nimport type { PluginEntryData } from \"@powerhousedao/host-core\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, Plugin, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\nimport { resolveConnectDevPlugins } from \"./connect-dev-plugins.js\";\nimport { readDevRun } from \"./dev-run.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n /** Files served by name, read against the working directory at each\n * request (runner.serveFiles), as the servers of a build serve them. */\n serveFiles?: Readonly<Record<string, string>>;\n /** Runs before a config change replaces the server, for a caller whose\n * override follows the config too. When it rejects, the server stays. */\n beforeRestart?: () => Promise<void>;\n /** Runs each restart's server start, for a caller that started the first\n * one inside a wrapper of its own. */\n restartWith?: (start: () => Promise<ViteDevServer>) => Promise<ViteDevServer>;\n /** Handed what stops Studio for good, before it resolves: the config\n * watcher and whichever server is current. The first server's own `close`\n * stops neither once a config change has replaced it. */\n exposeStop?: (stop: () => Promise<void>) => void;\n /** Sign-in by link: the loopback endpoint every server of this Studio\n * serves (F3d). One for all of them, so a code taken stays taken. */\n localSignIn?: Omit<LocalSignInOptions, \"port\" | \"base\">;\n /** Makes this a dev server with its dev-server plugins: the default ones\n * and `entries`, a host's `runner.devPlugins`, written at `where`. Without\n * it, none load. */\n devPlugins?: { entries: readonly PluginEntryData[]; where: string };\n};\n\n/** Where a dev server listens. */\nfunction portOf(server: ViteDevServer | undefined): number | undefined {\n const address = server?.httpServer?.address();\n return typeof address === \"object\" && address ? address.port : undefined;\n}\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n {\n routes,\n cacheDir,\n reloadOnConfigChange,\n proxy,\n serveFiles,\n beforeRestart,\n restartWith,\n exposeStop,\n localSignIn,\n devPlugins,\n }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n // Ahead of vite's own middlewares (its SPA fallback among them), under the\n // base vite serves at.\n const servedFiles: Plugin | undefined = serveFiles && {\n name: \"ph:serve-files\",\n configureServer(server) {\n server.middlewares.use(\n servedFilesStep(\n resolveServedFiles(serveFiles, dirname),\n server.config.base,\n ),\n );\n },\n };\n // Ahead of vite's CORS: it answers this computer's pages only. Made with\n // the first server and kept by the next ones.\n const current: { server?: ViteDevServer; step?: LocalSignInStep } = {};\n const signInPlugin: Plugin | undefined = localSignIn && {\n name: \"ph:local-sign-in\",\n configureServer(server) {\n current.server = server;\n current.step ??= localSignInStep({\n ...localSignIn,\n base: server.config.base,\n port: () => portOf(current.server),\n });\n server.middlewares.use(current.step);\n },\n };\n const plugins = [\n ...(signInPlugin ? [signInPlugin] : []),\n ...(servedFiles ? [servedFiles] : []),\n ];\n\n // Resolved once: every restart serves the same plugin instances, so what a\n // plugin gave an open tab, such as a token, stays good.\n const devServerPlugins = devPlugins\n ? await resolveConnectDevPlugins({\n projectRoot: dirname,\n entries: devPlugins.entries,\n where: devPlugins.where,\n context: { projectRoot: dirname, run: () => readDevRun(dirname) },\n })\n : [];\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n plugins: [...plugins, ...devServerPlugins],\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n let loaded = reloadOnConfigChange ? readConfig(configFile) : undefined;\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) {\n exposeStop?.(() => {\n current.step?.dispose();\n return first.close();\n });\n return first;\n }\n\n let server = first;\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n let stopped = false;\n const restart = async () => {\n if (stopped) return;\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await beforeRestart?.();\n await server.close();\n server = await (restartWith\n ? restartWith(() => start(false))\n : start(false));\n };\n const queueRestart = () => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file === CONFIG_FILE) queueRestart();\n });\n watcher.unref();\n exposeStop?.(async () => {\n stopped = true;\n clearTimeout(timer);\n watcher.close();\n current.step?.dispose();\n // A restart under way ends first: it leaves the server to close.\n await restarts;\n await server.close();\n });\n // Catch config edits made while the first server was starting.\n queueRestart();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAM,WAAW;;;;;;AAOjB,MAAa,8BAA0D,CACrE,iCACF;AAiBA,MAAM,iBAAiB;;AAGvB,MAAM,WAAW,SAAqC,UACpD,mBACE,YAAY,SACZ,WACA,UACA,SACA,KACF;;AAGF,eAAe,cACb,UACA,OACA,SACyB;CACzB,MAAM,UAA0B,CAAC;CACjC,KAAK,MAAM,EAAE,QAAQ,WAAW,UAAU;EACxC,MAAM,YAAY,OAAO,OAAO;EAChC,MAAM,QACJ;EACF,IAAI,CAAC,WACH,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,MAAM,OAAO,2BAC7C,KACF;EAEF,MAAM,QAAiB,MAAM,UAAU,OAAO;EAC9C,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,MAAM,IAAI,YACR,GAAG,MAAM,2BAA2B,MA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uCACzB,EAAE,WAAW,KAAK,CACpB;EACA,MAAM,gBAAgB;EACtB,MAAM,OAAO,MAAM;EACnB,SAAS,OAAO,cACZ,kBAAkB,MAAM,KAAK,CAAC,IAC9B,MAAM,KAAK;CACjB;CACA,MAAM,qBAAqB;EACzB,aAAa,KAAK;EAClB,QAAQ,iBAAiB;GACvB,WAAW,SAAS,KAAK,OAAO,CAAC,CAAC,OAAO,UAAmB;IAC1D,OAAO,OAAO,OAAO,MACnB,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC9F;GACF,CAAC;EACH,GAAG,kBAAkB;CACvB;CAEA,MAAM,UAAU,MAAM,UAAU,QAAQ,SAAS;EAC/C,IAAI,SAAS,aAAa,aAAa;CACzC,CAAC;CACD,QAAQ,MAAM;CACd,aAAa,YAAY;EACvB,UAAU;EACV,aAAa,KAAK;EAClB,QAAQ,MAAM;EACd,QAAQ,MAAM,QAAQ;EAEtB,MAAM;EACN,MAAM,OAAO,MAAM;CACrB,CAAC;CAED,aAAa;CACb,OAAO;AACT","debug_id":"e56cea60-d144-5b02-b0e3-335765c8a937"}
1
+ {"version":3,"file":"connect-studio-SH4U0Cpm.mjs","sources":["../src/services/connect-dev-plugins.ts","../src/services/dev-run.ts","../src/services/connect-studio.ts"],"sourcesContent":["import {\n normalizePluginEntries,\n PluginError,\n resolveHostPlugins,\n type ConnectDevHooks,\n type ConnectDevServerContext,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\nimport type { PluginOption } from \"vite\";\n\n/** The verb the plugins of a dev server are resolved for. */\nconst DEV_VERB = \"dev\";\n\n/**\n * The dev-server plugins every Connect dev server loads, resolved from the\n * CLI's own dependencies. A host turns one off with an entry of the same\n * module and `enabled: false` in its `runner.devPlugins`.\n */\nexport const DEFAULT_CONNECT_DEV_PLUGINS: readonly PluginEntryData[] = [\n \"@powerhousedao/devtools/connect\",\n];\n\nexport type ConnectDevPluginsOptions = {\n projectRoot: string;\n /** The host's `runner.devPlugins`, resolved from the project. */\n entries?: readonly PluginEntryData[];\n /** Where `entries` are written, for error messages. */\n where: string;\n context: ConnectDevServerContext;\n /** In place of {@link DEFAULT_CONNECT_DEV_PLUGINS}. */\n defaults?: readonly PluginEntryData[];\n};\n\ntype Resolved = Awaited<\n ReturnType<typeof resolveHostPlugins<ConnectDevHooks<PluginOption>>>\n>;\n\nconst DEFAULTS_WHERE = \"the dev server's default plugins\";\n\n/** Resolves from the CLI's own dependencies, where the default plugins are. */\nconst fromCli = (entries: readonly PluginEntryData[], where: string) =>\n resolveHostPlugins<ConnectDevHooks<PluginOption>>(\n import.meta.dirname,\n \"connect\",\n DEV_VERB,\n entries,\n where,\n );\n\n/** What the plugins' `devServer` hooks give. */\nasync function vitePluginsOf(\n resolved: Resolved,\n where: string,\n context: ConnectDevServerContext,\n): Promise<PluginOption[]> {\n const plugins: PluginOption[] = [];\n for (const { plugin, entry } of resolved) {\n const devServer = plugin.hooks?.devServer;\n const shape =\n 'A dev-server plugin default-exports `{ name, appliesTo: \"connect\", hooks: { devServer } }`, and the hook returns a list of Vite plugins.';\n if (!devServer) {\n throw new PluginError(\n `${where}: dev-server plugin \"${entry.module}\" has no devServer hook.`,\n shape,\n );\n }\n const given: unknown = await devServer(context);\n if (!Array.isArray(given)) {\n throw new PluginError(\n `${where}: the devServer hook of \"${entry.module}\" did not return a list.`,\n shape,\n );\n }\n plugins.push(...(given as PluginOption[]));\n }\n return plugins;\n}\n\n/** A default plugin is an aid, not a part of the dev server: one that cannot\n * load, or whose hook fails, is left out with a warning, and the server\n * starts without it. */\nasync function defaultPlugins(\n entries: readonly PluginEntryData[],\n context: ConnectDevServerContext,\n): Promise<PluginOption[]> {\n const plugins: PluginOption[] = [];\n for (const entry of entries) {\n try {\n const resolved = await fromCli([entry], DEFAULTS_WHERE);\n plugins.push(...(await vitePluginsOf(resolved, DEFAULTS_WHERE, context)));\n } catch (error) {\n console.warn(\n `[connect] Leaving out a default dev-server plugin: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return plugins;\n}\n\n/**\n * The Vite plugins of a Connect dev server's plugins: the default ones and\n * the host's, each asked through its `devServer` hook. Only a dev server\n * (`runConnectStudio`) asks, so what the plugins add never reaches a build.\n */\nexport async function resolveConnectDevPlugins({\n projectRoot,\n entries = [],\n where,\n context,\n defaults = DEFAULT_CONNECT_DEV_PLUGINS,\n}: ConnectDevPluginsOptions): Promise<PluginOption[]> {\n const moduleOf = (entry: PluginEntryData) =>\n normalizePluginEntries([entry], where)[0].module;\n const defaultModules = new Set(defaults.map(moduleOf));\n const named = new Set(entries.map(moduleOf));\n const isDefault = (entry: PluginEntryData) =>\n defaultModules.has(moduleOf(entry));\n\n // What a host names itself must load: a failure there stops the server.\n const hosts = [\n // A host's entry for a default plugin configures that plugin or turns it\n // off: it is still the CLI's, which a project need not depend on.\n ...(await fromCli(entries.filter(isDefault), where)),\n ...(await resolveHostPlugins<ConnectDevHooks<PluginOption>>(\n projectRoot,\n \"connect\",\n DEV_VERB,\n entries.filter((entry) => !isDefault(entry)),\n where,\n )),\n ];\n return [\n ...(await defaultPlugins(\n defaults.filter((entry) => !named.has(moduleOf(entry))),\n context,\n )),\n ...(await vitePluginsOf(hosts, where, context)),\n ];\n}\n","import type { ConnectDevRun } from \"@powerhousedao/host-core\";\nimport { getVersion } from \"../get-version.js\";\nimport { readVetraRuntime } from \"../utils/vetra-runtime.js\";\n\n/** What this process knows of the run its dev server is part of. Another\n * process's `ph vetra` in the same project is not this run. */\nexport function readDevRun(projectDir: string): ConnectDevRun {\n const record = readVetraRuntime(projectDir);\n const own = record?.pid === process.pid ? record : undefined;\n const services: Record<string, string> = {};\n if (own?.connectUrl) services.connect = own.connectUrl;\n if (own?.switchboardUrl) services.switchboard = own.switchboardUrl;\n if (own?.mcpUrl) services.mcp = own.mcpUrl;\n return {\n tool: { name: \"ph-cli\", version: getVersion() },\n startedAt: own?.startedAt ?? null,\n services,\n };\n}\n","import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport {\n resolveServedFiles,\n servedFilesStep,\n} from \"@powerhousedao/ph-run/connect-serve\";\nimport {\n localSignInStep,\n type LocalSignInOptions,\n type LocalSignInStep,\n} from \"@powerhousedao/ph-run/local-sign-in\";\nimport type { PluginEntryData } from \"@powerhousedao/host-core\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, Plugin, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\nimport { resolveConnectDevPlugins } from \"./connect-dev-plugins.js\";\nimport { readDevRun } from \"./dev-run.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n /** Files served by name, read against the working directory at each\n * request (runner.serveFiles), as the servers of a build serve them. */\n serveFiles?: Readonly<Record<string, string>>;\n /** Runs before a config change replaces the server, for a caller whose\n * override follows the config too. When it rejects, the server stays. */\n beforeRestart?: () => Promise<void>;\n /** Runs each restart's server start, for a caller that started the first\n * one inside a wrapper of its own. */\n restartWith?: (start: () => Promise<ViteDevServer>) => Promise<ViteDevServer>;\n /** Handed what stops Studio for good, before it resolves: the config\n * watcher and whichever server is current. The first server's own `close`\n * stops neither once a config change has replaced it. */\n exposeStop?: (stop: () => Promise<void>) => void;\n /** Sign-in by link: the loopback endpoint every server of this Studio\n * serves (F3d). One for all of them, so a code taken stays taken. */\n localSignIn?: Omit<LocalSignInOptions, \"port\" | \"base\">;\n /** Makes this a dev server with its dev-server plugins: the default ones\n * and `entries`, a host's `runner.devPlugins`, written at `where`. Without\n * it, none load. */\n devPlugins?: { entries: readonly PluginEntryData[]; where: string };\n};\n\n/** Where a dev server listens. */\nfunction portOf(server: ViteDevServer | undefined): number | undefined {\n const address = server?.httpServer?.address();\n return typeof address === \"object\" && address ? address.port : undefined;\n}\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n {\n routes,\n cacheDir,\n reloadOnConfigChange,\n proxy,\n serveFiles,\n beforeRestart,\n restartWith,\n exposeStop,\n localSignIn,\n devPlugins,\n }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n // Ahead of vite's own middlewares (its SPA fallback among them), under the\n // base vite serves at.\n const servedFiles: Plugin | undefined = serveFiles && {\n name: \"ph:serve-files\",\n configureServer(server) {\n server.middlewares.use(\n servedFilesStep(\n resolveServedFiles(serveFiles, dirname),\n server.config.base,\n ),\n );\n },\n };\n // Ahead of vite's CORS: it answers this computer's pages only. Made with\n // the first server and kept by the next ones.\n const current: { server?: ViteDevServer; step?: LocalSignInStep } = {};\n const signInPlugin: Plugin | undefined = localSignIn && {\n name: \"ph:local-sign-in\",\n configureServer(server) {\n current.server = server;\n current.step ??= localSignInStep({\n ...localSignIn,\n base: server.config.base,\n port: () => portOf(current.server),\n });\n server.middlewares.use(current.step);\n },\n };\n const plugins = [\n ...(signInPlugin ? [signInPlugin] : []),\n ...(servedFiles ? [servedFiles] : []),\n ];\n\n // Resolved once: every restart serves the same plugin instances, so what a\n // plugin gave an open tab, such as a token, stays good.\n const devServerPlugins = devPlugins\n ? await resolveConnectDevPlugins({\n projectRoot: dirname,\n entries: devPlugins.entries,\n where: devPlugins.where,\n context: { projectRoot: dirname, run: () => readDevRun(dirname) },\n })\n : [];\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n plugins: [...plugins, ...devServerPlugins],\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n let loaded = reloadOnConfigChange ? readConfig(configFile) : undefined;\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) {\n exposeStop?.(() => {\n current.step?.dispose();\n return first.close();\n });\n return first;\n }\n\n let server = first;\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n let stopped = false;\n const restart = async () => {\n if (stopped) return;\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await beforeRestart?.();\n await server.close();\n server = await (restartWith\n ? restartWith(() => start(false))\n : start(false));\n };\n const queueRestart = () => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file === CONFIG_FILE) queueRestart();\n });\n watcher.unref();\n exposeStop?.(async () => {\n stopped = true;\n clearTimeout(timer);\n watcher.close();\n current.step?.dispose();\n // A restart under way ends first: it leaves the server to close.\n await restarts;\n await server.close();\n });\n // Catch config edits made while the first server was starting.\n queueRestart();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAM,WAAW;;;;;;AAOjB,MAAa,8BAA0D,CACrE,iCACF;AAiBA,MAAM,iBAAiB;;AAGvB,MAAM,WAAW,SAAqC,UACpD,mBACE,YAAY,SACZ,WACA,UACA,SACA,KACF;;AAGF,eAAe,cACb,UACA,OACA,SACyB;CACzB,MAAM,UAA0B,CAAC;CACjC,KAAK,MAAM,EAAE,QAAQ,WAAW,UAAU;EACxC,MAAM,YAAY,OAAO,OAAO;EAChC,MAAM,QACJ;EACF,IAAI,CAAC,WACH,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,MAAM,OAAO,2BAC7C,KACF;EAEF,MAAM,QAAiB,MAAM,UAAU,OAAO;EAC9C,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,MAAM,IAAI,YACR,GAAG,MAAM,2BAA2B,MAAM,OAAO,2BACjD,KACF;EAEF,QAAQ,KAAK,GAAI,KAAwB;CAC3C;CACA,OAAO;AACT;;;;AAKA,eAAe,eACb,SACA,SACyB;CACzB,MAAM,UAA0B,CAAC;CACjC,KAAK,MAAM,SAAS,SAClB,IAAI;EACF,MAAM,WAAW,MAAM,QAAQ,CAAC,KAAK,GAAG,cAAc;EACtD,QAAQ,KAAK,GAAI,MAAM,cAAc,UAAU,gBAAgB,OAAO,CAAE;CAC1E,SAAS,OAAO;EACd,QAAQ,KACN,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC7G;CACF;CAEF,OAAO;AACT;;;;;;AAOA,eAAsB,yBAAyB,EAC7C,aACA,UAAU,CAA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aAAa,aAAa;CACzC,CAAC;CACD,QAAQ,MAAM;CACd,aAAa,YAAY;EACvB,UAAU;EACV,aAAa,KAAK;EAClB,QAAQ,MAAM;EACd,QAAQ,MAAM,QAAQ;EAEtB,MAAM;EACN,MAAM,OAAO,MAAM;CACrB,CAAC;CAED,aAAa;CACb,OAAO;AACT","debug_id":"0155c796-e4e5-5b70-bf70-268c24470dd5"}
@@ -1,6 +1,6 @@
1
1
 
2
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]="a0173a8f-a81f-5cf8-9ce3-157981a85936")}catch(e){}}();
3
- import { t as definitionChecks } from "./check-Cx_AeBQe.mjs";
3
+ import { t as definitionChecks } from "./check-DQnWxQCS.mjs";
4
4
  import { readProjectDefinitions } from "@powerhousedao/codegen/utils";
5
5
  //#region src/services/model/definitions-worker.ts
6
6
  async function check(projectRoot, profile) {
@@ -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]="7b15c1d5-e9e7-5d18-9bf0-80f3184cc19d")}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]="2e03fd50-e032-5707-b31f-405d0f1ea6e4")}catch(e){}}();
4
4
  function getVersion() {
5
- return "6.4.0-next.5";
5
+ return "6.4.0-next.6";
6
6
  }
7
7
  //#endregion
8
8
  export { getVersion as t };
9
9
 
10
- //# sourceMappingURL=get-version-CTP__ORu.mjs.map
11
- //# debugId=7b15c1d5-e9e7-5d18-9bf0-80f3184cc19d
10
+ //# sourceMappingURL=get-version-Cz5WJkpH.mjs.map
11
+ //# debugId=2e03fd50-e032-5707-b31f-405d0f1ea6e4
@@ -1 +1 @@
1
- {"version":3,"file":"get-version-CTP__ORu.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":"7b15c1d5-e9e7-5d18-9bf0-80f3184cc19d"}
1
+ {"version":3,"file":"get-version-Cz5WJkpH.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":"2e03fd50-e032-5707-b31f-405d0f1ea6e4"}
@@ -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]="4842d577-7fb4-5bf9-8853-ddeba294b81f")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-CTP__ORu.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]="117843b5-8007-55ed-b766-ea7ab7956938")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-Cz5WJkpH.mjs";
4
4
  import { a as restartVetra, n as currentPhCliRunVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launcher-6NKfi6Au.mjs";
5
5
  import { i as readVetraRuntime } from "./vetra-runtime-Bk6CW-BE.mjs";
6
6
  import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
@@ -401,5 +401,5 @@ async function startMcpLauncher(options) {
401
401
  //#endregion
402
402
  export { startMcpLauncher };
403
403
 
404
- //# sourceMappingURL=mcp-gcG7SW9L.mjs.map
405
- //# debugId=4842d577-7fb4-5bf9-8853-ddeba294b81f
404
+ //# sourceMappingURL=mcp-Cx2HhCsK.mjs.map
405
+ //# debugId=117843b5-8007-55ed-b766-ea7ab7956938
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-gcG7SW9L.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 type { LocalDocumentModels } from \"@powerhousedao/reactor-mcp/remote\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport { identityDataDir } from \"@powerhousedao/shared/clis/identity\";\nimport type * as RenownIdentity from \"@renown/sdk/identity\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n ensureVetra,\n restartVetra,\n currentPhCliRunVetraCommand,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launcher.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 {@link currentPhCliRunVetraCommand}. */\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 dev stack (its Switchboard and Connect, what `ph dev` runs) and wait until it is ready. \" +\n \"Use it after a change the stack reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Connect 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 /** That Vetra's record, for its Switchboard's GraphQL endpoint. */\n #record: VetraRuntimeRecord | 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 /** The running Vetra's Switchboard GraphQL endpoint, starting Vetra when it is down. */\n async switchboard(onProgress?: Progress): Promise<string> {\n await this.get(onProgress);\n return vetraUrls(this.#record!).switchboardUrl;\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:\n this.options.vetraCommand ?? currentPhCliRunVetraCommand(projectDir),\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 this.#record = record;\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/** The tools that write: they run here, signed and borne as the MCP client's session. */\nexport const SIGNED_TOOLS: ReadonlySet<string> = new Set([\n \"createDocument\",\n \"addActions\",\n \"deleteDocument\",\n]);\n\n/** What an MCP client's session is called, and its credential signs. */\nexport function mcpSessionLabel(clientName: string | undefined): string {\n return `mcp ${clientName?.trim() || \"client\"}`;\n}\n\n/** How long a Renown approval of a session is waited for. */\nconst APPROVAL_WAIT_MS = 10 * 60_000;\n\ntype Answer = { result: CallToolResult } | { forward: true };\n\n/**\n * The writing tools, run in this process over the project's Switchboard,\n * every action signed and every request borne as the MCP client's own\n * session (`mcp <client>`), kept in the project's data folder with its\n * credential's record: the pseudonym's, issued at the first write, or one a\n * Renown login approves once at Renown's console. A call that needs a model\n * this process does not hold, before it wrote anything, goes to the host's\n * `/mcp` instead, which signs its writes itself.\n */\nclass SignedTools {\n #models: Promise<LocalDocumentModels> | undefined;\n /** The console approvals waited for, by session label. */\n #approvals = new Map<string, string>();\n\n constructor(private readonly projectDir: string) {}\n\n #localModels(): Promise<LocalDocumentModels> {\n this.#models ??= import(\"@powerhousedao/reactor-mcp/remote\").then(\n ({ localDocumentModels }) =>\n localDocumentModels(this.projectDir, {\n onError: (error) =>\n console.error(\n `[ph mcp] the project's document models did not load: ${error instanceof Error ? error.message : String(error)}`,\n ),\n }),\n );\n return this.#models;\n }\n\n async call(\n params: CallToolRequest[\"params\"],\n label: string,\n graphqlUrl: string,\n signal: AbortSignal,\n ): Promise<Answer> {\n const identity = await import(\"@renown/sdk/identity\");\n const dataDir = identityDataDir(this.projectDir);\n let session: Awaited<ReturnType<typeof identity.openSession>>;\n try {\n session = await identity.openSession({\n dataDir,\n label,\n place: \"data-folder\",\n interactive: false,\n target: { dataDir },\n // A client that acts by itself stays withdrawn where it was withdrawn.\n reissueWithdrawn: false,\n });\n } catch (error) {\n if (error instanceof identity.SessionApprovalRequiredError) {\n return { result: toolError(this.#approve(identity, label, dataDir)) };\n }\n throw error;\n }\n const [{ createRemoteServer }, { GraphQLReactorClient }, models] =\n await Promise.all([\n import(\"@powerhousedao/reactor-mcp/remote\"),\n import(\"@powerhousedao/reactor-browser/graphql-client\"),\n this.#localModels(),\n ]);\n const client = new GraphQLReactorClient({\n url: graphqlUrl,\n documentModels: () => models.current(),\n signer: session.actionSigner,\n tokenProvider: () => session.bearer(),\n realtime: false,\n });\n const seen = { missing: false, wrote: false };\n const server = createRemoteServer({\n client,\n documentModels: () => models.current(),\n onMissingModel: () => {\n seen.missing = true;\n },\n onWrite: () => {\n seen.wrote = true;\n },\n });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n const local = new Client({ name: \"ph-mcp\", version: getVersion() });\n try {\n await server.connect(serverSide);\n await local.connect(clientSide);\n const result = (await local.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n )) as CallToolResult;\n if (result.isError && seen.missing && !seen.wrote) {\n return { forward: true };\n }\n return { result };\n } finally {\n client.dispose();\n await local.close().catch(() => {});\n await server.close().catch(() => {});\n }\n }\n\n /** Starts, once per session, the approval a Renown login gives at the console. */\n #approve(\n identity: typeof RenownIdentity,\n label: string,\n dataDir: string,\n ): string {\n const waiting = this.#approvals.get(label);\n if (waiting) return waiting;\n const approval = identity.startSessionApproval({ dataDir, label });\n const message =\n `This MCP client acts for your Renown login, and its session \"${label}\" needs your approval once: ` +\n `open ${approval.url}, approve it with your wallet, then call the tool again.`;\n this.#approvals.set(label, message);\n void import(\"@renown/sdk/node\")\n .then(({ openBrowser }) => openBrowser(approval.url))\n .catch(() => {});\n void identity\n .pollSessionApproval({\n approval,\n timeoutMs: APPROVAL_WAIT_MS,\n target: { dataDir },\n })\n .then((outcome) => {\n if (outcome.status === \"ready\") {\n console.error(`[ph mcp] ${label} approved for ${outcome.address}`);\n }\n })\n .catch((error: unknown) =>\n console.error(\n `[ph mcp] the approval of ${label} failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n )\n .finally(() => this.#approvals.delete(label));\n return message;\n }\n\n async close(): Promise<void> {\n const models = this.#models;\n this.#models = undefined;\n await (await models)?.close();\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 run dev` 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 signed = projectDir ? new SignedTools(projectDir) : undefined;\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 if (signed && SIGNED_TOOLS.has(request.params.name)) {\n const answer = await signed.call(\n request.params,\n mcpSessionLabel(server.getClientVersion()?.name),\n await upstream.switchboard(onProgress),\n extra.signal,\n );\n if (\"result\" in answer) return answer.result;\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 const exit = () => {\n void (signed?.close() ?? Promise.resolve())\n .catch(() => {})\n .finally(() => process.exit(0));\n };\n transport.onclose = exit;\n process.stdin.once(\"end\", exit);\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA0CA,MAAM,kBAAk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rC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,MAAM,aAAa;EACjB,CAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,EAAA,CACtC,YAAY,CAAC,CAAC,CAAC,CACf,cAAc,QAAQ,KAAK,CAAC,CAAC;CAClC;CACA,UAAU,UAAU;CACpB,QAAQ,MAAM,KAAK,OAAO,IAAI;CAC9B,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"4842d577-7fb4-5bf9-8853-ddeba294b81f"}
1
+ {"version":3,"file":"mcp-Cx2HhCsK.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 type { LocalDocumentModels } from \"@powerhousedao/reactor-mcp/remote\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport { identityDataDir } from \"@powerhousedao/shared/clis/identity\";\nimport type * as RenownIdentity from \"@renown/sdk/identity\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n ensureVetra,\n restartVetra,\n currentPhCliRunVetraCommand,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launcher.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 {@link currentPhCliRunVetraCommand}. */\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 dev stack (its Switchboard and Connect, what `ph dev` runs) and wait until it is ready. \" +\n \"Use it after a change the stack reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Connect 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 /** That Vetra's record, for its Switchboard's GraphQL endpoint. */\n #record: VetraRuntimeRecord | 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 /** The running Vetra's Switchboard GraphQL endpoint, starting Vetra when it is down. */\n async switchboard(onProgress?: Progress): Promise<string> {\n await this.get(onProgress);\n return vetraUrls(this.#record!).switchboardUrl;\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:\n this.options.vetraCommand ?? currentPhCliRunVetraCommand(projectDir),\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 this.#record = record;\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/** The tools that write: they run here, signed and borne as the MCP client's session. */\nexport const SIGNED_TOOLS: ReadonlySet<string> = new Set([\n \"createDocument\",\n \"addActions\",\n \"deleteDocument\",\n]);\n\n/** What an MCP client's session is called, and its credential signs. */\nexport function mcpSessionLabel(clientName: string | undefined): string {\n return `mcp ${clientName?.trim() || \"client\"}`;\n}\n\n/** How long a Renown approval of a session is waited for. */\nconst APPROVAL_WAIT_MS = 10 * 60_000;\n\ntype Answer = { result: CallToolResult } | { forward: true };\n\n/**\n * The writing tools, run in this process over the project's Switchboard,\n * every action signed and every request borne as the MCP client's own\n * session (`mcp <client>`), kept in the project's data folder with its\n * credential's record: the pseudonym's, issued at the first write, or one a\n * Renown login approves once at Renown's console. A call that needs a model\n * this process does not hold, before it wrote anything, goes to the host's\n * `/mcp` instead, which signs its writes itself.\n */\nclass SignedTools {\n #models: Promise<LocalDocumentModels> | undefined;\n /** The console approvals waited for, by session label. */\n #approvals = new Map<string, string>();\n\n constructor(private readonly projectDir: string) {}\n\n #localModels(): Promise<LocalDocumentModels> {\n this.#models ??= import(\"@powerhousedao/reactor-mcp/remote\").then(\n ({ localDocumentModels }) =>\n localDocumentModels(this.projectDir, {\n onError: (error) =>\n console.error(\n `[ph mcp] the project's document models did not load: ${error instanceof Error ? error.message : String(error)}`,\n ),\n }),\n );\n return this.#models;\n }\n\n async call(\n params: CallToolRequest[\"params\"],\n label: string,\n graphqlUrl: string,\n signal: AbortSignal,\n ): Promise<Answer> {\n const identity = await import(\"@renown/sdk/identity\");\n const dataDir = identityDataDir(this.projectDir);\n let session: Awaited<ReturnType<typeof identity.openSession>>;\n try {\n session = await identity.openSession({\n dataDir,\n label,\n place: \"data-folder\",\n interactive: false,\n target: { dataDir },\n // A client that acts by itself stays withdrawn where it was withdrawn.\n reissueWithdrawn: false,\n });\n } catch (error) {\n if (error instanceof identity.SessionApprovalRequiredError) {\n return { result: toolError(this.#approve(identity, label, dataDir)) };\n }\n throw error;\n }\n const [{ createRemoteServer }, { GraphQLReactorClient }, models] =\n await Promise.all([\n import(\"@powerhousedao/reactor-mcp/remote\"),\n import(\"@powerhousedao/reactor-browser/graphql-client\"),\n this.#localModels(),\n ]);\n const client = new GraphQLReactorClient({\n url: graphqlUrl,\n documentModels: () => models.current(),\n signer: session.actionSigner,\n tokenProvider: () => session.bearer(),\n realtime: false,\n });\n const seen = { missing: false, wrote: false };\n const server = createRemoteServer({\n client,\n documentModels: () => models.current(),\n onMissingModel: () => {\n seen.missing = true;\n },\n onWrite: () => {\n seen.wrote = true;\n },\n });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n const local = new Client({ name: \"ph-mcp\", version: getVersion() });\n try {\n await server.connect(serverSide);\n await local.connect(clientSide);\n const result = (await local.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n )) as CallToolResult;\n if (result.isError && seen.missing && !seen.wrote) {\n return { forward: true };\n }\n return { result };\n } finally {\n client.dispose();\n await local.close().catch(() => {});\n await server.close().catch(() => {});\n }\n }\n\n /** Starts, once per session, the approval a Renown login gives at the console. */\n #approve(\n identity: typeof RenownIdentity,\n label: string,\n dataDir: string,\n ): string {\n const waiting = this.#approvals.get(label);\n if (waiting) return waiting;\n const approval = identity.startSessionApproval({ dataDir, label });\n const message =\n `This MCP client acts for your Renown login, and its session \"${label}\" needs your approval once: ` +\n `open ${approval.url}, approve it with your wallet, then call the tool again.`;\n this.#approvals.set(label, message);\n void import(\"@renown/sdk/node\")\n .then(({ openBrowser }) => openBrowser(approval.url))\n .catch(() => {});\n void identity\n .pollSessionApproval({\n approval,\n timeoutMs: APPROVAL_WAIT_MS,\n target: { dataDir },\n })\n .then((outcome) => {\n if (outcome.status === \"ready\") {\n console.error(`[ph mcp] ${label} approved for ${outcome.address}`);\n }\n })\n .catch((error: unknown) =>\n console.error(\n `[ph mcp] the approval of ${label} failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n )\n .finally(() => this.#approvals.delete(label));\n return message;\n }\n\n async close(): Promise<void> {\n const models = this.#models;\n this.#models = undefined;\n await (await models)?.close();\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 run dev` 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 signed = projectDir ? new SignedTools(projectDir) : undefined;\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 if (signed && SIGNED_TOOLS.has(request.params.name)) {\n const answer = await signed.call(\n request.params,\n mcpSessionLabel(server.getClientVersion()?.name),\n await upstream.switchboard(onProgress),\n extra.signal,\n );\n if (\"result\" in answer) return answer.result;\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 const exit = () => {\n void (signed?.close() ?? Promise.resolve())\n .catch(() => {})\n .finally(() => process.exit(0));\n };\n transport.onclose = exit;\n process.stdin.once(\"end\", exit);\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA0CA,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,y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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,IAAI,UAAU,aAAa,IAAI,QAAQ,OAAO,IAAI,GAAG;IACnD,MAAM,SAAS,MAAM,OAAO,KAC1B,QAAQ,QACR,gBAAgB,OAAO,iBAAiB,CAAC,EAAE,IAAI,GAC/C,MAAM,SAAS,YAAY,UAAU,GACrC,MAAM,MACR;IACA,IAAI,YAAY,QAAQ,OAAO,OAAO;GACxC;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,MAAM,aAAa;EACjB,CAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,EAAA,CACtC,YAAY,CAAC,CAAC,CAAC,CACf,cAAc,QAAQ,KAAK,CAAC,CAAC;CAClC;CACA,UAAU,UAAU;CACpB,QAAQ,MAAM,KAAK,OAAO,IAAI;CAC9B,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"117843b5-8007-55ed-b766-ea7ab7956938"}
@@ -1,7 +1,7 @@
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]="f0ae58e6-c5a6-55b9-b978-887a260c4b9e")}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]="64e7dafd-158f-5afd-94a4-ef8f12e7d927")}catch(e){}}();
3
3
  import { i as findNodeProjectRoot, s as isPowerhouseProject } from "./utils-D5VlY5AZ.mjs";
4
- import { n as unifiedDiff } from "./migrate-subgraphs-BUgTeHcm.mjs";
4
+ import { n as unifiedDiff } from "./migrate-subgraphs-Dw5UFCQ3.mjs";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { dirname, join, relative } from "node:path";
7
7
  import { execSync } from "node:child_process";
@@ -205,5 +205,5 @@ async function startMigrate({ versionPositional, version, force, debug, dryRun }
205
205
  //#endregion
206
206
  export { startMigrate };
207
207
 
208
- //# sourceMappingURL=migrate-BaWZhorc.mjs.map
209
- //# debugId=f0ae58e6-c5a6-55b9-b978-887a260c4b9e
208
+ //# sourceMappingURL=migrate-BzPAS4zM.mjs.map
209
+ //# debugId=64e7dafd-158f-5afd-94a4-ef8f12e7d927