@powerhousedao/ph-cli 6.4.0-next.0 → 6.4.0-next.1

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 (87) hide show
  1. package/README.md +1 -1
  2. package/dist/{build-D8_USaRh.mjs → build-C490lBnu.mjs} +7 -7
  3. package/dist/{build-D8_USaRh.mjs.map → build-C490lBnu.mjs.map} +1 -1
  4. package/dist/build-DblrRe4z.mjs +4 -0
  5. package/dist/{check-_K6EAsag.mjs → check-D84ta1Dh.mjs} +4 -4
  6. package/dist/{check-_K6EAsag.mjs.map → check-D84ta1Dh.mjs.map} +1 -1
  7. package/dist/{check-EpzhIKt1.mjs → check-DIK1LTss.mjs} +5 -5
  8. package/dist/{check-EpzhIKt1.mjs.map → check-DIK1LTss.mjs.map} +1 -1
  9. package/dist/{check-CVRb-CJD.mjs → check-F3nwJiG-.mjs} +3 -3
  10. package/dist/{cli-connect-override-DwlViDdp.mjs → cli-connect-override-BMU4Qldg.mjs} +7 -7
  11. package/dist/cli-connect-override-BMU4Qldg.mjs.map +1 -0
  12. package/dist/cli.mjs +14 -8
  13. package/dist/cli.mjs.map +1 -1
  14. package/dist/{compound-n-bO0qKh-Dx7fgKWx.mjs → compound-BWLJ0KBw-8hKyrfjG.mjs} +7 -7
  15. package/dist/compound-BWLJ0KBw-8hKyrfjG.mjs.map +1 -0
  16. package/dist/{connect-build-BIkm5fcG.mjs → connect-build-DW1fFVbU.mjs} +6 -6
  17. package/dist/{connect-build-BIkm5fcG.mjs.map → connect-build-DW1fFVbU.mjs.map} +1 -1
  18. package/dist/{connect-config-CH0KQqyU.mjs → connect-config-DVubBBLb.mjs} +4 -4
  19. package/dist/{connect-config-CH0KQqyU.mjs.map → connect-config-DVubBBLb.mjs.map} +1 -1
  20. package/dist/{connect-studio-C-9WE2Bg.mjs → connect-studio-CQC-LDSg.mjs} +4 -4
  21. package/dist/{connect-studio-C-9WE2Bg.mjs.map → connect-studio-CQC-LDSg.mjs.map} +1 -1
  22. package/dist/definitions-worker.mjs +1 -1
  23. package/dist/{dist-Dbvm_SmC.mjs → dist-BFMRL5C0.mjs} +5 -5
  24. package/dist/{dist-Dbvm_SmC.mjs.map → dist-BFMRL5C0.mjs.map} +1 -1
  25. package/dist/{explain-DB7uoJkY.mjs → explain-YPD3n6t8.mjs} +5 -5
  26. package/dist/{explain-DB7uoJkY.mjs.map → explain-YPD3n6t8.mjs.map} +1 -1
  27. package/dist/{export-DuYGBuQZ.mjs → export-DjQL6zkr.mjs} +5 -5
  28. package/dist/{export-DuYGBuQZ.mjs.map → export-DjQL6zkr.mjs.map} +1 -1
  29. package/dist/{generate-all-Mj_xGZZN.mjs → generate-all-BLot_H9Z.mjs} +4 -4
  30. package/dist/{generate-all-Mj_xGZZN.mjs.map → generate-all-BLot_H9Z.mjs.map} +1 -1
  31. package/dist/{generate-desktop-shell-DD9o4Rcl.mjs → generate-desktop-shell-CTrfzM9P.mjs} +4 -4
  32. package/dist/{generate-desktop-shell-DD9o4Rcl.mjs.map → generate-desktop-shell-CTrfzM9P.mjs.map} +1 -1
  33. package/dist/{get-version-DXnnvS_S.mjs → get-version-CcYVboCW.mjs} +4 -4
  34. package/dist/{get-version-DXnnvS_S.mjs.map → get-version-CcYVboCW.mjs.map} +1 -1
  35. package/dist/{index-V7TKBh-y.d.mts → index-D3H9pQ8u.d.mts} +2 -2
  36. package/dist/{index-V7TKBh-y.d.mts.map → index-D3H9pQ8u.d.mts.map} +1 -1
  37. package/dist/{init-Ltg4cJzm.mjs → init-IQ0VS0JK.mjs} +4 -4
  38. package/dist/{init-Ltg4cJzm.mjs.map → init-IQ0VS0JK.mjs.map} +1 -1
  39. package/dist/{mcp-DKqOFZlX.mjs → mcp-B3l1mtBq.mjs} +6 -6
  40. package/dist/{mcp-DKqOFZlX.mjs.map → mcp-B3l1mtBq.mjs.map} +1 -1
  41. package/dist/{migrate-CQpwBF1l.mjs → migrate-CzcBEypc.mjs} +5 -5
  42. package/dist/{migrate-CQpwBF1l.mjs.map → migrate-CzcBEypc.mjs.map} +1 -1
  43. package/dist/{migrate-document-models-DpXzLDuu.mjs → migrate-document-models-D0HSo4WN.mjs} +4 -4
  44. package/dist/{migrate-document-models-DpXzLDuu.mjs.map → migrate-document-models-D0HSo4WN.mjs.map} +1 -1
  45. package/dist/{migrate-subgraphs-CdfkO6l9.mjs → migrate-subgraphs-CfSMlcJD.mjs} +6 -6
  46. package/dist/{migrate-subgraphs-CdfkO6l9.mjs.map → migrate-subgraphs-CfSMlcJD.mjs.map} +1 -1
  47. package/dist/migrate-subgraphs-Hc5w9Mpk.mjs +4 -0
  48. package/dist/{ph-cli-commands-Dq-tIYhy.mjs → ph-cli-commands-CQXdWQ74.mjs} +39 -19
  49. package/dist/ph-cli-commands-CQXdWQ74.mjs.map +1 -0
  50. package/dist/ph-cli-commands-YE0ciOSX.mjs +4 -0
  51. package/dist/{run-sugar-Bnab2Z3f.mjs → run-sugar-BfnRBv7h.mjs} +3 -3
  52. package/dist/{run-sugar-DsG2RRgx.mjs → run-sugar-hGKprsKz.mjs} +22 -15
  53. package/dist/run-sugar-hGKprsKz.mjs.map +1 -0
  54. package/dist/runners/connect.d.mts +1 -1
  55. package/dist/runners/connect.mjs +4 -4
  56. package/dist/runners/connect.mjs.map +1 -1
  57. package/dist/runners/switchboard.d.mts +1 -1
  58. package/dist/runners/switchboard.mjs +4 -4
  59. package/dist/scripts/generate-commands-docs.ts +2 -0
  60. package/dist/{sugar-checks-DBk5q_uJ.mjs → sugar-checks-CTCsK5DJ.mjs} +11 -11
  61. package/dist/sugar-checks-CTCsK5DJ.mjs.map +1 -0
  62. package/dist/{switchboard-reset-CY6J0lWO.mjs → switchboard-reset-BP7KwUc_.mjs} +4 -4
  63. package/dist/{switchboard-reset-CY6J0lWO.mjs.map → switchboard-reset-BP7KwUc_.mjs.map} +1 -1
  64. package/dist/{verify-C_fL8YsF.mjs → verify-NK6a_7j8.mjs} +4 -4
  65. package/dist/{verify-C_fL8YsF.mjs.map → verify-NK6a_7j8.mjs.map} +1 -1
  66. package/dist/vetra-gateway-Bpe50oGk.mjs +4 -0
  67. package/dist/vetra-gateway-BxcduYAI.mjs +173 -0
  68. package/dist/vetra-gateway-BxcduYAI.mjs.map +1 -0
  69. package/dist/{vetra-host-CDfny6E8.mjs → vetra-host-BrLdIMRP.mjs} +7 -7
  70. package/dist/vetra-host-BrLdIMRP.mjs.map +1 -0
  71. package/dist/{vetra-instance-DlXAeiU7.mjs → vetra-instance-CPNIsaxh.mjs} +5 -5
  72. package/dist/vetra-instance-CPNIsaxh.mjs.map +1 -0
  73. package/dist/vetra-launcher-BtDWQBuh.mjs +4 -0
  74. package/dist/{vetra-launcher-CYX10K2m.mjs → vetra-launcher-Dokr1aDK.mjs} +5 -5
  75. package/dist/{vetra-launcher-CYX10K2m.mjs.map → vetra-launcher-Dokr1aDK.mjs.map} +1 -1
  76. package/package.json +16 -16
  77. package/dist/build-FVWjguYr.mjs +0 -4
  78. package/dist/cli-connect-override-DwlViDdp.mjs.map +0 -1
  79. package/dist/compound-n-bO0qKh-Dx7fgKWx.mjs.map +0 -1
  80. package/dist/migrate-subgraphs-CoUuwzmR.mjs +0 -4
  81. package/dist/ph-cli-commands-Daeqh5Me.mjs +0 -4
  82. package/dist/ph-cli-commands-Dq-tIYhy.mjs.map +0 -1
  83. package/dist/run-sugar-DsG2RRgx.mjs.map +0 -1
  84. package/dist/sugar-checks-DBk5q_uJ.mjs.map +0 -1
  85. package/dist/vetra-host-CDfny6E8.mjs.map +0 -1
  86. package/dist/vetra-instance-DlXAeiU7.mjs.map +0 -1
  87. package/dist/vetra-launcher-TDLXj0tY.mjs +0 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sugar-checks-CTCsK5DJ.mjs","sources":["../src/utils/sugar-checks.ts"],"sourcesContent":["import {\n loadHost,\n probeHostsFolder,\n withoutHostsMessage,\n type RunnerArgsSchema,\n} from \"@powerhousedao/host-core\";\nimport {\n DEPRECATIONS_REMOVED_IN,\n MIGRATION_GUIDE_URL,\n} from \"@powerhousedao/shared/clis/deprecations\";\nimport { CONNECT_VERBS, HOST_COMMANDS, type SugarHost } from \"./run-sugar.js\";\n\n/**\n * What `ph dev`, `ph connect` and `ph switchboard` are refused for, before\n * they become `ph run <host>` (run-sugar.ts): a project without the host\n * file, and the flags of the commands they once were that `ph run` has no\n * argument for. `ph run` is not checked here, nor is any other host name: a\n * runner refuses the arguments it does not know itself. Nor are the flags of\n * a host on a runner of its own: they are checked against the stock runners.\n */\n\n/** `ph switchboard` flags that are verbs of the host. */\nconst SWITCHBOARD_VERB_FLAGS: Readonly<Record<string, string>> = {\n \"--migrate\": \"migrate\",\n \"--migrate-status\": \"migrate-status\",\n \"--reset\": \"reset\",\n \"--dev\": \"dev\",\n};\n\n/** Read by the CLI itself, before any command. */\nconst CLI_FLAGS = new Set([\"--debug\"]);\n\n/** The runner argument schemas the flags are checked against. */\nexport interface SugarArgSchemas {\n switchboard: RunnerArgsSchema;\n connect: RunnerArgsSchema;\n}\n\ninterface SugarInvocation {\n /** As typed: `ph connect build`. */\n typed: string;\n /** The host it runs. */\n host: SugarHost;\n /** What it is sugar for: `ph run <host> [verb]`. */\n replacement: string;\n /** The flags passed, by name, without their values. */\n flags: string[];\n}\n\nfunction sugarInvocation(args: readonly string[]): SugarInvocation | undefined {\n const [command, ...rest] = args;\n if (command === undefined || !Object.hasOwn(HOST_COMMANDS, command)) {\n return undefined;\n }\n if (rest.some((arg) => arg === \"--help\" || arg === \"-h\")) return undefined;\n const flags = [\n ...new Set(\n rest\n .filter((arg) => arg.startsWith(\"-\") && arg !== \"--\")\n .map((arg) => arg.split(\"=\")[0]),\n ),\n ].filter((name) => !CLI_FLAGS.has(name));\n // A word right after the command is the subcommand or the verb.\n const word =\n rest.length > 0 && !rest[0].startsWith(\"-\") ? rest[0] : undefined;\n if (command === \"connect\") {\n // `ph connect config` reads and writes the config: a tool, not a host.\n if (word === \"config\") return undefined;\n const verb =\n word === undefined\n ? CONNECT_VERBS.studio\n : Object.hasOwn(CONNECT_VERBS, word)\n ? CONNECT_VERBS[word]\n : word;\n return {\n typed: word ? `ph connect ${word}` : \"ph connect\",\n host: \"connect\",\n replacement: `ph run connect ${verb}`,\n flags,\n };\n }\n // `ph dev` runs hosts/vetra.\n const host = HOST_COMMANDS[command];\n return {\n typed: word ? `ph ${command} ${word}` : `ph ${command}`,\n host,\n replacement: word ? `ph run ${host} ${word}` : `ph run ${host}`,\n flags,\n };\n}\n\n/**\n * `ph reactor` was an alias of `ph switchboard`. It is gone, unless the\n * project names a host of its own that.\n */\nfunction removedAliasError(\n args: readonly string[],\n projectRoot: string,\n): string | undefined {\n if (args[0] !== \"reactor\") return undefined;\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind === \"present\" && probe.hosts.includes(\"reactor\")) {\n return undefined;\n }\n return (\n `\\`ph reactor\\` was removed in ${DEPRECATIONS_REMOVED_IN}. ` +\n \"Use `ph switchboard` or `ph run switchboard` instead.\"\n );\n}\n\n/**\n * Why the command cannot run in this project: it has no hosts (the wording\n * of `ph run`, naming `ph migrate`), or it has hosts and not this one.\n * Undefined for anything else, for help, and for a project with the host.\n */\nexport function withoutHostError(\n args: readonly string[],\n projectRoot: string,\n): string | undefined {\n const invocation = sugarInvocation(args);\n if (!invocation) return undefined;\n const { typed, host } = invocation;\n const probe = probeHostsFolder(projectRoot);\n if (probe.kind !== \"present\") {\n return withoutHostsMessage(probe, `\\`${typed}\\``);\n }\n if (probe.hosts.includes(host)) return undefined;\n // `ph migrate` adds the hosts to a project that has none, and only then.\n return (\n `This project has no hosts/${host}/host.js, so \\`${typed}\\` cannot run. ` +\n `\\`ph migrate\\` adds the host files to a project without hosts only: add hosts/${host}/host.js to this one. ` +\n `See ${MIGRATION_GUIDE_URL}`\n );\n}\n\n/**\n * The flags `ph run <host>` has no argument for, as one error. A flag the\n * runner takes passes, under its member name for `ph dev`\n * (`--switchboard-port`); a flag the runner retired passes too, and the\n * runner says so. Undefined when every flag passes.\n */\nexport function removedFlagsError(\n args: readonly string[],\n schemas: SugarArgSchemas,\n): string | undefined {\n const invocation = sugarInvocation(args);\n if (!invocation) return undefined;\n const { typed, host, replacement } = invocation;\n // A compound hands each member its arguments; a member option goes by its\n // member name there (`--switchboard-port`), never by its plain one.\n const members =\n host === \"vetra\" ? [schemas.switchboard, schemas.connect] : [schemas[host]];\n const scoped = new Set(\n members.flatMap((schema) => Object.values(schema.memberOptions ?? {})),\n );\n const accepts = (name: string): boolean =>\n host === \"vetra\"\n ? // `ph run vetra` takes --restart itself (vetra-host.ts).\n name === \"--restart\" ||\n members.some(\n (schema) =>\n schema.memberOptions?.[name] !== undefined ||\n (!scoped.has(name) &&\n [...schema.options, ...schema.flags].includes(name)),\n )\n : [...members[0].options, ...members[0].flags].includes(name);\n const errors: string[] = [];\n const unsupported: string[] = [];\n for (const name of invocation.flags) {\n const verb =\n host === \"switchboard\" ? SWITCHBOARD_VERB_FLAGS[name] : undefined;\n const retired = members.some(\n (schema) => schema.retired?.[name] !== undefined,\n );\n if (verb !== undefined) {\n errors.push(\n `\\`${typed} ${name}\\` was removed in ${DEPRECATIONS_REMOVED_IN}. Use \\`ph run switchboard ${verb}\\` instead.`,\n );\n } else if (accepts(name) || retired) {\n continue;\n } else {\n unsupported.push(name);\n }\n }\n if (unsupported.length > 0) {\n const one = unsupported.length === 1;\n const subject = one\n ? `\\`${typed} ${unsupported[0]}\\` was removed in ${DEPRECATIONS_REMOVED_IN}: \\`${replacement}\\` has no such argument.`\n : `The \\`${typed}\\` flags ${unsupported.join(\", \")} were removed in ${DEPRECATIONS_REMOVED_IN}: \\`${replacement}\\` has no such arguments.`;\n errors.push(\n `${subject} Set what ${one ? \"it configures\" : \"they configure\"} in the host files under hosts/ instead. ` +\n `See ${MIGRATION_GUIDE_URL}`,\n );\n }\n return errors.length > 0 ? errors.join(\"\\n\") : undefined;\n}\n\n/** The runners the scaffold's hosts name, whose schemas the flags are\n * checked against. ph-cli's are the ph-run ones, re-exported. */\nconst STOCK_RUNNERS: Readonly<Record<string, readonly string[]>> = {\n connect: [\n \"@powerhousedao/ph-cli/runners/connect\",\n \"@powerhousedao/ph-run/runners/connect\",\n ],\n switchboard: [\n \"@powerhousedao/ph-cli/runners/switchboard\",\n \"@powerhousedao/ph-run/runners/switchboard\",\n ],\n};\nconst COMPOUND_RUNNER = \"@powerhousedao/host-core/runners/compound\";\n\nasync function runnerModuleOf(\n projectRoot: string,\n host: string,\n): Promise<{ module: string; children?: unknown } | undefined> {\n try {\n const { host: definition } = await loadHost(projectRoot, host);\n return {\n module: definition.runner.module,\n children: (definition as { children?: unknown }).children,\n };\n } catch {\n // `ph run` loads it next and says what is wrong with it.\n return undefined;\n }\n}\n\n/**\n * Whether the host runs the stock runner of its command: the connect or\n * switchboard runner, or for `ph dev` the compound over members that are\n * the project's connect and switchboard hosts, each on its stock runner.\n * Anything else has arguments of its own, which its runner checks.\n */\nexport async function runsStockRunner(\n projectRoot: string,\n host: SugarHost,\n): Promise<boolean> {\n const loaded = await runnerModuleOf(projectRoot, host);\n if (!loaded) return false;\n if (host !== \"vetra\") return STOCK_RUNNERS[host].includes(loaded.module);\n if (loaded.module !== COMPOUND_RUNNER) return false;\n const children = loaded.children;\n if (typeof children !== \"object\" || children === null) return false;\n const members = new Set<string>();\n for (const child of Object.values(children as Record<string, unknown>)) {\n const { host: member, runner } = (child ?? {}) as {\n host?: unknown;\n runner?: { module?: unknown };\n };\n if (typeof member !== \"string\" || !Object.hasOwn(STOCK_RUNNERS, member)) {\n return false;\n }\n // A member that names a runner module is not on its sibling's.\n if (runner?.module !== undefined) return false;\n members.add(member);\n }\n for (const member of members) {\n const sibling = await runnerModuleOf(projectRoot, member);\n if (!sibling || !STOCK_RUNNERS[member].includes(sibling.module)) {\n return false;\n }\n }\n return true;\n}\n\nasync function loadArgSchemas(): Promise<SugarArgSchemas | undefined> {\n try {\n const [switchboard, connect] = await Promise.all([\n import(\"@powerhousedao/ph-run/runners/switchboard\"),\n import(\"@powerhousedao/ph-run/runners/connect\"),\n ]);\n return {\n switchboard: switchboard.argsSchema,\n connect: connect.argsSchema,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Run by the CLI on the command line as typed, before the host sugar: the\n * error the invocation ends with, if any. `args` is untouched either way.\n */\nexport async function sugarError(\n args: readonly string[],\n projectRoot: string,\n): Promise<string | undefined> {\n const removed = removedAliasError(args, projectRoot);\n if (removed !== undefined) return removed;\n const withoutHost = withoutHostError(args, projectRoot);\n if (withoutHost !== undefined) return withoutHost;\n const invocation = sugarInvocation(args);\n if (!invocation || invocation.flags.length === 0) return undefined;\n // A runner of the project's own takes the arguments it declares.\n if (!(await runsStockRunner(projectRoot, invocation.host))) return undefined;\n // Without the schemas the runner still refuses what it does not accept.\n const schemas = await loadArgSchemas();\n return schemas ? removedFlagsError(args, schemas) : undefined;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,yBAA2D;CAC/D,aAAa;CACb,oBAAoB;CACpB,WAAW;CACX,SAAS;AACX;;AAGA,MAAM,4BAAY,IAAI,IAAI,CAAC,SAAS,CAAC;AAmBrC,SAAS,gBAAgB,MAAsD;CAC7E,MAAM,CAAC,SAAS,GAAG,QAAQ;CAC3B,IAAI,YAAY,KAAA,KAAa,CAAC,OAAO,OAAO,eAAe,OAAO,GAChE;CAEF,IAAI,KAAK,MAAM,QAAQ,QAAQ,YAAY,QAAQ,IAAI,GAAG,OAAO,KAAA;CACjE,MAAM,QAAQ,CACZ,GAAG,IAAI,IACL,KACG,QAAQ,QAAQ,IAAI,WAAW,GAAG,KAAK,QAAQ,IAAI,CAAC,CACpD,KAAK,QAAQ,IAAI,MAAM,GAAG,CAAC,CAAC,EAAE,CACnC,CACF,CAAC,CAAC,QAAQ,SAAS,CAAC,UAAU,IAAI,IAAI,CAAC;CAEvC,MAAM,OACJ,KAAK,SAAS,KAAK,CAAC,KAAK,EAAE,CAAC,WAAW,GAAG,IAAI,KAAK,KAAK,KAAA;CAC1D,I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MAAM,WAAW;CACtD,IAAI,gBAAgB,KAAA,GAAW,OAAO;CACtC,MAAM,aAAa,gBAAgB,IAAI;CACvC,IAAI,CAAC,cAAc,WAAW,MAAM,WAAW,GAAG,OAAO,KAAA;CAEzD,IAAI,CAAE,MAAM,gBAAgB,aAAa,WAAW,IAAI,GAAI,OAAO,KAAA;CAEnE,MAAM,UAAU,MAAM,eAAe;CACrC,OAAO,UAAU,kBAAkB,MAAM,OAAO,IAAI,KAAA;AACtD","debug_id":"c2e3e5f7-c34e-5af7-ba98-23479b2072b3"}
@@ -1,8 +1,8 @@
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]="a911ad59-3916-5198-86c1-17183904ce37")}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]="c6d177bb-1a46-5191-9fe0-d41f393b02ba")}catch(e){}}();
3
3
  import { promises } from "node:fs";
4
- import { cyan, green, red, yellow } from "colorette";
5
4
  import { defaultStoreDirs } from "@powerhousedao/shared/clis/ph-dir";
5
+ import { cyan, green, red, yellow } from "colorette";
6
6
  //#region src/services/switchboard-reset.ts
7
7
  const CONFIRMATION_TOKEN = "reset";
8
8
  function isPostgresUrl(url) {
@@ -85,5 +85,5 @@ async function resetSwitchboardDatabase(options) {
85
85
  //#endregion
86
86
  export { resetSwitchboardDatabase };
87
87
 
88
- //# sourceMappingURL=switchboard-reset-CY6J0lWO.mjs.map
89
- //# debugId=a911ad59-3916-5198-86c1-17183904ce37
88
+ //# sourceMappingURL=switchboard-reset-BP7KwUc_.mjs.map
89
+ //# debugId=c6d177bb-1a46-5191-9fe0-d41f393b02ba
@@ -1 +1 @@
1
- {"version":3,"file":"switchboard-reset-CY6J0lWO.mjs","sources":["../src/services/switchboard-reset.ts"],"sourcesContent":["import { defaultStoreDirs } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { yellow, red, green, cyan } from \"colorette\";\nimport { promises as fs } from \"node:fs\";\n\nexport interface ResetSwitchboardOptions {\n dbPath?: string;\n yes?: boolean;\n}\n\nexport interface ResolvedResetPaths {\n reactorDir: string | null;\n readModelDir: string | null;\n postgresUrl: string | null;\n}\n\nconst CONFIRMATION_TOKEN = \"reset\";\n\nexport function isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\n/**\n * Resolves the on-disk PGlite directories that `--reset` would delete.\n * Mirrors the resolution in apps/switchboard/src/server.mts so we touch the\n * same paths the running switchboard uses. When a Postgres URL is configured\n * the corresponding directory is null and `postgresUrl` is populated so the\n * caller can refuse.\n */\nexport function resolveResetPaths(\n options: ResetSwitchboardOptions,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedResetPaths {\n const defaults = defaultStoreDirs(env);\n const readModelDbPath =\n options.dbPath ?? env.DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL;\n const readModelPath = readModelDbPath || defaults.readModel;\n const reactorDbUrl =\n options.dbPath ??\n env.PH_REACTOR_DATABASE_URL ??\n env.PH_SWITCHBOARD_DATABASE_URL;\n const reactorPath = reactorDbUrl || defaults.reactor;\n\n const reactorIsPostgres = !!reactorDbUrl && isPostgresUrl(reactorDbUrl);\n const readModelIsPostgres =\n !!readModelDbPath && isPostgresUrl(readModelDbPath);\n\n let postgresUrl: string | null = null;\n if (reactorIsPostgres) postgresUrl = reactorDbUrl as string;\n else if (readModelIsPostgres) postgresUrl = readModelDbPath as string;\n\n return {\n reactorDir: reactorIsPostgres ? null : reactorPath,\n readModelDir: readModelIsPostgres ? null : readModelPath,\n postgresUrl,\n };\n}\n\nasync function promptForConfirmation(): Promise<boolean> {\n const enquirer = await import(\"enquirer\");\n try {\n const answer = await enquirer.default.prompt<{ confirmation: string }>({\n type: \"input\",\n name: \"confirmation\",\n message: `Type \"${CONFIRMATION_TOKEN}\" to confirm wiping the local switchboard databases:`,\n });\n return answer.confirmation.trim() === CONFIRMATION_TOKEN;\n } catch {\n return false;\n }\n}\n\nexport async function resetSwitchboardDatabase(\n options: ResetSwitchboardOptions,\n): Promise<void> {\n const paths = resolveResetPaths(options);\n\n if (paths.postgresUrl) {\n console.error(\n red(\n `Refusing to reset: a PostgreSQL URL is configured (${paths.postgresUrl}).`,\n ),\n );\n console.error(\n yellow(\n \"`ph run switchboard reset` only wipes the local PGlite stores. \" +\n \"To reset a Postgres-backed switchboard, drop/recreate the database manually.\",\n ),\n );\n process.exit(1);\n }\n\n const targets = [paths.reactorDir, paths.readModelDir].filter(\n (d): d is string => d !== null,\n );\n\n if (targets.length === 0) {\n console.error(red(\"No local PGlite directories resolved; nothing to do.\"));\n process.exit(1);\n }\n\n console.log(yellow(\"The following directories will be permanently deleted:\"));\n for (const dir of targets) {\n console.log(` - ${dir}`);\n }\n console.log(\n yellow(\n \"This will wipe all local switchboard state. Migrations will re-run on next `ph switchboard`.\",\n ),\n );\n\n let confirmed = false;\n if (options.yes) {\n confirmed = true;\n } else if (isInteractive()) {\n confirmed = await promptForConfirmation();\n } else {\n console.error(\n red(\n \"Refusing to reset in a non-interactive context without --yes. Re-run with --yes to confirm.\",\n ),\n );\n process.exit(1);\n }\n\n if (!confirmed) {\n console.error(red(\"Aborted: confirmation not provided.\"));\n process.exit(1);\n }\n\n for (const dir of targets) {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(cyan(`Removed ${dir}`));\n }\n\n console.log(\n green(\n \"Switchboard local storage reset. Run `ph switchboard` to re-initialize.\",\n ),\n );\n}\n"],"names":["fs"],"mappings":";;;;;;AAeA,MAAM,qBAAqB;AAE3B,SAA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AAQ,MAAM,IAAI,sDAAsD,CAAC;EACzE,QAAQ,KAAK,CAAC;CAChB;CAEA,QAAQ,IAAI,OAAO,wDAAwD,CAAC;CAC5E,KAAK,MAAM,OAAO,SAChB,QAAQ,IAAI,OAAO,KAAK;CAE1B,QAAQ,IACN,OACE,8FACF,CACF;CAEA,IAAI,YAAY;CAChB,IAAI,QAAQ,KACV,YAAY;MACP,IAAI,cAAc,GACvB,YAAY,MAAM,sBAAsB;MACnC;EACL,QAAQ,MACN,IACE,6FACF,CACF;EACA,QAAQ,KAAK,CAAC;CAChB;CAEA,IAAI,CAAC,WAAW;EACd,QAAQ,MAAM,IAAI,qCAAqC,CAAC;EACxD,QAAQ,KAAK,CAAC;CAChB;CAEA,KAAK,MAAM,OAAO,SAAS;EACzB,MAAMA,SAAG,GAAG,KAAK;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EACjD,QAAQ,IAAI,KAAK,WAAW,KAAK,CAAC;CACpC;CAEA,QAAQ,IACN,MACE,yEACF,CACF;AACF","debug_id":"a911ad59-3916-5198-86c1-17183904ce37"}
1
+ {"version":3,"file":"switchboard-reset-BP7KwUc_.mjs","sources":["../src/services/switchboard-reset.ts"],"sourcesContent":["import { defaultStoreDirs } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { yellow, red, green, cyan } from \"colorette\";\nimport { promises as fs } from \"node:fs\";\n\nexport interface ResetSwitchboardOptions {\n dbPath?: string;\n yes?: boolean;\n}\n\nexport interface ResolvedResetPaths {\n reactorDir: string | null;\n readModelDir: string | null;\n postgresUrl: string | null;\n}\n\nconst CONFIRMATION_TOKEN = \"reset\";\n\nexport function isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\n/**\n * Resolves the on-disk PGlite directories that `--reset` would delete.\n * Mirrors the resolution in apps/switchboard/src/server.mts so we touch the\n * same paths the running switchboard uses. When a Postgres URL is configured\n * the corresponding directory is null and `postgresUrl` is populated so the\n * caller can refuse.\n */\nexport function resolveResetPaths(\n options: ResetSwitchboardOptions,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedResetPaths {\n const defaults = defaultStoreDirs(env);\n const readModelDbPath =\n options.dbPath ?? env.DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL;\n const readModelPath = readModelDbPath || defaults.readModel;\n const reactorDbUrl =\n options.dbPath ??\n env.PH_REACTOR_DATABASE_URL ??\n env.PH_SWITCHBOARD_DATABASE_URL;\n const reactorPath = reactorDbUrl || defaults.reactor;\n\n const reactorIsPostgres = !!reactorDbUrl && isPostgresUrl(reactorDbUrl);\n const readModelIsPostgres =\n !!readModelDbPath && isPostgresUrl(readModelDbPath);\n\n let postgresUrl: string | null = null;\n if (reactorIsPostgres) postgresUrl = reactorDbUrl as string;\n else if (readModelIsPostgres) postgresUrl = readModelDbPath as string;\n\n return {\n reactorDir: reactorIsPostgres ? null : reactorPath,\n readModelDir: readModelIsPostgres ? null : readModelPath,\n postgresUrl,\n };\n}\n\nasync function promptForConfirmation(): Promise<boolean> {\n const enquirer = await import(\"enquirer\");\n try {\n const answer = await enquirer.default.prompt<{ confirmation: string }>({\n type: \"input\",\n name: \"confirmation\",\n message: `Type \"${CONFIRMATION_TOKEN}\" to confirm wiping the local switchboard databases:`,\n });\n return answer.confirmation.trim() === CONFIRMATION_TOKEN;\n } catch {\n return false;\n }\n}\n\nexport async function resetSwitchboardDatabase(\n options: ResetSwitchboardOptions,\n): Promise<void> {\n const paths = resolveResetPaths(options);\n\n if (paths.postgresUrl) {\n console.error(\n red(\n `Refusing to reset: a PostgreSQL URL is configured (${paths.postgresUrl}).`,\n ),\n );\n console.error(\n yellow(\n \"`ph run switchboard reset` only wipes the local PGlite stores. \" +\n \"To reset a Postgres-backed switchboard, drop/recreate the database manually.\",\n ),\n );\n process.exit(1);\n }\n\n const targets = [paths.reactorDir, paths.readModelDir].filter(\n (d): d is string => d !== null,\n );\n\n if (targets.length === 0) {\n console.error(red(\"No local PGlite directories resolved; nothing to do.\"));\n process.exit(1);\n }\n\n console.log(yellow(\"The following directories will be permanently deleted:\"));\n for (const dir of targets) {\n console.log(` - ${dir}`);\n }\n console.log(\n yellow(\n \"This will wipe all local switchboard state. Migrations will re-run on next `ph switchboard`.\",\n ),\n );\n\n let confirmed = false;\n if (options.yes) {\n confirmed = true;\n } else if (isInteractive()) {\n confirmed = await promptForConfirmation();\n } else {\n console.error(\n red(\n \"Refusing to reset in a non-interactive context without --yes. Re-run with --yes to confirm.\",\n ),\n );\n process.exit(1);\n }\n\n if (!confirmed) {\n console.error(red(\"Aborted: confirmation not provided.\"));\n process.exit(1);\n }\n\n for (const dir of targets) {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(cyan(`Removed ${dir}`));\n }\n\n console.log(\n green(\n \"Switchboard local storage reset. Run `ph switchboard` to re-initialize.\",\n ),\n );\n}\n"],"names":["fs"],"mappings":";;;;;;AAeA,MAAM,qBAAqB;AAE3B,SAAgB,cAAc,KAAsB;CAClD,OAAO,IAAI,WAAW,eAAe,KAAK,IAAI,WAAW,aAAa;AACxE;AAEA,SAAS,gBAAyB;CAChC,OAAO,QAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC,QAAQ,IAAI;AACtD;;;;;;;;AASA,SAAgB,kBACd,SACA,MAAyB,QAAQ,KACb;CACpB,MAAM,WAAW,iBAAiB,GAAG;CACrC,MAAM,kBACJ,QAAQ,UAAU,IAAI,gBAAgB,IAAI;CAC5C,MAAM,gBAAgB,mBAAmB,SAAS;CAClD,MAAM,eACJ,QAAQ,UACR,IAAI,2BACJ,IAAI;CACN,MAAM,cAAc,gBAAgB,SAAS;CAE7C,MAAM,oBAAoB,CAAC,CAAC,gBAAgB,cAAc,YAAY;CACtE,MAAM,sBACJ,CAAC,CAAC,mBAAmB,cAAc,eAAe;CAEpD,IAAI,cAA6B;CACjC,IAAI,mBAAmB,cAAc;MAChC,IAAI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CAAC;CACpC;CAEA,QAAQ,IACN,MACE,yEACF,CACF;AACF","debug_id":"c6d177bb-1a46-5191-9fe0-d41f393b02ba"}
@@ -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]="8841ab23-e9d1-5eea-b70a-058103b6e688")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-DXnnvS_S.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]="9c1bf72c-bcf7-512a-813a-8cfe96e6aa48")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-CcYVboCW.mjs";
4
4
  import { f as verifyReleaseApproval, i as revisionFiles, n as publishedFiles, o as packRelease, r as readReleaseApproval, s as packedDigests, u as decisionWithoutApproval } from "./files-D6_euBBn.mjs";
5
5
  //#region src/services/release/verify.ts
6
6
  /**
@@ -67,5 +67,5 @@ function checkApprovalBeforePublish(packageRoot, required) {
67
67
  //#endregion
68
68
  export { checkApprovalBeforePublish, renderReleaseDecision, verifyRelease };
69
69
 
70
- //# sourceMappingURL=verify-C_fL8YsF.mjs.map
71
- //# debugId=8841ab23-e9d1-5eea-b70a-058103b6e688
70
+ //# sourceMappingURL=verify-NK6a_7j8.mjs.map
71
+ //# debugId=9c1bf72c-bcf7-512a-813a-8cfe96e6aa48
@@ -1 +1 @@
1
- {"version":3,"file":"verify-C_fL8YsF.mjs","sources":["../src/services/release/verify.ts"],"sourcesContent":["import { getVersion } from \"../../get-version.js\";\nimport {\n type ApprovalRead,\n decisionWithoutApproval,\n type ReleaseDecision,\n verifyReleaseApproval,\n} from \"./approval.js\";\nimport { publishedFiles, readReleaseApproval, revisionFiles } from \"./files.js\";\nimport { packedDigests, packRelease, type PackedRelease } from \"./pack.js\";\nimport type { FileDigest } from \"./revision.js\";\n\n/**\n * Compares the package as it is now with its release approval: the files\n * the revision reads, with the output directory and exclusions the approval\n * records, and what `npm pack` publishes, or `published` when the caller\n * already packed it. Throws when either cannot be read.\n */\nexport function verifyRelease(\n packageRoot: string,\n read: ApprovalRead = readReleaseApproval(packageRoot),\n published?: readonly FileDigest[],\n): ReleaseDecision {\n if (read.kind !== \"found\") return decisionWithoutApproval(read);\n const { approval } = read;\n return verifyReleaseApproval(approval, {\n phCliVersion: getVersion(),\n files: revisionFiles(packageRoot, [\n approval.outDir,\n ...approval.packageRevision.excluded,\n ]),\n publishedFiles: published ?? publishedFiles(packageRoot),\n });\n}\n\nconst HEADLINES: Readonly<Record<ReleaseDecision[\"decision\"], string>> = {\n approved: \"the release approval matches this package\",\n missing: \"this package has no release approval\",\n unreadable: \"the release approval cannot be read\",\n stale: \"the release approval does not match this package\",\n refused: \"the release approval records a release check that did not pass\",\n};\n\n/** The decision and each reason on its own line. */\nexport function renderReleaseDecision(decision: ReleaseDecision): string {\n return [\n `${decision.decision}: ${HEADLINES[decision.decision]}`,\n ...decision.reasons.map((reason) => ` - ${reason}`),\n ].join(\"\\n\");\n}\n\n/**\n * Whether `ph publish` goes on. With `--require-approval`, `packed` is the\n * tarball the approval was checked against: publish that file, and call its\n * `dispose` once done.\n */\nexport type PublishCheck =\n | { readonly proceed: false }\n | { readonly proceed: true; readonly packed?: PackedRelease };\n\n/**\n * Checks the release approval before `ph publish` resolves a registry.\n * Without an approval file and without `required`, does nothing, as before\n * approvals existed. Otherwise a decision other than approved is a warning,\n * or with `required` a refusal.\n */\nexport function checkApprovalBeforePublish(\n packageRoot: string,\n required: boolean,\n): PublishCheck {\n const read = readReleaseApproval(packageRoot);\n if (read.kind === \"missing\" && !required) return { proceed: true };\n let text: string;\n let packed: PackedRelease | undefined;\n let approved = false;\n try {\n if (required && read.kind === \"found\") packed = packRelease(packageRoot);\n const decision = verifyRelease(\n packageRoot,\n read,\n packed && packedDigests(packed),\n );\n approved = decision.decision === \"approved\";\n text = renderReleaseDecision(decision);\n } catch (error) {\n text = `the release approval could not be checked: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (approved) {\n console.log(`✔ ${text}`);\n return { proceed: true, packed };\n }\n packed?.dispose();\n if (required) {\n console.error(\n `✘ ${text}\\nph publish --require-approval publishes only an approved package. Run ph build --release, then publish again.`,\n );\n return { proceed: false };\n }\n console.warn(\n `⚠ ${text}\\nPublishing anyway. Run ph build --release to approve this package, or pass --require-approval to stop here instead.`,\n );\n return { proceed: true };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAiBA,SAAgB,cACd,aACA,OAAqB,oBAAoB,WAAW,GACpD,WACiB;CACjB,IAAI,KAAK,SAAS,SAAS,OAAO,wBAAwB,IAAI;CAC9D,MAAM,EAAE,aAAa;CACrB,OAAO,sBAAsB,UAAU;EACrC,cAAc,WAAW;EACzB,OAAO,cAAc,aAAa,CAChC,SAAS,QACT,GAAG,SAAS,gBAAgB,QAC9B,CAAC;EACD,gBAAgB,aAAa,eAAe,WAAW;CACzD,CAAC;AACH;AAEA,MAAM,YAAmE;CACvE,UAAU;CACV,SAAS;CACT,YAAY;CACZ,OAAO;CACP,SAAS;AACX;;AAGA,SAAgB,sBAAsB,UAAmC;CACvE,OAAO,CACL,GAAG,SAAS,SAAS,IAAI,UAAU,SAAS,aAC5C,GAAG,SAAS,QAAQ,KAAK,WAAW,OAAO,QAAQ,CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;;AAiBA,SAAgB,2BACd,aACA,UACc;CACd,MAAM,OAAO,oBAAoB,WAAW;CAC5C,IAAI,KAAK,SAAS,aAAa,CAAC,UAAU,OAAO,EAAE,SAAS,KAAK;CACjE,IAAI;CACJ,IAAI;CACJ,IAAI,WAAW;CACf,IAAI;EACF,IAAI,YAAY,KAAK,SAAS,SAAS,SAAS,YAAY,WAAW;EACvE,MAAM,WAAW,cACf,aACA,MACA,UAAU,cAAc,MAAM,CAChC;EACA,WAAW,SAAS,aAAa;EACjC,OAAO,sBAAsB,QAAQ;CACvC,SAAS,OAAO;EACd,OAAO,8CAA8C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAC5G;CACA,IAAI,UAAU;EACZ,QAAQ,IAAI,KAAK,MAAM;EACvB,OAAO;GAAE,SAAS;GAAM;EAAO;CACjC;CACA,QAAQ,QAAQ;CAChB,IAAI,UAAU;EACZ,QAAQ,MACN,KAAK,KAAK,gHACZ;EACA,OAAO,EAAE,SAAS,MAAM;CAC1B;CACA,QAAQ,KACN,KAAK,KAAK,sHACZ;CACA,OAAO,EAAE,SAAS,KAAK;AACzB","debug_id":"8841ab23-e9d1-5eea-b70a-058103b6e688"}
1
+ {"version":3,"file":"verify-NK6a_7j8.mjs","sources":["../src/services/release/verify.ts"],"sourcesContent":["import { getVersion } from \"../../get-version.js\";\nimport {\n type ApprovalRead,\n decisionWithoutApproval,\n type ReleaseDecision,\n verifyReleaseApproval,\n} from \"./approval.js\";\nimport { publishedFiles, readReleaseApproval, revisionFiles } from \"./files.js\";\nimport { packedDigests, packRelease, type PackedRelease } from \"./pack.js\";\nimport type { FileDigest } from \"./revision.js\";\n\n/**\n * Compares the package as it is now with its release approval: the files\n * the revision reads, with the output directory and exclusions the approval\n * records, and what `npm pack` publishes, or `published` when the caller\n * already packed it. Throws when either cannot be read.\n */\nexport function verifyRelease(\n packageRoot: string,\n read: ApprovalRead = readReleaseApproval(packageRoot),\n published?: readonly FileDigest[],\n): ReleaseDecision {\n if (read.kind !== \"found\") return decisionWithoutApproval(read);\n const { approval } = read;\n return verifyReleaseApproval(approval, {\n phCliVersion: getVersion(),\n files: revisionFiles(packageRoot, [\n approval.outDir,\n ...approval.packageRevision.excluded,\n ]),\n publishedFiles: published ?? publishedFiles(packageRoot),\n });\n}\n\nconst HEADLINES: Readonly<Record<ReleaseDecision[\"decision\"], string>> = {\n approved: \"the release approval matches this package\",\n missing: \"this package has no release approval\",\n unreadable: \"the release approval cannot be read\",\n stale: \"the release approval does not match this package\",\n refused: \"the release approval records a release check that did not pass\",\n};\n\n/** The decision and each reason on its own line. */\nexport function renderReleaseDecision(decision: ReleaseDecision): string {\n return [\n `${decision.decision}: ${HEADLINES[decision.decision]}`,\n ...decision.reasons.map((reason) => ` - ${reason}`),\n ].join(\"\\n\");\n}\n\n/**\n * Whether `ph publish` goes on. With `--require-approval`, `packed` is the\n * tarball the approval was checked against: publish that file, and call its\n * `dispose` once done.\n */\nexport type PublishCheck =\n | { readonly proceed: false }\n | { readonly proceed: true; readonly packed?: PackedRelease };\n\n/**\n * Checks the release approval before `ph publish` resolves a registry.\n * Without an approval file and without `required`, does nothing, as before\n * approvals existed. Otherwise a decision other than approved is a warning,\n * or with `required` a refusal.\n */\nexport function checkApprovalBeforePublish(\n packageRoot: string,\n required: boolean,\n): PublishCheck {\n const read = readReleaseApproval(packageRoot);\n if (read.kind === \"missing\" && !required) return { proceed: true };\n let text: string;\n let packed: PackedRelease | undefined;\n let approved = false;\n try {\n if (required && read.kind === \"found\") packed = packRelease(packageRoot);\n const decision = verifyRelease(\n packageRoot,\n read,\n packed && packedDigests(packed),\n );\n approved = decision.decision === \"approved\";\n text = renderReleaseDecision(decision);\n } catch (error) {\n text = `the release approval could not be checked: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (approved) {\n console.log(`✔ ${text}`);\n return { proceed: true, packed };\n }\n packed?.dispose();\n if (required) {\n console.error(\n `✘ ${text}\\nph publish --require-approval publishes only an approved package. Run ph build --release, then publish again.`,\n );\n return { proceed: false };\n }\n console.warn(\n `⚠ ${text}\\nPublishing anyway. Run ph build --release to approve this package, or pass --require-approval to stop here instead.`,\n );\n return { proceed: true };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAiBA,SAAgB,cACd,aACA,OAAqB,oBAAoB,WAAW,GACpD,WACiB;CACjB,IAAI,KAAK,SAAS,SAAS,O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1
+ import { c as vetraGateway } from "./vetra-gateway-BxcduYAI.mjs";
2
+ export { vetraGateway };
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]="f913a474-09a0-5aab-b591-da9ce2601fed")}catch(e){}}();
4
+ //# debugId=f913a474-09a0-5aab-b591-da9ce2601fed
@@ -0,0 +1,173 @@
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]="46e3ee35-2128-5e5e-a250-776548e23331")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-CcYVboCW.mjs";
4
+ import { Q as resolvePackageRoot } from "./compound-BWLJ0KBw-8hKyrfjG.mjs";
5
+ import { readFileSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ import { CALLER_CWD_ENV } from "@powerhousedao/shared/clis/command-names";
9
+ import { yellow } from "colorette";
10
+ import { resolveCommand } from "package-manager-detector";
11
+ import { valid } from "semver";
12
+ //#region src/services/vetra-gateway.ts
13
+ /**
14
+ * `ph vetra` is the gateway to Vetra Studio, the host `studio` that the
15
+ * package @powerhousedao/vetra-cli supplies. ph-cli names the package and the
16
+ * host and nothing else of it: `ph vetra [verb] [args]` is
17
+ * `ph run @powerhousedao/vetra-cli/studio [verb] [args]`, once the project
18
+ * has the package. A project without it gets it first, as a devDependency at
19
+ * this ph-cli's version: the two are released with the same version numbers.
20
+ */
21
+ const VETRA_STUDIO_PACKAGE = "@powerhousedao/vetra-cli";
22
+ const VETRA_STUDIO_HOST = `${VETRA_STUDIO_PACKAGE}/studio`;
23
+ /** Set on the ph-cli started after an install: it finds the package, or
24
+ * fails, and never installs it again. */
25
+ const VETRA_GATEWAY_ENV = "PH_VETRA_GATEWAY_INSTALLED";
26
+ /** The command line that adds the package at ph-cli's version as a
27
+ * devDependency, with the project's package manager. */
28
+ function studioInstallCommand(agent, phCliVersion) {
29
+ const version = valid(phCliVersion) ?? "latest";
30
+ const releaseAge = agent.startsWith("pnpm") ? ["--config.minimum-release-age=0"] : [];
31
+ const resolved = resolveCommand(agent, "add", [
32
+ "-D",
33
+ `${VETRA_STUDIO_PACKAGE}@${version}`,
34
+ ...releaseAge
35
+ ]);
36
+ if (!resolved) throw new Error(`Could not resolve an install command for package manager "${agent}".`);
37
+ return [resolved.command, ...resolved.args].join(" ");
38
+ }
39
+ /** What `ph vetra` does in a project: install the package, or run its host,
40
+ * warning when the installed version is not ph-cli's. */
41
+ function planVetraGateway(facts) {
42
+ const { installed, phCliVersion, packageManager } = facts;
43
+ const command = studioInstallCommand(packageManager, phCliVersion);
44
+ if (installed === void 0) return {
45
+ action: "install",
46
+ notice: `Vetra Studio is the package ${VETRA_STUDIO_PACKAGE}, which this project does not have yet. Installing it as a devDependency with ${packageManager}:`,
47
+ command
48
+ };
49
+ const { version } = installed;
50
+ if (version !== void 0 && valid(phCliVersion) !== null && version !== phCliVersion) return {
51
+ action: "run",
52
+ warning: `${VETRA_STUDIO_PACKAGE} ${version} is installed, but this ph-cli is ${phCliVersion}: align them with \`${command}\`.`
53
+ };
54
+ return { action: "run" };
55
+ }
56
+ /**
57
+ * `ph vetra [verb] [args]` (`rest`) in the project: the `ph run` command line
58
+ * of the studio host when the package is there. Otherwise it installs the
59
+ * package and runs that command line in a new ph-cli, since a package
60
+ * installed while this one runs is not reliably resolved by it (Node caches
61
+ * lookups, and the install may relink what it imports later).
62
+ */
63
+ async function openVetraStudio(rest, deps) {
64
+ const { projectPath, packageManager } = await deps.project();
65
+ if (projectPath === void 0) throw new Error("No Powerhouse project found, so `ph vetra` cannot open Vetra Studio: it installs into and runs in a project. Run it in one, or create one with `ph init`.");
66
+ const runArgs = [
67
+ "run",
68
+ VETRA_STUDIO_HOST,
69
+ ...rest
70
+ ];
71
+ const plan = planVetraGateway({
72
+ installed: deps.installedStudio(projectPath),
73
+ phCliVersion: deps.phCliVersion,
74
+ packageManager
75
+ });
76
+ if (plan.action === "run") {
77
+ if (plan.warning) deps.warn(plan.warning);
78
+ return {
79
+ args: runArgs,
80
+ projectRoot: projectPath
81
+ };
82
+ }
83
+ if (rest.includes("--stop")) return {
84
+ args: runArgs,
85
+ projectRoot: projectPath
86
+ };
87
+ const manual = `Install it yourself, then run \`ph vetra\` again:\n ${plan.command}`;
88
+ if (deps.env["PH_VETRA_GATEWAY_INSTALLED"]) throw new Error(`${VETRA_STUDIO_PACKAGE} was installed, but this ph-cli does not find it from ${projectPath}. ${manual}`);
89
+ deps.log(plan.notice);
90
+ deps.log(`> ${plan.command}`);
91
+ const code = await deps.install(plan.command, projectPath);
92
+ if (code !== 0) {
93
+ const how = code === null ? "could not run" : `exited with code ${code}`;
94
+ throw new Error(`The install of ${VETRA_STUDIO_PACKAGE} ${how}, so Vetra Studio cannot start. ${manual}`);
95
+ }
96
+ if (deps.installedStudio(projectPath) === void 0) throw new Error(`The install passed, but ${VETRA_STUDIO_PACKAGE} does not resolve from ${projectPath}. ${manual}`);
97
+ return { exitCode: await deps.reexec(runArgs, projectPath) };
98
+ }
99
+ /** The package's version as `ph run <package>/<host>` finds it: from the
100
+ * project root, by its package.json, without importing it. */
101
+ function installedStudio(projectRoot) {
102
+ const root = resolvePackageRoot(projectRoot, VETRA_STUDIO_PACKAGE);
103
+ if (root === void 0) return void 0;
104
+ try {
105
+ const { version } = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"));
106
+ return { version: typeof version === "string" ? version : void 0 };
107
+ } catch {
108
+ return { version: void 0 };
109
+ }
110
+ }
111
+ function runInstall(command, cwd) {
112
+ return new Promise((resolve) => {
113
+ const child = spawn(command, {
114
+ cwd,
115
+ stdio: "inherit",
116
+ shell: true,
117
+ windowsHide: true
118
+ });
119
+ child.once("error", () => resolve(null));
120
+ child.once("close", (code) => resolve(code));
121
+ });
122
+ }
123
+ function reexecPhCli(args, cwd) {
124
+ const child = spawn(process.execPath, [process.argv[1], ...args], {
125
+ cwd,
126
+ stdio: "inherit",
127
+ env: {
128
+ ...process.env,
129
+ [VETRA_GATEWAY_ENV]: "1"
130
+ },
131
+ windowsHide: true
132
+ });
133
+ const ignore = () => {};
134
+ const forward = (signal) => child.kill(signal);
135
+ process.on("SIGINT", ignore);
136
+ process.on("SIGTERM", forward);
137
+ return new Promise((resolve) => {
138
+ const done = (code) => {
139
+ process.off("SIGINT", ignore);
140
+ process.off("SIGTERM", forward);
141
+ resolve(code);
142
+ };
143
+ child.once("error", () => done(1));
144
+ child.once("exit", (code) => done(code ?? 1));
145
+ });
146
+ }
147
+ /** cli.ts's `ph vetra`: the command line to go on with, in the project root,
148
+ * or the exit code of the ph-cli that ran it. */
149
+ async function vetraGateway(rest) {
150
+ const result = await openVetraStudio(rest, {
151
+ project: async () => {
152
+ const { getPowerhouseProjectInfo } = await import("@powerhousedao/shared/clis");
153
+ return getPowerhouseProjectInfo(void 0, { silent: true });
154
+ },
155
+ phCliVersion: getVersion(),
156
+ installedStudio,
157
+ install: runInstall,
158
+ reexec: reexecPhCli,
159
+ env: process.env,
160
+ log: (message) => console.log(message),
161
+ warn: (message) => console.warn(yellow(message))
162
+ });
163
+ if ("args" in result && path.resolve(result.projectRoot) !== process.cwd()) {
164
+ process.env[CALLER_CWD_ENV] ??= process.cwd();
165
+ process.chdir(result.projectRoot);
166
+ }
167
+ return result;
168
+ }
169
+ //#endregion
170
+ export { openVetraStudio as a, vetraGateway as c, installedStudio as i, VETRA_STUDIO_HOST as n, planVetraGateway as o, VETRA_STUDIO_PACKAGE as r, studioInstallCommand as s, VETRA_GATEWAY_ENV as t };
171
+
172
+ //# sourceMappingURL=vetra-gateway-BxcduYAI.mjs.map
173
+ //# debugId=46e3ee35-2128-5e5e-a250-776548e23331
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-gateway-BxcduYAI.mjs","sources":["../src/services/vetra-gateway.ts"],"sourcesContent":["import { resolvePackageRoot } from \"@powerhousedao/host-core\";\nimport { CALLER_CWD_ENV } from \"@powerhousedao/shared/clis/command-names\";\nimport { yellow } from \"colorette\";\nimport { spawn } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { resolveCommand, type Agent } from \"package-manager-detector\";\nimport { valid } from \"semver\";\nimport { getVersion } from \"../get-version.js\";\n\n/**\n * `ph vetra` is the gateway to Vetra Studio, the host `studio` that the\n * package @powerhousedao/vetra-cli supplies. ph-cli names the package and the\n * host and nothing else of it: `ph vetra [verb] [args]` is\n * `ph run @powerhousedao/vetra-cli/studio [verb] [args]`, once the project\n * has the package. A project without it gets it first, as a devDependency at\n * this ph-cli's version: the two are released with the same version numbers.\n */\nexport const VETRA_STUDIO_PACKAGE = \"@powerhousedao/vetra-cli\";\nexport const VETRA_STUDIO_HOST = `${VETRA_STUDIO_PACKAGE}/studio`;\n\n/** Set on the ph-cli started after an install: it finds the package, or\n * fails, and never installs it again. */\nexport const VETRA_GATEWAY_ENV = \"PH_VETRA_GATEWAY_INSTALLED\";\n\n/** The package as the project has it; undefined when it has none. */\nexport type InstalledStudio = { version: string | undefined } | undefined;\n\nexport type VetraGatewayPlan =\n | { action: \"run\"; warning?: string }\n | { action: \"install\"; notice: string; command: string };\n\n/** The command line that adds the package at ph-cli's version as a\n * devDependency, with the project's package manager. */\nexport function studioInstallCommand(\n agent: Agent,\n phCliVersion: string,\n): string {\n // A build that does not know its version takes the latest release.\n const version = valid(phCliVersion) ?? \"latest\";\n // As `ph install --local`: on a release day the packages are younger than\n // pnpm 11's minimumReleaseAge.\n const releaseAge = agent.startsWith(\"pnpm\")\n ? [\"--config.minimum-release-age=0\"]\n : [];\n const resolved = resolveCommand(agent, \"add\", [\n \"-D\",\n `${VETRA_STUDIO_PACKAGE}@${version}`,\n ...releaseAge,\n ]);\n if (!resolved) {\n throw new Error(\n `Could not resolve an install command for package manager \"${agent}\".`,\n );\n }\n return [resolved.command, ...resolved.args].join(\" \");\n}\n\n/** What `ph vetra` does in a project: install the package, or run its host,\n * warning when the installed version is not ph-cli's. */\nexport function planVetraGateway(facts: {\n installed: InstalledStudio;\n phCliVersion: string;\n packageManager: Agent;\n}): VetraGatewayPlan {\n const { installed, phCliVersion, packageManager } = facts;\n const command = studioInstallCommand(packageManager, phCliVersion);\n if (installed === undefined) {\n return {\n action: \"install\",\n notice:\n `Vetra Studio is the package ${VETRA_STUDIO_PACKAGE}, which this project does not have yet. ` +\n `Installing it as a devDependency with ${packageManager}:`,\n command,\n };\n }\n const { version } = installed;\n if (\n version !== undefined &&\n valid(phCliVersion) !== null &&\n version !== phCliVersion\n ) {\n return {\n action: \"run\",\n warning: `${VETRA_STUDIO_PACKAGE} ${version} is installed, but this ph-cli is ${phCliVersion}: align them with \\`${command}\\`.`,\n };\n }\n return { action: \"run\" };\n}\n\nexport interface VetraGatewayDeps {\n /** The project root, undefined outside a project, and its package manager. */\n project: () => Promise<{ projectPath?: string; packageManager: Agent }>;\n phCliVersion: string;\n installedStudio: (projectRoot: string) => InstalledStudio;\n /** Runs an install command line in `cwd`; resolves to its exit code. */\n install: (command: string, cwd: string) => Promise<number | null>;\n /** Runs this ph-cli with `args` in a new process; resolves to its exit code. */\n reexec: (args: string[], cwd: string) => Promise<number>;\n env: NodeJS.ProcessEnv;\n log: (message: string) => void;\n warn: (message: string) => void;\n}\n\nexport type VetraGatewayResult =\n /** Go on with this command line, in the project root. */\n | { args: string[]; projectRoot: string }\n /** A new ph-cli ran it, after the install. */\n | { exitCode: number };\n\n/**\n * `ph vetra [verb] [args]` (`rest`) in the project: the `ph run` command line\n * of the studio host when the package is there. Otherwise it installs the\n * package and runs that command line in a new ph-cli, since a package\n * installed while this one runs is not reliably resolved by it (Node caches\n * lookups, and the install may relink what it imports later).\n */\nexport async function openVetraStudio(\n rest: readonly string[],\n deps: VetraGatewayDeps,\n): Promise<VetraGatewayResult> {\n const { projectPath, packageManager } = await deps.project();\n if (projectPath === undefined) {\n throw new Error(\n \"No Powerhouse project found, so `ph vetra` cannot open Vetra Studio: it installs into and runs in a project. \" +\n \"Run it in one, or create one with `ph init`.\",\n );\n }\n const runArgs = [\"run\", VETRA_STUDIO_HOST, ...rest];\n const plan = planVetraGateway({\n installed: deps.installedStudio(projectPath),\n phCliVersion: deps.phCliVersion,\n packageManager,\n });\n if (plan.action === \"run\") {\n if (plan.warning) deps.warn(plan.warning);\n return { args: runArgs, projectRoot: projectPath };\n }\n // A stop reads the run record only: there is nothing to install for it.\n if (rest.includes(\"--stop\"))\n return { args: runArgs, projectRoot: projectPath };\n const manual = `Install it yourself, then run \\`ph vetra\\` again:\\n ${plan.command}`;\n if (deps.env[VETRA_GATEWAY_ENV]) {\n throw new Error(\n `${VETRA_STUDIO_PACKAGE} was installed, but this ph-cli does not find it from ${projectPath}. ${manual}`,\n );\n }\n deps.log(plan.notice);\n deps.log(`> ${plan.command}`);\n const code = await deps.install(plan.command, projectPath);\n if (code !== 0) {\n const how = code === null ? \"could not run\" : `exited with code ${code}`;\n throw new Error(\n `The install of ${VETRA_STUDIO_PACKAGE} ${how}, so Vetra Studio cannot start. ${manual}`,\n );\n }\n if (deps.installedStudio(projectPath) === undefined) {\n throw new Error(\n `The install passed, but ${VETRA_STUDIO_PACKAGE} does not resolve from ${projectPath}. ${manual}`,\n );\n }\n return { exitCode: await deps.reexec(runArgs, projectPath) };\n}\n\n/** The package's version as `ph run <package>/<host>` finds it: from the\n * project root, by its package.json, without importing it. */\nexport function installedStudio(projectRoot: string): InstalledStudio {\n const root = resolvePackageRoot(projectRoot, VETRA_STUDIO_PACKAGE);\n if (root === undefined) return undefined;\n try {\n const { version } = JSON.parse(\n readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as { version?: unknown };\n return { version: typeof version === \"string\" ? version : undefined };\n } catch {\n return { version: undefined };\n }\n}\n\nfunction runInstall(command: string, cwd: string): Promise<number | null> {\n return new Promise((resolve) => {\n // One command line, as printed: a shell runs the package manager's shim.\n const child = spawn(command, {\n cwd,\n stdio: \"inherit\",\n shell: true,\n windowsHide: true,\n });\n child.once(\"error\", () => resolve(null));\n child.once(\"close\", (code) => resolve(code));\n });\n}\n\nfunction reexecPhCli(args: string[], cwd: string): Promise<number> {\n const child = spawn(process.execPath, [process.argv[1], ...args], {\n cwd,\n stdio: \"inherit\",\n env: { ...process.env, [VETRA_GATEWAY_ENV]: \"1\" },\n windowsHide: true,\n });\n // Ctrl-C reaches the child from the terminal as well: wait while it stops.\n const ignore = () => {};\n const forward = (signal: NodeJS.Signals) => child.kill(signal);\n process.on(\"SIGINT\", ignore);\n process.on(\"SIGTERM\", forward);\n return new Promise<number>((resolve) => {\n const done = (code: number) => {\n process.off(\"SIGINT\", ignore);\n process.off(\"SIGTERM\", forward);\n resolve(code);\n };\n child.once(\"error\", () => done(1));\n child.once(\"exit\", (code) => done(code ?? 1));\n });\n}\n\n/** cli.ts's `ph vetra`: the command line to go on with, in the project root,\n * or the exit code of the ph-cli that ran it. */\nexport async function vetraGateway(\n rest: readonly string[],\n): Promise<{ args: string[] } | { exitCode: number }> {\n const result = await openVetraStudio(rest, {\n project: async () => {\n const { getPowerhouseProjectInfo } =\n await import(\"@powerhousedao/shared/clis\");\n return getPowerhouseProjectInfo(undefined, { silent: true });\n },\n phCliVersion: getVersion(),\n installedStudio,\n install: runInstall,\n reexec: reexecPhCli,\n env: process.env,\n log: (message) => console.log(message),\n warn: (message) => console.warn(yellow(message)),\n });\n if (\"args\" in result && path.resolve(result.projectRoot) !== process.cwd()) {\n // As ph-cmd runs ph-cli: in the project root, with relative paths still\n // meaning the caller's cwd.\n process.env[CALLER_CWD_ENV] ??= process.cwd();\n process.chdir(result.projectRoot);\n }\n return result;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,uBAAuB;AACpC,MAAa,oBAAoB,GAAG,qBAAqB;;;AAIzD,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alThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f60c004e-ab21-5e9b-9910-2a0cd7232c57")}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]="9b004534-e9d0-589a-8a74-a3c6fcc69596")}catch(e){}}();
3
3
  import { _ as unknown, d as object, r as array } from "./schemas-DzgKfQIx.mjs";
4
- import { J as readProjectName, a as STORE_VERBS, r as ONE_SHOT_VERBS } from "./compound-n-bO0qKh-Dx7fgKWx.mjs";
5
- import { c as vetraRuntimeRecord, l as writeVetraRuntime, n as vetraRuntimeRefusal, r as clearVetraRuntime, s as syncMcpPortNotices } from "./vetra-instance-DlXAeiU7.mjs";
4
+ import { J as readProjectName, a as STORE_VERBS, r as ONE_SHOT_VERBS } from "./compound-BWLJ0KBw-8hKyrfjG.mjs";
5
+ import { c as vetraRuntimeRecord, l as writeVetraRuntime, n as vetraRuntimeRefusal, r as clearVetraRuntime, s as syncMcpPortNotices } from "./vetra-instance-CPNIsaxh.mjs";
6
6
  import { yellow } from "colorette";
7
7
  import { outputsSchema } from "@powerhousedao/ph-run/runners/connect";
8
8
  import { outputsSchema as outputsSchema$1 } from "@powerhousedao/ph-run/runners/switchboard";
@@ -24,7 +24,7 @@ async function runVetraHost(args) {
24
24
  const projectName = readProjectName(projectDir);
25
25
  const restart = args.argv?.includes(RESTART_FLAG) ?? false;
26
26
  if (restart) {
27
- const { stopVetra } = await import("./vetra-launcher-TDLXj0tY.mjs");
27
+ const { stopVetra } = await import("./vetra-launcher-BtDWQBuh.mjs");
28
28
  await stopVetra({
29
29
  projectDir,
30
30
  projectName,
@@ -40,7 +40,7 @@ async function runVetraHost(args) {
40
40
  publishVetraRuntime(projectDir, projectName, result);
41
41
  return result;
42
42
  }
43
- /** `ph run vetra --restart`, which `ph vetra --restart` is sugar for. */
43
+ /** `ph run vetra --restart`, which `ph dev --restart` is sugar for. */
44
44
  const RESTART_FLAG = "--restart";
45
45
  const startedSchema = object({ started: array(object({ outputs: unknown() })) });
46
46
  const portOf = (url) => Number(new URL(url).port);
@@ -90,5 +90,5 @@ function publishVetraRuntime(projectDir, projectName, result) {
90
90
  //#endregion
91
91
  export { runVetraHost };
92
92
 
93
- //# sourceMappingURL=vetra-host-CDfny6E8.mjs.map
94
- //# debugId=f60c004e-ab21-5e9b-9910-2a0cd7232c57
93
+ //# sourceMappingURL=vetra-host-BrLdIMRP.mjs.map
94
+ //# debugId=9b004534-e9d0-589a-8a74-a3c6fcc69596
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-host-BrLdIMRP.mjs","sources":["../src/services/run/vetra-host.ts"],"sourcesContent":["import {\n ONE_SHOT_VERBS,\n readProjectName,\n STORE_VERBS,\n} from \"@powerhousedao/host-core\";\nimport { outputsSchema as connectOutputsSchema } from \"@powerhousedao/ph-run/runners/connect\";\nimport { outputsSchema as switchboardOutputsSchema } from \"@powerhousedao/ph-run/runners/switchboard\";\nimport { startRun, type StartRunArgs } from \"@powerhousedao/ph-run/start-run\";\nimport { yellow } from \"colorette\";\nimport { z } from \"zod\";\nimport { vetraRuntimeRefusal } from \"../../utils/vetra-instance.js\";\nimport {\n clearVetraRuntime,\n syncMcpPortNotices,\n vetraRuntimeRecord,\n writeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../../utils/vetra-runtime.js\";\n\n/**\n * `ph run vetra`: the vetra host is the generic compound runner over a\n * switchboard and a connect member, so nothing below `ph run` knows it is\n * Vetra. What makes the stack the project's Vetra is done here around\n * startRun: refuse while another Vetra holds\n * the project, publish `.ph/vetra-runtime.json` once the stack is ready,\n * clear it on exit, and correct a drifted `.mcp.json`. `--restart` is its own\n * argument, not a runner's: it stops the recorded Vetra first.\n */\nexport async function runVetraHost(args: StartRunArgs): Promise<unknown> {\n const verb = args.verb ?? \"run\";\n // `build` starts nothing; a store verb is refused for a compound.\n if (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb)) {\n return startRun(args);\n }\n const projectDir = args.projectRoot ?? process.cwd();\n const projectName = readProjectName(projectDir);\n const restart = args.argv?.includes(RESTART_FLAG) ?? false;\n if (restart) {\n const { stopVetra } = await import(\"../../utils/vetra-launcher.js\");\n await stopVetra({\n projectDir,\n projectName,\n onProgress: (message) => console.log(message),\n });\n }\n const refusal = await vetraRuntimeRefusal(projectDir, projectName);\n if (refusal) throw new Error(refusal);\n\n const result = await startRun(\n restart\n ? { ...args, argv: args.argv?.filter((arg) => arg !== RESTART_FLAG) }\n : args,\n );\n publishVetraRuntime(projectDir, projectName, result);\n return result;\n}\n\n/** `ph run vetra --restart`, which `ph dev --restart` is sugar for. */\nconst RESTART_FLAG = \"--restart\";\n\nconst startedSchema = z.object({\n started: z.array(z.object({ outputs: z.unknown() })),\n});\n\nconst portOf = (url: string) => Number(new URL(url).port);\n\nfunction firstMatch<T>(\n schema: z.ZodType<T>,\n candidates: unknown[],\n): T | undefined {\n for (const candidate of candidates) {\n const match = schema.safeParse(candidate);\n if (match.success) return match.data;\n }\n return undefined;\n}\n\n/**\n * The record of a ready compound: its members are told apart by the outputs\n * their runners publish, since a host file is free to name them.\n */\nexport function vetraRecordOfRun(\n projectName: string,\n result: unknown,\n): VetraRuntimeRecord | undefined {\n const parsed = startedSchema.safeParse(result);\n const outputs = parsed.success\n ? parsed.data.started.map((member) => member.outputs)\n : [];\n const switchboard = firstMatch(switchboardOutputsSchema, outputs);\n if (!switchboard) return undefined;\n const connect = firstMatch(connectOutputsSchema, outputs);\n return vetraRuntimeRecord({\n projectName,\n switchboardPort: portOf(switchboard.origin),\n // Vite may have taken another port, and the base path is Connect's.\n connectPort: connect ? portOf(connect.origin) : 0,\n switchboardUrl: switchboard.endpoints.graphql,\n mcpUrl: switchboard.endpoints.mcp,\n connectUrl: connect?.endpoints.connect,\n });\n}\n\n/**\n * Publishes the record of the stack startRun returned and syncs the MCP\n * configs to its port. Returns what clears the record again; it also runs on\n * exit. No SIGINT/SIGTERM handler: the compound owns the exit, and its\n * process.exit reaches the exit event.\n */\nexport function publishVetraRuntime(\n projectDir: string,\n projectName: string,\n result: unknown,\n): () => void {\n const record = vetraRecordOfRun(projectName, result);\n if (!record) {\n console.warn(\n yellow(\n \"No switchboard member is running, so .ph/vetra-runtime.json is not written and `ph mcp` will not find this stack.\",\n ),\n );\n return () => {};\n }\n // Record what the stack actually bound, so a second Vetra can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, record);\n // A restarted Vetra may already have written its own.\n const release = () => clearVetraRuntime(projectDir, process.pid);\n process.on(\"exit\", release);\n\n for (const notice of syncMcpPortNotices(projectDir, record.switchboardPort)) {\n console.log(yellow(notice));\n }\n return release;\n}\n"],"names":["z.object","z.array","z.unknown","switchboardOutputsSchema","connectOutputsSchema"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,aAAa,MAAsC;CACvE,MAAM,OAAO,KAAK,QAAQ;CAE1B,IAAI,eAAe,IAAI,IAAI,KAAK,YAAY,IAAI,IAAI,GAClD,OAAO,SAAS,IAAI;CAEtB,MAAM,aAAa,KAAK,eAAe,QAAQ,IAAI;CACnD,MAAM,cAAc,gBAAgB,UAAU;CAC9C,MAAM,UAAU,KAAK,MAAM,SAAS,YAAY,KAAK;CACrD,IAAI,SAAS;EACX,MAAM,EAAE,cAAc,MAAM,OAAO;EACnC,MAAM,UAAU;GACd;GACA;GACA,aAAa,YAAY,QAAQ,IAAI,OAAO;EAC9C,CAAC;CACH;CACA,MAAM,UAAU,MAAM,oBAAoB,YAAY,WAAW;CACjE,IAAI,SAAS,MAAM,IAAI,MAAM,OAAO;CAEpC,MAAM,SAAS,MAAM,SACnB,UACI;EAAE,GAAG;EAAM,MAAM,KAAK,MAAM,QAAQ,QAAQ,QAAQ,YAAY;CA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T","debug_id":"9b004534-e9d0-589a-8a74-a3c6fcc69596"}
@@ -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]="8f95e550-af95-5efc-b872-b761ec031b79")}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]="ca914e2a-3bcb-5ccb-b73b-6d381ea2e1e8")}catch(e){}}();
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
@@ -20,7 +20,7 @@ function writeVetraRuntime(projectDir, record) {
20
20
  fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\n`);
21
21
  }
22
22
  /**
23
- * The record this process publishes for the Vetra it started. `ph vetra` and
23
+ * The record this process publishes for the Vetra it started. `ph dev` and
24
24
  * `ph run vetra` both build it here, so the two write the same fields. The
25
25
  * Switchboard's URLs follow from its port unless the caller knows them.
26
26
  */
@@ -175,7 +175,7 @@ function syncMcpPortNotices(projectDir, port) {
175
175
  * `.ph/run/vetra.json` and, once ready, in `.ph/vetra-runtime.json`, which is
176
176
  * what a start asks here: whether a Vetra already holds the project.
177
177
  */
178
- /** The host folder `ph vetra` runs, and the name its host file carries. */
178
+ /** The host folder `ph dev` runs, and the name its host file carries. */
179
179
  const VETRA_HOST = "vetra";
180
180
  /** Why `ph run vetra` must not start: a live Vetra holds the project. */
181
181
  async function vetraRuntimeRefusal(projectDir, projectName) {
@@ -189,5 +189,5 @@ async function vetraRuntimeRefusal(projectDir, projectName) {
189
189
  //#endregion
190
190
  export { probeVetraRuntime as a, vetraRuntimeRecord as c, isPortInUse as i, writeVetraRuntime as l, vetraRuntimeRefusal as n, readVetraRuntime as o, clearVetraRuntime as r, syncMcpPortNotices as s, VETRA_HOST as t };
191
191
 
192
- //# sourceMappingURL=vetra-instance-DlXAeiU7.mjs.map
193
- //# debugId=8f95e550-af95-5efc-b872-b761ec031b79
192
+ //# sourceMappingURL=vetra-instance-CPNIsaxh.mjs.map
193
+ //# debugId=ca914e2a-3bcb-5ccb-b73b-6d381ea2e1e8
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-instance-CPNIsaxh.mjs","sources":["../src/utils/vetra-runtime.ts","../src/utils/vetra-instance.ts"],"sourcesContent":["import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport net from \"node:net\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n /** The Switchboard's GraphQL endpoint; absent in records from before it was written. */\n switchboardUrl?: string;\n mcpUrl: string;\n /** Vetra Studio; absent with --disable-connect. */\n connectUrl?: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"starting\"; record: VetraRuntimeRecord }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst READY_TIMEOUT_MS = 2000;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR.\nconst recordPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-runtime.json\");\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\n/**\n * The record this process publishes for the Vetra it started. `ph dev` and\n * `ph run vetra` both build it here, so the two write the same fields. The\n * Switchboard's URLs follow from its port unless the caller knows them.\n */\nexport function vetraRuntimeRecord(input: {\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n switchboardUrl?: string;\n mcpUrl?: string;\n /** Left out when no Vetra Studio runs. */\n connectUrl?: string;\n}): VetraRuntimeRecord {\n const { switchboardPort, connectUrl } = input;\n return {\n pid: process.pid,\n projectName: input.projectName,\n switchboardPort,\n connectPort: input.connectPort,\n switchboardUrl:\n input.switchboardUrl ?? `http://localhost:${switchboardPort}/graphql`,\n mcpUrl: input.mcpUrl ?? `http://localhost:${switchboardPort}/mcp`,\n ...(connectUrl ? { connectUrl } : {}),\n startedAt: new Date().toISOString(),\n };\n}\n\n/** Deletes the record; with `pid`, only the record of that process. */\nexport function clearVetraRuntime(projectDir: string, pid?: number): void {\n if (pid !== undefined && readVetraRuntime(projectDir)?.pid !== pid) return;\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nexport function isPortInUse(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = net.connect({ port, host: \"localhost\" });\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve(true);\n });\n socket.once(\"error\", () => resolve(false));\n });\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n const alive = isPidAlive(record.pid);\n const ready = alive && (await isReady(record.switchboardPort));\n // The record lands once the port is bound; `/ready` turns 200 later.\n const starting =\n alive && !ready && (await isPortInUse(record.switchboardPort));\n if (!ready && !starting) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return ready ? { status: \"live\", record } : { status: \"starting\", record };\n}\n\nconst MCP_FILES = [\n \".mcp.json\",\n path.join(\".cursor\", \"mcp.json\"),\n path.join(\".gemini\", \"settings.json\"),\n];\n\ntype McpConfig = { mcpServers?: Record<string, { url?: string }> };\ntype UrlMcpConfig = [string, McpConfig, { url?: string }];\n\n/** Each MCP config whose `reactor-mcp` entry still points at a URL. */\nfunction urlMcpConfigs(projectDir: string): UrlMcpConfig[] {\n const found: UrlMcpConfig[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n let parsed: McpConfig;\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as McpConfig;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (server?.url) found.push([rel, parsed, server]);\n }\n return found;\n}\n\n/** The MCP configs `ph migrate` would move to the `ph mcp` launcher. */\nexport function legacyMcpConfigs(projectDir: string): string[] {\n return urlMcpConfigs(projectDir).map(([rel]) => rel);\n}\n\n/**\n * Point every URL-style `reactor-mcp` entry at `port`, returning the files\n * changed. Stdio entries (`ph mcp`) carry no port and are left alone; this\n * keeps projects that have not run `ph migrate` working.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n const wanted = `http://localhost:${port}/mcp`;\n for (const [rel, parsed, server] of urlMcpConfigs(projectDir)) {\n if (server.url === wanted) continue;\n server.url = wanted;\n fs.writeFileSync(\n path.join(projectDir, rel),\n `${JSON.stringify(parsed, null, 2)}\\n`,\n );\n changed.push(rel);\n }\n return changed;\n}\n\n/**\n * {@link syncMcpPort} for a Vetra that just bound `port`, returning what to\n * tell the user. An MCP client resolved `.mcp.json` before this process\n * started and cannot re-read it, so a drifted literal means the agent is\n * pointed at the wrong port — possibly another project's reactor. Correct the\n * file and say so plainly; we cannot fix the already-open client ourselves.\n */\nexport function syncMcpPortNotices(projectDir: string, port: number): string[] {\n const notices: string[] = [];\n const driftedMcpFiles = syncMcpPort(projectDir, port);\n if (driftedMcpFiles.length > 0) {\n notices.push(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${port}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n );\n }\n if (legacyMcpConfigs(projectDir).length > 0) {\n notices.push(\n \"reactor-mcp still points at a URL; run `ph migrate` to switch it to the `ph mcp` launcher.\",\n );\n }\n return notices;\n}\n","import { probeVetraRuntime } from \"./vetra-runtime.js\";\n\n/**\n * One Vetra per project. `ph run vetra` records its stack in\n * `.ph/run/vetra.json` and, once ready, in `.ph/vetra-runtime.json`, which is\n * what a start asks here: whether a Vetra already holds the project.\n */\n\n/** The host folder `ph dev` runs, and the name its host file carries. */\nexport const VETRA_HOST = \"vetra\";\n\n/** Why `ph run vetra` must not start: a live Vetra holds the project. */\nexport async function vetraRuntimeRefusal(\n projectDir: string,\n projectName: string,\n): Promise<string | undefined> {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\" || probe.status === \"starting\") {\n if (probe.record.pid === process.pid) return undefined;\n return `Vetra is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`;\n }\n if (probe.status === \"foreign\") {\n return (\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`\n );\n }\n return undefined;\n}\n"],"names":[],"mappings":";;;;;;;AAyBA,MAAM,mBAAmB;AAGzB,MAAM,cAAc,eAClB,KAAK,KAAK,aAAa,UAAU,GAAG,oBAAoB;AAE1D,SAAgB,iBACd,YACgC;CAChC,IAAI;EACF,OAAO,KAAK,MACV,GAAG,aAAa,WAAW,UAAU,GAAG,MAAM,CAChD;CACF,QAAQ;EAEN;CACF;AACF;AAEA,SAAgB,kBACd,YACA,QACM;CACN,MAAM,SAAS,WAAW,UAAU;CACpC,GAAG,UAAU,KAAK,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CACtD,GAAG,cAAc,QAAQ,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,GAAG;AACjE;;;;;;AAOA,SAAgB,mBAAmB,OAQZ;CACrB,MAAM,EAAE,iBAAiB,eAAe;CACxC,OAAO;EACL,KAAK,QAAQ;EACb,aAAa,MAAM;EACnB;EACA,aAAa,MAAM;EACnB,gBACE,MAAM,kBAAkB,oBAAoB,gBAAgB;EAC9D,QAAQ,MAAM,UAAU,oBAAoB,gBAAgB;EAC5D,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACnC,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC;AACF;;AAGA,SAAgB,kBAAkB,YAAoB,KAAoB;CACxE,IAAI,QAAQ,KAAA,KAAa,iBAAiB,UAAU,CAAC,EAAE,QAAQ,KAAK;CACpE,IAAI;EACF,GAAG,OAAO,WAAW,UAAU,CAAC;CAClC,QAAQ,CAER;AACF;AAEA,SAAS,WAAW,KAAsB;CACxC,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAA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EAC7C,OAAO,kDAAkD,MAAM,OAAO,IAAI;CAC5E;CACA,IAAI,MAAM,WAAW,WACnB,OACE,sDAAsD,MAAM,OAAO,YAAY,0BACvD,YAAY;AAK1C","debug_id":"ca914e2a-3bcb-5ccb-b73b-6d381ea2e1e8"}
@@ -0,0 +1,4 @@
1
+ import { o as stopVetra } from "./vetra-launcher-Dokr1aDK.mjs";
2
+ export { stopVetra };
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]="2131716e-47fc-5dc3-a00b-0ec15d9d82ee")}catch(e){}}();
4
+ //# debugId=2131716e-47fc-5dc3-a00b-0ec15d9d82ee
@@ -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]="03b8abe1-7aa3-5da4-88d7-90c03e3bda50")}catch(e){}}();
3
- import { X as requestStop } from "./compound-n-bO0qKh-Dx7fgKWx.mjs";
4
- import { a as probeVetraRuntime, i as isPortInUse, r as clearVetraRuntime, t as VETRA_HOST } from "./vetra-instance-DlXAeiU7.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]="e35415c1-3b9c-52c8-b997-4219f0c52968")}catch(e){}}();
3
+ import { X as requestStop } from "./compound-BWLJ0KBw-8hKyrfjG.mjs";
4
+ import { a as probeVetraRuntime, i as isPortInUse, r as clearVetraRuntime, t as VETRA_HOST } from "./vetra-instance-CPNIsaxh.mjs";
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { spawn } from "node:child_process";
@@ -215,5 +215,5 @@ async function restartVetra(options) {
215
215
  //#endregion
216
216
  export { restartVetra as a, readLogTail as i, currentPhCliRunVetraCommand as n, stopVetra as o, ensureVetra as r, vetraLogPath as s, VetraStartError as t };
217
217
 
218
- //# sourceMappingURL=vetra-launcher-CYX10K2m.mjs.map
219
- //# debugId=03b8abe1-7aa3-5da4-88d7-90c03e3bda50
218
+ //# sourceMappingURL=vetra-launcher-Dokr1aDK.mjs.map
219
+ //# debugId=e35415c1-3b9c-52c8-b997-4219f0c52968
@@ -1 +1 @@
1
- {"version":3,"file":"vetra-launcher-CYX10K2m.mjs","sources":["../src/utils/vetra-launcher.ts"],"sourcesContent":["import { requestStop } from \"@powerhousedao/host-core\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { VETRA_HOST } from \"./vetra-instance.js\";\nimport {\n clearVetraRuntime,\n isPortInUse,\n probeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"./vetra-runtime.js\";\n\nexport type VetraCommand = {\n command: string;\n args: string[];\n /** How messages name it; `ph run vetra` when left out. */\n label?: string;\n};\n\nexport type EnsureVetraOptions = {\n projectDir: string;\n projectName: string;\n /** The port a strict-port Vetra will bind. */\n switchboardPort: number;\n command: VetraCommand;\n timeoutMs: number;\n pollMs?: number;\n /** Told what it waits on while Vetra is not ready yet, about once a second. */\n onProgress?: (message: string) => void;\n};\n\nexport class VetraStartError extends Error {}\n\nconst LOG_TAIL_LINES = 60;\nconst PORT_GRACE_MS = 10_000;\nconst STOP_TIMEOUT_MS = 15_000;\nconst PROGRESS_EVERY_MS = 1000;\n\nconst lockPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-start.lock\");\n\nexport const vetraLogPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra.log\");\n\n// Forward slashes, so messages read the same on every platform.\nconst shownLogPath = (projectDir: string) =>\n path.relative(projectDir, vetraLogPath(projectDir)).split(path.sep).join(\"/\");\n\n/**\n * What starts a project's Vetra: `ph run vetra --strictPort`, run by the\n * ph-cli executing this code. The host's own defaultVerb picks the verb. In\n * a project without the host it fails, and its output says why.\n */\nexport function currentPhCliRunVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"run\", VETRA_HOST, \"--strictPort\"],\n label: `ph run ${VETRA_HOST}`,\n };\n}\n\nfunction isPidAlive(pid: number | undefined): boolean {\n if (!pid) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\ntype LockRecord = { pid: number; vetraPid?: number };\n\nfunction readLock(projectDir: string): LockRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(lockPath(projectDir), \"utf8\"),\n ) as LockRecord;\n } catch {\n return undefined;\n }\n}\n\nfunction isLockHeld(lock: LockRecord | undefined): boolean {\n return !!lock && (isPidAlive(lock.pid) || isPidAlive(lock.vetraPid));\n}\n\n/** Held while the launcher or the Vetra it started is alive. */\nfunction tryAcquireLock(projectDir: string): boolean {\n const target = lockPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n fs.writeFileSync(target, JSON.stringify({ pid: process.pid }), {\n flag: \"wx\",\n });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (isLockHeld(readLock(projectDir))) return false;\n fs.rmSync(target, { force: true });\n }\n }\n return false;\n}\n\nfunction releaseLock(projectDir: string): void {\n if (readLock(projectDir)?.pid === process.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n}\n\nexport function readLogTail(projectDir: string): string {\n try {\n const text = fs.readFileSync(vetraLogPath(projectDir), \"utf8\");\n const lines = stripVTControlCharacters(text).trimEnd().split(\"\\n\");\n return lines.slice(-LOG_TAIL_LINES).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\nfunction withOutput(message: string, projectDir: string): VetraStartError {\n const tail = readLogTail(projectDir);\n const where = shownLogPath(projectDir);\n return new VetraStartError(\n tail\n ? `${message}\\n\\nVetra output (last lines of ${where}):\\n${tail}`\n : message,\n );\n}\n\nfunction foreignError(record: VetraRuntimeRecord): VetraStartError {\n return new VetraStartError(\n `.ph/vetra-runtime.json describes a live Vetra for \"${record.projectName}\" (pid ${record.pid}), not this project. ` +\n `Refusing to start a second reactor. Delete .ph/vetra-runtime.json if that record is wrong.`,\n );\n}\n\nasync function waitForLive(\n options: EnsureVetraOptions,\n deadline: number,\n stillStarting: () => boolean,\n): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, pollMs = 250, onProgress } = options;\n const startedAt = Date.now();\n let reportedAt = startedAt;\n while (Date.now() < deadline) {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"starting\" && !stillStarting()) return undefined;\n if (onProgress && Date.now() - reportedAt >= PROGRESS_EVERY_MS) {\n reportedAt = Date.now();\n const seconds = Math.round((reportedAt - startedAt) / 1000);\n onProgress(`Waiting for Vetra to be ready (${seconds}s)...`);\n }\n await sleep(pollMs);\n }\n return undefined;\n}\n\n/** This project's live Vetra, or a detached `ph run vetra` started and awaited; never a second reactor. */\nexport async function ensureVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, switchboardPort, timeoutMs } = options;\n const deadline = Date.now() + timeoutMs;\n const seconds = Math.round(timeoutMs / 1000);\n const report = options.onProgress ?? (() => {});\n\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status === \"starting\") {\n report(`Vetra (pid ${probe.record.pid}) is starting; waiting for it...`);\n const record = await waitForLive(options, deadline, () => false);\n if (record) return record;\n throw withOutput(\n `Vetra (pid ${probe.record.pid}) is running but did not answer /ready within ${seconds}s.`,\n projectDir,\n );\n }\n\n while (!tryAcquireLock(projectDir)) {\n // Another launcher is starting Vetra for this project.\n report(\"Another process is starting Vetra for this project; waiting...\");\n const record = await waitForLive(options, deadline, () =>\n isLockHeld(readLock(projectDir)),\n );\n if (record) return record;\n if (Date.now() >= deadline) {\n throw withOutput(\n `Another process is starting Vetra for this project and it did not become ready within ${seconds}s.`,\n projectDir,\n );\n }\n }\n\n let keepLock = false;\n try {\n const again = await probeVetraRuntime(projectDir, projectName);\n if (again.status === \"live\") return again.record;\n if (again.status === \"foreign\") throw foreignError(again.record);\n\n if (again.status === \"starting\" || (await isPortInUse(switchboardPort))) {\n // Maybe a Vetra that bound the port but has not written its record yet.\n const grace = Date.now() + PORT_GRACE_MS;\n const record = await waitForLive(\n options,\n deadline,\n () => Date.now() < grace,\n );\n if (record) return record;\n throw new VetraStartError(\n `Port ${switchboardPort} is in use, but .ph/vetra-runtime.json names no live Vetra for this project. ` +\n `Stop whatever holds the port, or move this project's port (reactor.port in powerhouse.config.json).`,\n );\n }\n\n const logFile = vetraLogPath(projectDir);\n report(`Starting Vetra; its output goes to ${shownLogPath(projectDir)}...`);\n const logFd = fs.openSync(logFile, \"w\");\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n const child = spawn(options.command.command, options.command.args, {\n cwd: projectDir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n windowsHide: true,\n });\n fs.closeSync(logFd);\n child.once(\"error\", (error) => (spawnError = error));\n child.once(\"exit\", (code, signal) => (exit = { code, signal }));\n child.unref();\n if (child.pid) {\n fs.writeFileSync(\n lockPath(projectDir),\n JSON.stringify({ pid: process.pid, vetraPid: child.pid }),\n );\n }\n\n const record = await waitForLive(\n options,\n deadline,\n () => !exit && !spawnError,\n );\n if (record) return record;\n\n if (spawnError) {\n throw new VetraStartError(\n `Could not run \\`${options.command.command}\\`: ${spawnError.message}`,\n );\n }\n if (exit) {\n const how =\n exit.signal !== null\n ? `was killed by ${exit.signal}`\n : `exited with code ${exit.code}`;\n throw withOutput(\n `\\`${options.command.label ?? `ph run ${VETRA_HOST}`}\\` ${how} before it was ready.`,\n projectDir,\n );\n }\n // Still booting: keep the lock on its pid so the next call waits instead of spawning.\n keepLock = true;\n throw withOutput(\n `Vetra (pid ${child.pid}) did not answer /ready on port ${switchboardPort} within ${seconds}s. ` +\n `It is still running; the next tool call waits for it again.`,\n projectDir,\n );\n } finally {\n if (!keepLock) releaseLock(projectDir);\n }\n}\n\nasync function waitForExit(\n record: VetraRuntimeRecord,\n deadline: number,\n): Promise<boolean> {\n while (Date.now() < deadline) {\n const gone =\n !isPidAlive(record.pid) && !(await isPortInUse(record.switchboardPort));\n if (gone) return true;\n await sleep(100);\n }\n return false;\n}\n\n/** Stops this project's running Vetra, if any; resolves to the record it stopped. */\nexport async function stopVetra(options: {\n projectDir: string;\n projectName: string;\n timeoutMs?: number;\n onProgress?: (message: string) => void;\n}): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, timeoutMs = STOP_TIMEOUT_MS } = options;\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"live\" && probe.status !== \"starting\") return undefined;\n const { record } = probe;\n const signal = (name: NodeJS.Signals) => {\n try {\n process.kill(record.pid, name);\n } catch {\n // Already gone.\n }\n };\n options.onProgress?.(`Stopping Vetra (pid ${record.pid})...`);\n // On Windows SIGTERM is a kill: ask through the stop channel, and signal\n // only a Vetra that has none.\n if (!(await requestStop(record.pid))) signal(\"SIGTERM\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n signal(\"SIGKILL\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n throw new VetraStartError(\n `Vetra (pid ${record.pid}) did not stop within ${Math.round((2 * timeoutMs) / 1000)}s.`,\n );\n }\n }\n clearVetraRuntime(projectDir, record.pid);\n if (readLock(projectDir)?.vetraPid === record.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n return record;\n}\n\n/** Stops this project's Vetra and starts it again, detached, as {@link ensureVetra} does. */\nexport async function restartVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, onProgress } = options;\n const stopped = await stopVetra({ projectDir, projectName, onProgress });\n if (stopped) onProgress?.(`Stopped Vetra (pid ${stopped.pid}).`);\n return ensureVetra(options);\n}\n"],"names":[],"mappings":";;;;;;;;;;AAiCA,IAAa,kBAAb,cAAqC,MAAM,CAAC;AAG5C,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAE1B,MAAM,YAAY,eAChB,KAAK,KAAK,aAAa,UAAU,GAAG,kBAAkB;AAExD,MAAa,gBAAgB,eAC3B,KAAK,KAAK,aAAa,UAAU,GAAG,WAAW;AAGjD,MAAM,gBAAgB,eACpB,KAAK,SAAS,YAAY,aAAa,UAAU,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;;;;;;AAO9E,SAAgB,8BAA4C;CAC1D,OAAO;EACL,SAAS,QAAQ;EACjB,MAAM;GAAC,QAAQ,KAAK;GAAI;GAAO;GAAY;EAAc;EACzD,OAAO,UAAU;CACnB;AACF;AAEA,SAAS,WAAW,KAAkC;CACpD,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,SAAS,OAAO;EACd,OAAQ,MAAgC,SAAS;CACnD;AACF;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;AAIlE,SAAS,SAAS,YAA4C;CAC5D,IAAI;EACF,OAAO,KAAK,MACV,GAAG,aAAa,SAAS,UAAU,GAAG,MAAM,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AI,wBAAwB,KAAK,MAAO,IAAI,YAAa,GAAI,EAAE,GACtF;CAEJ;CACA,kBAAkB,YAAY,OAAO,GAAG;CACxC,IAAI,SAAS,UAAU,CAAC,EAAE,aAAa,OAAO,KAC5C,GAAG,OAAO,SAAS,UAAU,GAAG,EAAE,OAAO,KAAK,CAAC;CAEjD,OAAO;AACT;;AAGA,eAAsB,aACpB,SAC6B;CAC7B,MAAM,EAAE,YAAY,aAAa,eAAe;CAChD,MAAM,UAAU,MAAM,UAAU;EAAE;EAAY;EAAa;CAAW,CAAC;CACvE,IAAI,SAAS,aAAa,sBAAsB,QAAQ,IAAI,GAAG;CAC/D,OAAO,YAAY,OAAO;AAC5B","debug_id":"03b8abe1-7aa3-5da4-88d7-90c03e3bda50"}
1
+ {"version":3,"file":"vetra-launcher-Dokr1aDK.mjs","sources":["../src/utils/vetra-launcher.ts"],"sourcesContent":["import { requestStop } from \"@powerhousedao/host-core\";\nimport { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport { VETRA_HOST } from \"./vetra-instance.js\";\nimport {\n clearVetraRuntime,\n isPortInUse,\n probeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"./vetra-runtime.js\";\n\nexport type VetraCommand = {\n command: string;\n args: string[];\n /** How messages name it; `ph run vetra` when left out. */\n label?: string;\n};\n\nexport type EnsureVetraOptions = {\n projectDir: string;\n projectName: string;\n /** The port a strict-port Vetra will bind. */\n switchboardPort: number;\n command: VetraCommand;\n timeoutMs: number;\n pollMs?: number;\n /** Told what it waits on while Vetra is not ready yet, about once a second. */\n onProgress?: (message: string) => void;\n};\n\nexport class VetraStartError extends Error {}\n\nconst LOG_TAIL_LINES = 60;\nconst PORT_GRACE_MS = 10_000;\nconst STOP_TIMEOUT_MS = 15_000;\nconst PROGRESS_EVERY_MS = 1000;\n\nconst lockPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-start.lock\");\n\nexport const vetraLogPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra.log\");\n\n// Forward slashes, so messages read the same on every platform.\nconst shownLogPath = (projectDir: string) =>\n path.relative(projectDir, vetraLogPath(projectDir)).split(path.sep).join(\"/\");\n\n/**\n * What starts a project's Vetra: `ph run vetra --strictPort`, run by the\n * ph-cli executing this code. The host's own defaultVerb picks the verb. In\n * a project without the host it fails, and its output says why.\n */\nexport function currentPhCliRunVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"run\", VETRA_HOST, \"--strictPort\"],\n label: `ph run ${VETRA_HOST}`,\n };\n}\n\nfunction isPidAlive(pid: number | undefined): boolean {\n if (!pid) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\ntype LockRecord = { pid: number; vetraPid?: number };\n\nfunction readLock(projectDir: string): LockRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(lockPath(projectDir), \"utf8\"),\n ) as LockRecord;\n } catch {\n return undefined;\n }\n}\n\nfunction isLockHeld(lock: LockRecord | undefined): boolean {\n return !!lock && (isPidAlive(lock.pid) || isPidAlive(lock.vetraPid));\n}\n\n/** Held while the launcher or the Vetra it started is alive. */\nfunction tryAcquireLock(projectDir: string): boolean {\n const target = lockPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n fs.writeFileSync(target, JSON.stringify({ pid: process.pid }), {\n flag: \"wx\",\n });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (isLockHeld(readLock(projectDir))) return false;\n fs.rmSync(target, { force: true });\n }\n }\n return false;\n}\n\nfunction releaseLock(projectDir: string): void {\n if (readLock(projectDir)?.pid === process.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n}\n\nexport function readLogTail(projectDir: string): string {\n try {\n const text = fs.readFileSync(vetraLogPath(projectDir), \"utf8\");\n const lines = stripVTControlCharacters(text).trimEnd().split(\"\\n\");\n return lines.slice(-LOG_TAIL_LINES).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\nfunction withOutput(message: string, projectDir: string): VetraStartError {\n const tail = readLogTail(projectDir);\n const where = shownLogPath(projectDir);\n return new VetraStartError(\n tail\n ? `${message}\\n\\nVetra output (last lines of ${where}):\\n${tail}`\n : message,\n );\n}\n\nfunction foreignError(record: VetraRuntimeRecord): VetraStartError {\n return new VetraStartError(\n `.ph/vetra-runtime.json describes a live Vetra for \"${record.projectName}\" (pid ${record.pid}), not this project. ` +\n `Refusing to start a second reactor. Delete .ph/vetra-runtime.json if that record is wrong.`,\n );\n}\n\nasync function waitForLive(\n options: EnsureVetraOptions,\n deadline: number,\n stillStarting: () => boolean,\n): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, pollMs = 250, onProgress } = options;\n const startedAt = Date.now();\n let reportedAt = startedAt;\n while (Date.now() < deadline) {\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"starting\" && !stillStarting()) return undefined;\n if (onProgress && Date.now() - reportedAt >= PROGRESS_EVERY_MS) {\n reportedAt = Date.now();\n const seconds = Math.round((reportedAt - startedAt) / 1000);\n onProgress(`Waiting for Vetra to be ready (${seconds}s)...`);\n }\n await sleep(pollMs);\n }\n return undefined;\n}\n\n/** This project's live Vetra, or a detached `ph run vetra` started and awaited; never a second reactor. */\nexport async function ensureVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, switchboardPort, timeoutMs } = options;\n const deadline = Date.now() + timeoutMs;\n const seconds = Math.round(timeoutMs / 1000);\n const report = options.onProgress ?? (() => {});\n\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"live\") return probe.record;\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status === \"starting\") {\n report(`Vetra (pid ${probe.record.pid}) is starting; waiting for it...`);\n const record = await waitForLive(options, deadline, () => false);\n if (record) return record;\n throw withOutput(\n `Vetra (pid ${probe.record.pid}) is running but did not answer /ready within ${seconds}s.`,\n projectDir,\n );\n }\n\n while (!tryAcquireLock(projectDir)) {\n // Another launcher is starting Vetra for this project.\n report(\"Another process is starting Vetra for this project; waiting...\");\n const record = await waitForLive(options, deadline, () =>\n isLockHeld(readLock(projectDir)),\n );\n if (record) return record;\n if (Date.now() >= deadline) {\n throw withOutput(\n `Another process is starting Vetra for this project and it did not become ready within ${seconds}s.`,\n projectDir,\n );\n }\n }\n\n let keepLock = false;\n try {\n const again = await probeVetraRuntime(projectDir, projectName);\n if (again.status === \"live\") return again.record;\n if (again.status === \"foreign\") throw foreignError(again.record);\n\n if (again.status === \"starting\" || (await isPortInUse(switchboardPort))) {\n // Maybe a Vetra that bound the port but has not written its record yet.\n const grace = Date.now() + PORT_GRACE_MS;\n const record = await waitForLive(\n options,\n deadline,\n () => Date.now() < grace,\n );\n if (record) return record;\n throw new VetraStartError(\n `Port ${switchboardPort} is in use, but .ph/vetra-runtime.json names no live Vetra for this project. ` +\n `Stop whatever holds the port, or move this project's port (reactor.port in powerhouse.config.json).`,\n );\n }\n\n const logFile = vetraLogPath(projectDir);\n report(`Starting Vetra; its output goes to ${shownLogPath(projectDir)}...`);\n const logFd = fs.openSync(logFile, \"w\");\n let exit: { code: number | null; signal: string | null } | undefined;\n let spawnError: Error | undefined;\n const child = spawn(options.command.command, options.command.args, {\n cwd: projectDir,\n detached: true,\n stdio: [\"ignore\", logFd, logFd],\n windowsHide: true,\n });\n fs.closeSync(logFd);\n child.once(\"error\", (error) => (spawnError = error));\n child.once(\"exit\", (code, signal) => (exit = { code, signal }));\n child.unref();\n if (child.pid) {\n fs.writeFileSync(\n lockPath(projectDir),\n JSON.stringify({ pid: process.pid, vetraPid: child.pid }),\n );\n }\n\n const record = await waitForLive(\n options,\n deadline,\n () => !exit && !spawnError,\n );\n if (record) return record;\n\n if (spawnError) {\n throw new VetraStartError(\n `Could not run \\`${options.command.command}\\`: ${spawnError.message}`,\n );\n }\n if (exit) {\n const how =\n exit.signal !== null\n ? `was killed by ${exit.signal}`\n : `exited with code ${exit.code}`;\n throw withOutput(\n `\\`${options.command.label ?? `ph run ${VETRA_HOST}`}\\` ${how} before it was ready.`,\n projectDir,\n );\n }\n // Still booting: keep the lock on its pid so the next call waits instead of spawning.\n keepLock = true;\n throw withOutput(\n `Vetra (pid ${child.pid}) did not answer /ready on port ${switchboardPort} within ${seconds}s. ` +\n `It is still running; the next tool call waits for it again.`,\n projectDir,\n );\n } finally {\n if (!keepLock) releaseLock(projectDir);\n }\n}\n\nasync function waitForExit(\n record: VetraRuntimeRecord,\n deadline: number,\n): Promise<boolean> {\n while (Date.now() < deadline) {\n const gone =\n !isPidAlive(record.pid) && !(await isPortInUse(record.switchboardPort));\n if (gone) return true;\n await sleep(100);\n }\n return false;\n}\n\n/** Stops this project's running Vetra, if any; resolves to the record it stopped. */\nexport async function stopVetra(options: {\n projectDir: string;\n projectName: string;\n timeoutMs?: number;\n onProgress?: (message: string) => void;\n}): Promise<VetraRuntimeRecord | undefined> {\n const { projectDir, projectName, timeoutMs = STOP_TIMEOUT_MS } = options;\n const probe = await probeVetraRuntime(projectDir, projectName);\n if (probe.status === \"foreign\") throw foreignError(probe.record);\n if (probe.status !== \"live\" && probe.status !== \"starting\") return undefined;\n const { record } = probe;\n const signal = (name: NodeJS.Signals) => {\n try {\n process.kill(record.pid, name);\n } catch {\n // Already gone.\n }\n };\n options.onProgress?.(`Stopping Vetra (pid ${record.pid})...`);\n // On Windows SIGTERM is a kill: ask through the stop channel, and signal\n // only a Vetra that has none.\n if (!(await requestStop(record.pid))) signal(\"SIGTERM\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n signal(\"SIGKILL\");\n if (!(await waitForExit(record, Date.now() + timeoutMs))) {\n throw new VetraStartError(\n `Vetra (pid ${record.pid}) did not stop within ${Math.round((2 * timeoutMs) / 1000)}s.`,\n );\n }\n }\n clearVetraRuntime(projectDir, record.pid);\n if (readLock(projectDir)?.vetraPid === record.pid) {\n fs.rmSync(lockPath(projectDir), { force: true });\n }\n return record;\n}\n\n/** Stops this project's Vetra and starts it again, detached, as {@link ensureVetra} does. */\nexport async function restartVetra(\n options: EnsureVetraOptions,\n): Promise<VetraRuntimeRecord> {\n const { projectDir, projectName, onProgress } = options;\n const stopped = await stopVetra({ projectDir, projectName, onProgress });\n if (stopped) onProgress?.(`Stopped Vetra (pid ${stopped.pid}).`);\n return ensureVetra(options);\n}\n"],"names":[],"mappings":";;;;;;;;;;AAiCA,IAAa,kBAAb,cAAqC,MAAM,CAAC;AAG5C,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAE1B,MAAM,YAAY,eAChB,KAAK,KAAK,aAAa,UAAU,GAAG,kBAAkB;AAExD,MAAa,gBAAgB,eAC3B,KAAK,KAAK,aAAa,UAAU,GAAG,WAAW;AAGjD,MAAM,gBAAgB,eACpB,KAAK,SAAS,YAAY,aAAa,UAAU,CAAC,CAAC,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;;;;;;AAO9E,SAAgB,8BAA4C;CAC1D,OAAO;EACL,SAAS,QAAQ;EACjB,MAAM;GAAC,QAAQ,KAAK;GAAI;GAAO;GAAY;EAAc;EACzD,OAAO,UAAU;CACnB;AACF;AAEA,SAAS,WAAW,KAAkC;CACpD,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACF,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,SAAS,OAAO;EACd,OAAQ,MAAgC,SAAS;CACnD;AACF;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,MAAM,WAAW,GAAG,EAAE,CAAC;AAI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