@powerhousedao/ph-cli 6.2.3-dev.78 → 6.2.3-dev.79

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 (86) hide show
  1. package/dist/{build-Dj8qfSSe.mjs → build-DUzhIPb7.mjs} +8 -55
  2. package/dist/build-DUzhIPb7.mjs.map +1 -0
  3. package/dist/build-FoZl36TM.mjs +4 -0
  4. package/dist/{check-KEXBwJXM.mjs → check-DDy1o6Vr.mjs} +10 -7
  5. package/dist/check-DDy1o6Vr.mjs.map +1 -0
  6. package/dist/{cli-connect-override-C65On7dE.mjs → cli-connect-override-By7u9IVR.mjs} +4 -4
  7. package/dist/{cli-connect-override-C65On7dE.mjs.map → cli-connect-override-By7u9IVR.mjs.map} +1 -1
  8. package/dist/cli.mjs +5 -9
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/{connect-build-B9jwzQlf.mjs → connect-build-BBAZuqpo.mjs} +5 -5
  11. package/dist/{connect-build-B9jwzQlf.mjs.map → connect-build-BBAZuqpo.mjs.map} +1 -1
  12. package/dist/{connect-config-D5SHcBf1.mjs → connect-config-ghJlOd-x.mjs} +4 -4
  13. package/dist/{connect-config-D5SHcBf1.mjs.map → connect-config-ghJlOd-x.mjs.map} +1 -1
  14. package/dist/connect-studio-BaVeuul3.mjs +78 -0
  15. package/dist/connect-studio-BaVeuul3.mjs.map +1 -0
  16. package/dist/{connect-studio-CYETzL2c.mjs → connect-studio-CfggUldW.mjs} +3 -3
  17. package/dist/{dist-CSn_YRdB.mjs → dist-Bd6sSt7Y.mjs} +19 -19
  18. package/dist/dist-Bd6sSt7Y.mjs.map +1 -0
  19. package/dist/{explain-BsZw-WrZ.mjs → explain-C9zER5xn.mjs} +4 -4
  20. package/dist/{explain-BsZw-WrZ.mjs.map → explain-C9zER5xn.mjs.map} +1 -1
  21. package/dist/{export-BGJVYlCK.mjs → export-CrIz2spe.mjs} +4 -4
  22. package/dist/{export-BGJVYlCK.mjs.map → export-CrIz2spe.mjs.map} +1 -1
  23. package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
  24. package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
  25. package/dist/{generate-piece-U3tP-Sex.mjs → generate-piece-C6ymlErL.mjs} +6 -6
  26. package/dist/{generate-piece-U3tP-Sex.mjs.map → generate-piece-C6ymlErL.mjs.map} +1 -1
  27. package/dist/{generate-piece-action-DbxrzfKY.mjs → generate-piece-action-uYRdKtQA.mjs} +5 -5
  28. package/dist/{generate-piece-action-DbxrzfKY.mjs.map → generate-piece-action-uYRdKtQA.mjs.map} +1 -1
  29. package/dist/{generate-piece-trigger-CqVOcL9g.mjs → generate-piece-trigger-CZaDD-cc.mjs} +5 -5
  30. package/dist/{generate-piece-trigger-CqVOcL9g.mjs.map → generate-piece-trigger-CZaDD-cc.mjs.map} +1 -1
  31. package/dist/{generate-processor-B9Umgjy9.mjs → generate-processor-BVjOsfjJ.mjs} +5 -5
  32. package/dist/{generate-processor-B9Umgjy9.mjs.map → generate-processor-BVjOsfjJ.mjs.map} +1 -1
  33. package/dist/{generate-subgraph-DRrInOOv.mjs → generate-subgraph-CrHbYK91.mjs} +5 -5
  34. package/dist/{generate-subgraph-DRrInOOv.mjs.map → generate-subgraph-CrHbYK91.mjs.map} +1 -1
  35. package/dist/get-version-_coBX13A.mjs +11 -0
  36. package/dist/get-version-_coBX13A.mjs.map +1 -0
  37. package/dist/{index-DHHaYrj2.d.mts → index-DdpGYzN0.d.mts} +2 -2
  38. package/dist/{index-DHHaYrj2.d.mts.map → index-DdpGYzN0.d.mts.map} +1 -1
  39. package/dist/{init-ScuT3z7P.mjs → init-Ch1rCksS.mjs} +12 -10
  40. package/dist/{init-ScuT3z7P.mjs.map → init-Ch1rCksS.mjs.map} +1 -1
  41. package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
  42. package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
  43. package/dist/mcp-CZ02pj76.mjs +262 -0
  44. package/dist/mcp-CZ02pj76.mjs.map +1 -0
  45. package/dist/member-config-8Vwys-4O.mjs +154 -0
  46. package/dist/member-config-8Vwys-4O.mjs.map +1 -0
  47. package/dist/{migrate-b38W7NH_.mjs → migrate-CIJaE3iZ.mjs} +4 -4
  48. package/dist/{migrate-b38W7NH_.mjs.map → migrate-CIJaE3iZ.mjs.map} +1 -1
  49. package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
  50. package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
  51. package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
  52. package/dist/{ph-cli-commands-DJYB9BDl.mjs → ph-cli-commands-B37zr8uN.mjs} +102 -35
  53. package/dist/ph-cli-commands-B37zr8uN.mjs.map +1 -0
  54. package/dist/ph-cli-commands-S3ArIR8q.mjs +4 -0
  55. package/dist/runners/connect.d.mts +5 -1
  56. package/dist/runners/connect.d.mts.map +1 -1
  57. package/dist/runners/connect.mjs +3 -3
  58. package/dist/runners/switchboard.d.mts +1159 -3
  59. package/dist/runners/switchboard.d.mts.map +1 -1
  60. package/dist/runners/switchboard.mjs +48 -67
  61. package/dist/runners/switchboard.mjs.map +1 -1
  62. package/dist/scripts/generate-commands-docs.ts +4 -0
  63. package/dist/{switchboard-h4-XgP1h.mjs → switchboard-BI35F5H7.mjs} +40 -8
  64. package/dist/switchboard-BI35F5H7.mjs.map +1 -0
  65. package/dist/switchboard-DohZ1tbp.mjs +4 -0
  66. package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
  67. package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
  68. package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
  69. package/dist/{vetra-C4ri3YLH.mjs → vetra-C9fsChId.mjs} +75 -127
  70. package/dist/vetra-C9fsChId.mjs.map +1 -0
  71. package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
  72. package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
  73. package/package.json +15 -13
  74. package/dist/build-C78yPntL.mjs +0 -4
  75. package/dist/build-Dj8qfSSe.mjs.map +0 -1
  76. package/dist/check-KEXBwJXM.mjs.map +0 -1
  77. package/dist/connect-studio-CEpyVlJ_.mjs +0 -39
  78. package/dist/connect-studio-CEpyVlJ_.mjs.map +0 -1
  79. package/dist/dist-CSn_YRdB.mjs.map +0 -1
  80. package/dist/install-added-dependencies-DVSbzler.mjs +0 -33
  81. package/dist/install-added-dependencies-DVSbzler.mjs.map +0 -1
  82. package/dist/ph-cli-commands-DJYB9BDl.mjs.map +0 -1
  83. package/dist/ph-cli-commands-JBUwDL2d.mjs +0 -4
  84. package/dist/switchboard-C5zgkRl2.mjs +0 -4
  85. package/dist/switchboard-h4-XgP1h.mjs.map +0 -1
  86. package/dist/vetra-C4ri3YLH.mjs.map +0 -1
@@ -0,0 +1,343 @@
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]="fa169741-6ee8-5b36-87b6-59a21c14932a")}catch(e){}}();
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { spawn } from "node:child_process";
6
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
7
+ import { stripVTControlCharacters } from "node:util";
8
+ import net from "node:net";
9
+ //#region src/utils/vetra-runtime.ts
10
+ const READY_TIMEOUT_MS = 2e3;
11
+ const recordPath = (projectDir) => path.join(resolvePhDir(projectDir), "vetra-runtime.json");
12
+ function readVetraRuntime(projectDir) {
13
+ try {
14
+ return JSON.parse(fs.readFileSync(recordPath(projectDir), "utf8"));
15
+ } catch {
16
+ return;
17
+ }
18
+ }
19
+ function writeVetraRuntime(projectDir, record) {
20
+ const target = recordPath(projectDir);
21
+ fs.mkdirSync(path.dirname(target), { recursive: true });
22
+ fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\n`);
23
+ }
24
+ /** Deletes the record; with `pid`, only the record of that process. */
25
+ function clearVetraRuntime(projectDir, pid) {
26
+ if (pid !== void 0 && readVetraRuntime(projectDir)?.pid !== pid) return;
27
+ try {
28
+ fs.rmSync(recordPath(projectDir));
29
+ } catch {}
30
+ }
31
+ function isPidAlive$1(pid) {
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ } catch (error) {
36
+ return error.code === "EPERM";
37
+ }
38
+ }
39
+ function isPortInUse(port) {
40
+ return new Promise((resolve) => {
41
+ const socket = net.connect({
42
+ port,
43
+ host: "localhost"
44
+ });
45
+ socket.once("connect", () => {
46
+ socket.destroy();
47
+ resolve(true);
48
+ });
49
+ socket.once("error", () => resolve(false));
50
+ });
51
+ }
52
+ async function isReady(port) {
53
+ try {
54
+ return (await fetch(`http://localhost:${port}/ready`, { signal: AbortSignal.timeout(READY_TIMEOUT_MS) })).ok;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ /**
60
+ * Decide whether the recorded instance is actually serving this project.
61
+ *
62
+ * All three checks are load-bearing. A pid can be reused by an unrelated
63
+ * process, so a live pid proves nothing on its own. Another project's
64
+ * switchboard would answer `/ready` on its own port, so a healthy `/ready`
65
+ * proves nothing either. And the recorded `projectName` is what separates
66
+ * "my instance" from "someone else's instance that happens to hold this
67
+ * port" — which is precisely the confusion that let an agent write document
68
+ * models into a different project's drive.
69
+ *
70
+ * A stale record is deleted so the next start is unblocked. A foreign one is
71
+ * left alone: it describes something that is alive.
72
+ */
73
+ async function probeVetraRuntime(projectDir, projectName) {
74
+ const record = readVetraRuntime(projectDir);
75
+ if (!record) return { status: "none" };
76
+ const alive = isPidAlive$1(record.pid);
77
+ const ready = alive && await isReady(record.switchboardPort);
78
+ const starting = alive && !ready && await isPortInUse(record.switchboardPort);
79
+ if (!ready && !starting) {
80
+ clearVetraRuntime(projectDir);
81
+ return { status: "stale" };
82
+ }
83
+ if (record.projectName !== projectName) return {
84
+ status: "foreign",
85
+ record
86
+ };
87
+ return ready ? {
88
+ status: "live",
89
+ record
90
+ } : {
91
+ status: "starting",
92
+ record
93
+ };
94
+ }
95
+ const MCP_FILES = [
96
+ ".mcp.json",
97
+ path.join(".cursor", "mcp.json"),
98
+ path.join(".gemini", "settings.json")
99
+ ];
100
+ /** Each MCP config whose `reactor-mcp` entry still points at a URL. */
101
+ function urlMcpConfigs(projectDir) {
102
+ const found = [];
103
+ for (const rel of MCP_FILES) {
104
+ const target = path.join(projectDir, rel);
105
+ if (!fs.existsSync(target)) continue;
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(fs.readFileSync(target, "utf8"));
109
+ } catch {
110
+ continue;
111
+ }
112
+ const server = parsed.mcpServers?.["reactor-mcp"];
113
+ if (server?.url) found.push([
114
+ rel,
115
+ parsed,
116
+ server
117
+ ]);
118
+ }
119
+ return found;
120
+ }
121
+ /** The MCP configs `ph migrate` would move to the `ph mcp` launcher. */
122
+ function legacyMcpConfigs(projectDir) {
123
+ return urlMcpConfigs(projectDir).map(([rel]) => rel);
124
+ }
125
+ /**
126
+ * Point every URL-style `reactor-mcp` entry at `port`, returning the files
127
+ * changed. Stdio entries (`ph mcp`) carry no port and are left alone; this
128
+ * keeps projects that have not run `ph migrate` working.
129
+ */
130
+ function syncMcpPort(projectDir, port) {
131
+ const changed = [];
132
+ const wanted = `http://localhost:${port}/mcp`;
133
+ for (const [rel, parsed, server] of urlMcpConfigs(projectDir)) {
134
+ if (server.url === wanted) continue;
135
+ server.url = wanted;
136
+ fs.writeFileSync(path.join(projectDir, rel), `${JSON.stringify(parsed, null, 2)}\n`);
137
+ changed.push(rel);
138
+ }
139
+ return changed;
140
+ }
141
+ //#endregion
142
+ //#region src/utils/vetra-launch.ts
143
+ var VetraStartError = class extends Error {};
144
+ const PORT_GRACE_MS = 1e4;
145
+ const STOP_TIMEOUT_MS = 15e3;
146
+ const PROGRESS_EVERY_MS = 1e3;
147
+ const lockPath = (projectDir) => path.join(resolvePhDir(projectDir), "vetra-start.lock");
148
+ const vetraLogPath = (projectDir) => path.join(resolvePhDir(projectDir), "vetra.log");
149
+ const shownLogPath = (projectDir) => path.relative(projectDir, vetraLogPath(projectDir)).split(path.sep).join("/");
150
+ /** `ph vetra --strictPort --watch` run by the ph-cli executing this code. */
151
+ function currentPhCliVetraCommand() {
152
+ return {
153
+ command: process.execPath,
154
+ args: [
155
+ process.argv[1],
156
+ "vetra",
157
+ "--strictPort",
158
+ "--watch"
159
+ ]
160
+ };
161
+ }
162
+ function isPidAlive(pid) {
163
+ if (!pid) return false;
164
+ try {
165
+ process.kill(pid, 0);
166
+ return true;
167
+ } catch (error) {
168
+ return error.code === "EPERM";
169
+ }
170
+ }
171
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
172
+ function readLock(projectDir) {
173
+ try {
174
+ return JSON.parse(fs.readFileSync(lockPath(projectDir), "utf8"));
175
+ } catch {
176
+ return;
177
+ }
178
+ }
179
+ function isLockHeld(lock) {
180
+ return !!lock && (isPidAlive(lock.pid) || isPidAlive(lock.vetraPid));
181
+ }
182
+ /** Held while the launcher or the Vetra it started is alive. */
183
+ function tryAcquireLock(projectDir) {
184
+ const target = lockPath(projectDir);
185
+ fs.mkdirSync(path.dirname(target), { recursive: true });
186
+ for (let attempt = 0; attempt < 2; attempt++) try {
187
+ fs.writeFileSync(target, JSON.stringify({ pid: process.pid }), { flag: "wx" });
188
+ return true;
189
+ } catch (error) {
190
+ if (error.code !== "EEXIST") throw error;
191
+ if (isLockHeld(readLock(projectDir))) return false;
192
+ fs.rmSync(target, { force: true });
193
+ }
194
+ return false;
195
+ }
196
+ function releaseLock(projectDir) {
197
+ if (readLock(projectDir)?.pid === process.pid) fs.rmSync(lockPath(projectDir), { force: true });
198
+ }
199
+ function readLogTail(projectDir) {
200
+ try {
201
+ const text = fs.readFileSync(vetraLogPath(projectDir), "utf8");
202
+ return stripVTControlCharacters(text).trimEnd().split("\n").slice(-60).join("\n");
203
+ } catch {
204
+ return "";
205
+ }
206
+ }
207
+ function withOutput(message, projectDir) {
208
+ const tail = readLogTail(projectDir);
209
+ const where = shownLogPath(projectDir);
210
+ return new VetraStartError(tail ? `${message}\n\nVetra output (last lines of ${where}):\n${tail}` : message);
211
+ }
212
+ function foreignError(record) {
213
+ return new VetraStartError(`.ph/vetra-runtime.json describes a live Vetra for "${record.projectName}" (pid ${record.pid}), not this project. Refusing to start a second reactor. Delete .ph/vetra-runtime.json if that record is wrong.`);
214
+ }
215
+ async function waitForLive(options, deadline, stillStarting) {
216
+ const { projectDir, projectName, pollMs = 250, onProgress } = options;
217
+ const startedAt = Date.now();
218
+ let reportedAt = startedAt;
219
+ while (Date.now() < deadline) {
220
+ const probe = await probeVetraRuntime(projectDir, projectName);
221
+ if (probe.status === "live") return probe.record;
222
+ if (probe.status === "foreign") throw foreignError(probe.record);
223
+ if (probe.status !== "starting" && !stillStarting()) return void 0;
224
+ if (onProgress && Date.now() - reportedAt >= PROGRESS_EVERY_MS) {
225
+ reportedAt = Date.now();
226
+ onProgress(`Waiting for Vetra to be ready (${Math.round((reportedAt - startedAt) / 1e3)}s)...`);
227
+ }
228
+ await sleep(pollMs);
229
+ }
230
+ }
231
+ /** This project's live Vetra, or a detached `ph vetra` started and awaited; never a second reactor. */
232
+ async function ensureVetra(options) {
233
+ const { projectDir, projectName, switchboardPort, timeoutMs } = options;
234
+ const deadline = Date.now() + timeoutMs;
235
+ const seconds = Math.round(timeoutMs / 1e3);
236
+ const report = options.onProgress ?? (() => {});
237
+ const probe = await probeVetraRuntime(projectDir, projectName);
238
+ if (probe.status === "live") return probe.record;
239
+ if (probe.status === "foreign") throw foreignError(probe.record);
240
+ if (probe.status === "starting") {
241
+ report(`Vetra (pid ${probe.record.pid}) is starting; waiting for it...`);
242
+ const record = await waitForLive(options, deadline, () => false);
243
+ if (record) return record;
244
+ throw withOutput(`Vetra (pid ${probe.record.pid}) is running but did not answer /ready within ${seconds}s.`, projectDir);
245
+ }
246
+ while (!tryAcquireLock(projectDir)) {
247
+ report("Another process is starting Vetra for this project; waiting...");
248
+ const record = await waitForLive(options, deadline, () => isLockHeld(readLock(projectDir)));
249
+ if (record) return record;
250
+ if (Date.now() >= deadline) throw withOutput(`Another process is starting Vetra for this project and it did not become ready within ${seconds}s.`, projectDir);
251
+ }
252
+ let keepLock = false;
253
+ try {
254
+ const again = await probeVetraRuntime(projectDir, projectName);
255
+ if (again.status === "live") return again.record;
256
+ if (again.status === "foreign") throw foreignError(again.record);
257
+ if (again.status === "starting" || await isPortInUse(switchboardPort)) {
258
+ const grace = Date.now() + PORT_GRACE_MS;
259
+ const record = await waitForLive(options, deadline, () => Date.now() < grace);
260
+ if (record) return record;
261
+ throw new VetraStartError(`Port ${switchboardPort} is in use, but .ph/vetra-runtime.json names no live Vetra for this project. Stop whatever holds the port, or move this project's port (reactor.port in powerhouse.config.json).`);
262
+ }
263
+ const logFile = vetraLogPath(projectDir);
264
+ report(`Starting Vetra; its output goes to ${shownLogPath(projectDir)}...`);
265
+ const logFd = fs.openSync(logFile, "w");
266
+ let exit;
267
+ let spawnError;
268
+ const child = spawn(options.command.command, options.command.args, {
269
+ cwd: projectDir,
270
+ detached: true,
271
+ stdio: [
272
+ "ignore",
273
+ logFd,
274
+ logFd
275
+ ],
276
+ windowsHide: true
277
+ });
278
+ fs.closeSync(logFd);
279
+ child.once("error", (error) => spawnError = error);
280
+ child.once("exit", (code, signal) => exit = {
281
+ code,
282
+ signal
283
+ });
284
+ child.unref();
285
+ if (child.pid) fs.writeFileSync(lockPath(projectDir), JSON.stringify({
286
+ pid: process.pid,
287
+ vetraPid: child.pid
288
+ }));
289
+ const record = await waitForLive(options, deadline, () => !exit && !spawnError);
290
+ if (record) return record;
291
+ if (spawnError) throw new VetraStartError(`Could not run \`${options.command.command}\`: ${spawnError.message}`);
292
+ if (exit) throw withOutput(`\`ph vetra\` ${exit.signal !== null ? `was killed by ${exit.signal}` : `exited with code ${exit.code}`} before it was ready.`, projectDir);
293
+ keepLock = true;
294
+ throw withOutput(`Vetra (pid ${child.pid}) did not answer /ready on port ${switchboardPort} within ${seconds}s. It is still running; the next tool call waits for it again.`, projectDir);
295
+ } finally {
296
+ if (!keepLock) releaseLock(projectDir);
297
+ }
298
+ }
299
+ async function waitForExit(record, deadline) {
300
+ while (Date.now() < deadline) {
301
+ if (!isPidAlive(record.pid) && !await isPortInUse(record.switchboardPort)) return true;
302
+ await sleep(100);
303
+ }
304
+ return false;
305
+ }
306
+ /** Stops this project's running Vetra, if any; resolves to the record it stopped. */
307
+ async function stopVetra(options) {
308
+ const { projectDir, projectName, timeoutMs = STOP_TIMEOUT_MS } = options;
309
+ const probe = await probeVetraRuntime(projectDir, projectName);
310
+ if (probe.status === "foreign") throw foreignError(probe.record);
311
+ if (probe.status !== "live" && probe.status !== "starting") return void 0;
312
+ const { record } = probe;
313
+ const signal = (name) => {
314
+ try {
315
+ process.kill(record.pid, name);
316
+ } catch {}
317
+ };
318
+ options.onProgress?.(`Stopping Vetra (pid ${record.pid})...`);
319
+ signal("SIGTERM");
320
+ if (!await waitForExit(record, Date.now() + timeoutMs)) {
321
+ signal("SIGKILL");
322
+ if (!await waitForExit(record, Date.now() + timeoutMs)) throw new VetraStartError(`Vetra (pid ${record.pid}) did not stop within ${Math.round(2 * timeoutMs / 1e3)}s.`);
323
+ }
324
+ clearVetraRuntime(projectDir, record.pid);
325
+ if (readLock(projectDir)?.vetraPid === record.pid) fs.rmSync(lockPath(projectDir), { force: true });
326
+ return record;
327
+ }
328
+ /** Stops this project's Vetra and starts it again, detached, as {@link ensureVetra} does. */
329
+ async function restartVetra(options) {
330
+ const { projectDir, projectName, onProgress } = options;
331
+ const stopped = await stopVetra({
332
+ projectDir,
333
+ projectName,
334
+ onProgress
335
+ });
336
+ if (stopped) onProgress?.(`Stopped Vetra (pid ${stopped.pid}).`);
337
+ return ensureVetra(options);
338
+ }
339
+ //#endregion
340
+ export { stopVetra as a, probeVetraRuntime as c, writeVetraRuntime as d, restartVetra as i, readVetraRuntime as l, currentPhCliVetraCommand as n, clearVetraRuntime as o, ensureVetra as r, legacyMcpConfigs as s, VetraStartError as t, syncMcpPort as u };
341
+
342
+ //# sourceMappingURL=vetra-launch-DQDZxGTV.mjs.map
343
+ //# debugId=fa169741-6ee8-5b36-87b6-59a21c14932a
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-launch-DQDZxGTV.mjs","sources":["../src/utils/vetra-runtime.ts","../src/utils/vetra-launch.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/** 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","import { 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 {\n clearVetraRuntime,\n isPortInUse,\n probeVetraRuntime,\n type VetraRuntimeRecord,\n} from \"./vetra-runtime.js\";\n\nexport type VetraCommand = { command: string; args: string[] };\n\nexport type EnsureVetraOptions = {\n projectDir: string;\n projectName: string;\n /** The port `ph vetra --strictPort` 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/** `ph vetra --strictPort --watch` run by the ph-cli executing this code. */\nexport function currentPhCliVetraCommand(): VetraCommand {\n return {\n command: process.execPath,\n args: [process.argv[1], \"vetra\", \"--strictPort\", \"--watch\"],\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 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 `ph 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(`\\`ph vetra\\` ${how} before it was ready.`, projectDir);\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 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":["isPidAlive"],"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;;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,SAASA,aAAW,KAAsB;CACxC,IAAI;EACF,QAAQ,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I,KAAK;CAC5D,OAAO,SAAS;CAChB,IAAI,CAAE,MAAM,YAAY,QAAQ,KAAK,IAAI,IAAI,SAAS,GAAI;EACxD,OAAO,SAAS;EAChB,IAAI,CAAE,MAAM,YAAY,QAAQ,KAAK,IAAI,IAAI,SAAS,GACpD,MAAM,IAAI,gBACR,cAAc,OAAO,IAAI,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":"fa169741-6ee8-5b36-87b6-59a21c14932a"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.3-dev.78",
3
+ "version": "6.2.3-dev.79",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -38,15 +38,17 @@
38
38
  "keywords": [],
39
39
  "author": "",
40
40
  "dependencies": {
41
- "@powerhousedao/builder-tools": "6.2.3-dev.78",
42
- "@powerhousedao/codegen": "6.2.3-dev.78",
43
- "@powerhousedao/common": "6.2.3-dev.78",
44
- "@powerhousedao/config": "6.2.3-dev.78",
45
- "@powerhousedao/reactor": "6.2.3-dev.78",
46
- "@powerhousedao/shared": "6.2.3-dev.78",
47
- "@powerhousedao/switchboard": "6.2.3-dev.78",
48
- "@powerhousedao/vetra": "6.2.3-dev.78",
49
- "@renown/sdk": "6.2.3-dev.78",
41
+ "@modelcontextprotocol/sdk": "1.29.0",
42
+ "@powerhousedao/builder-tools": "6.2.3-dev.79",
43
+ "@powerhousedao/codegen": "6.2.3-dev.79",
44
+ "@powerhousedao/common": "6.2.3-dev.79",
45
+ "@powerhousedao/config": "6.2.3-dev.79",
46
+ "@powerhousedao/reactor": "6.2.3-dev.79",
47
+ "@powerhousedao/reactor-mcp": "6.2.3-dev.79",
48
+ "@powerhousedao/shared": "6.2.3-dev.79",
49
+ "@powerhousedao/switchboard": "6.2.3-dev.79",
50
+ "@powerhousedao/vetra": "6.2.3-dev.79",
51
+ "@renown/sdk": "6.2.3-dev.79",
50
52
  "@sentry/node-core": "^10.52.0",
51
53
  "@tsdown/css": "0.23.0",
52
54
  "@vercel/nft": "^1.11.0",
@@ -55,7 +57,7 @@
55
57
  "change-case": "5.4.4",
56
58
  "cmd-ts": "0.15.0",
57
59
  "colorette": "2.0.20",
58
- "document-model": "6.2.3-dev.78",
60
+ "document-model": "6.2.3-dev.79",
59
61
  "dotenv": "16.4.7",
60
62
  "enquirer": "2.4.1",
61
63
  "kysely": "0.28.16",
@@ -77,8 +79,8 @@
77
79
  "ts-morph": "27.0.2",
78
80
  "write-package": "7.2.0",
79
81
  "zod": "^4.5.4",
80
- "@powerhousedao/desktop": "6.2.3-dev.78",
81
- "@powerhousedao/host-core": "6.2.3-dev.78"
82
+ "@powerhousedao/desktop": "6.2.3-dev.79",
83
+ "@powerhousedao/host-core": "6.2.3-dev.79"
82
84
  },
83
85
  "scripts": {
84
86
  "tsc": "tsc",
@@ -1,4 +0,0 @@
1
- import { s as runBuild } from "./build-Dj8qfSSe.mjs";
2
- export { runBuild };
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="434bcb33-429a-5735-a189-9449f68e3f53")}catch(e){}}();
4
- //# debugId=434bcb33-429a-5735-a189-9449f68e3f53
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-Dj8qfSSe.mjs","sources":["../src/services/build.ts"],"sourcesContent":["import {\n browserEntry,\n buildBrowserBuildConfig,\n buildNodeBuildConfig,\n findBundledSharedDeps,\n} from \"@powerhousedao/shared/build-config\";\nimport type {\n BuiltPiece,\n ExternalDependency,\n TraceFiles,\n} from \"@powerhousedao/shared/build-pieces\";\nimport {\n assertPiecesOutDir,\n buildPieces,\n expandEntryGlobs,\n createDetectionCache,\n externalDependencyVersions,\n projectPath,\n externalDepsPlugin,\n pieceListPath,\n planPieces,\n syncDistManifest,\n undeclaredExternalDependencies,\n} from \"@powerhousedao/shared/build-pieces\";\nimport {\n localPackageNames,\n packageStyleEntry,\n packageStylesheet,\n} from \"@powerhousedao/shared/clis/package-style\";\nimport {\n findSharedImports,\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n} from \"@powerhousedao/shared/connect\";\nimport { execSync } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport { nodeFileTrace } from \"@vercel/nft\";\nimport { detect, resolveCommand, type Agent } from \"package-manager-detector\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport type { BuildArgs } from \"../types.js\";\n\n// nft reports paths relative to its base; from \"/\" that is every path minus its root.\n// One cache per build: the traces of a project's packages share most files.\nexport function createTraceFiles(): TraceFiles {\n const cache = {};\n return (file) => traceFile(file, cache);\n}\n\nexport const traceFiles: TraceFiles = createTraceFiles();\n\nasync function traceFile(file: string, cache: object) {\n const { fileList, reasons } = await nodeFileTrace([file], {\n base: \"/\",\n cache,\n });\n const absolute = (p: string) => resolve(\"/\", p);\n return {\n fileList: new Set([...fileList].map(absolute)),\n reasons: new Map(\n [...reasons].map(([p, reason]) => [\n absolute(p),\n { parents: new Set([...reason.parents].map(absolute)) },\n ]),\n ),\n };\n}\n\n/**\n * A Powerhouse package's `powerhouse.manifest.json` \"name\" must match its\n * `package.json` \"name\" — Connect and the registry resolve installed versions\n * by treating the manifest name as the npm package name, so a mismatch silently\n * breaks resolution. Fail the build early if they diverge. No-op when the\n * project has no manifest (nothing to compare).\n */\nexport async function assertManifestNameMatchesPackage(projectPath: string) {\n const manifestPath = join(projectPath, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n\n const { name: packageName } = await readPackage({ cwd: projectPath });\n\n let manifestName: unknown;\n try {\n manifestName = (\n JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { name?: unknown }\n ).name;\n } catch {\n throw new Error(\n `Failed to parse \"powerhouse.manifest.json\" at ${manifestPath}. Make sure it is valid JSON.`,\n );\n }\n\n if (manifestName !== packageName) {\n throw new Error(\n `Package name mismatch — \"package.json\" and \"powerhouse.manifest.json\" must have the same \"name\":\\n` +\n ` package.json \"name\": ${JSON.stringify(packageName)}\\n` +\n ` powerhouse.manifest.json \"name\": ${JSON.stringify(manifestName)}\\n\\n` +\n `Update one so they match, then run the build again.`,\n );\n }\n}\n\n// builder-tools' PACKAGE_ROUTES_MODULE and HOST_ROUTES_DIR, without loading it\n// for packages with no routes.\nconst OFFERED_ROUTES_MODULE = \".ph/connect-routes.package.ts\";\nconst HOST_ROUTES_DIR = \"hosts/connect/routes\";\n\n// The manifest with `connectRoutes` set when the package offers routes; as it\n// is, byte for byte, when the flag is already right.\nfunction withOfferedRoutes(json: string, offers: boolean) {\n const manifest = JSON.parse(json) as { connectRoutes?: boolean };\n if (offers ? manifest.connectRoutes === true : !(\"connectRoutes\" in manifest))\n return json;\n if (offers) manifest.connectRoutes = true;\n else delete manifest.connectRoutes;\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\nconst slashes = (path: string) => path.replaceAll(\"\\\\\", \"/\");\n\n/** Sets `connectRoutes` in the manifest the package's root module imports,\n * leaving the project's file as it is. */\nexport function offeredRoutesManifest(projectRoot: string, offers: boolean) {\n // Vite's ids use forward slashes on Windows too.\n const manifestPath = slashes(join(projectRoot, \"powerhouse.manifest.json\"));\n return {\n name: \"ph-offered-routes-manifest\",\n transform(code: string, id: string) {\n if (slashes(id) !== manifestPath) return null;\n return { code: withOfferedRoutes(code, offers), map: null };\n },\n };\n}\n\n/** Sets `connectRoutes` in the dist copy of the manifest. */\nexport function markOfferedRoutes(dir: string, offers: boolean) {\n const manifestPath = join(dir, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n const json = readFileSync(manifestPath, \"utf-8\");\n writeFileSync(manifestPath, withOfferedRoutes(json, offers));\n}\n\nconst CONNECT_IMPORT = /^@powerhousedao\\/connect(\\/|$)/;\n\nconst CONNECT_IMPORT_HINT =\n \"Routes a package offers other Connects import @powerhousedao/connect-core instead (ContentOutlet, ModalDialog, useDriveRouteData, useNavRoutes and useSidebarMode from @powerhousedao/connect-core/router, SidebarItem from @powerhousedao/design-system/connect); only its own host's _app.tsx and overrides may use @powerhousedao/connect.\";\n\ntype ModuleGraph = {\n getModuleInfo(id: string): {\n importedIds: readonly string[];\n dynamicallyImportedIds: readonly string[];\n } | null;\n error(message: string): never;\n};\n\nfunction reachableFrom(graph: ModuleGraph, entry: string) {\n const reached = new Set<string>();\n const pending = [entry];\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (reached.has(id)) continue;\n reached.add(id);\n const info = graph.getModuleInfo(id);\n if (info) pending.push(...info.importedIds, ...info.dynamicallyImportedIds);\n }\n return reached;\n}\n\n/** Fails the build on an import of Connect that the offered routes reach, as\n * other Connects don't share Connect with the package; warns on one from the\n * rest of the package, which bundles a copy of the Connect modules it uses. */\nexport function noConnectImports(routesEntry: string, routesDir: string) {\n const imports = new Map<string, Set<string>>();\n // Module ids may spell a Windows path with either separator.\n const slash = (path: string) => path.replaceAll(\"\\\\\", \"/\");\n const isRoute = (id: string) =>\n slash(id) === slash(routesEntry) ||\n slash(id).startsWith(`${slash(routesDir)}/`);\n return {\n name: \"ph-offered-routes-imports\",\n resolveId(source: string, importer: string | undefined) {\n if (!importer || !CONNECT_IMPORT.test(source)) return null;\n // Before resolving it: a route file's import fails even unresolved.\n if (isRoute(importer)) {\n throw new Error(\n `${importer} imports \"${source}\". ${CONNECT_IMPORT_HINT}`,\n );\n }\n const sources = imports.get(importer) ?? new Set<string>();\n imports.set(importer, sources.add(source));\n return null;\n },\n buildEnd(this: ModuleGraph, error?: Error) {\n if (error || !imports.size) return;\n const entry = this.getModuleInfo(routesEntry)\n ? routesEntry\n : slash(routesEntry);\n const reached = reachableFrom(this, entry);\n const described = ([importer, sources]: [string, Set<string>]) =>\n `${importer} imports ${[...sources].map((s) => `\"${s}\"`).join(\", \")}`;\n const offered = [...imports].filter(([id]) => reached.has(id));\n if (offered.length) {\n this.error(\n `${offered.map(described).join(\"\\n\")}\\n${CONNECT_IMPORT_HINT}`,\n );\n }\n console.warn(\n `⚠ ${[...imports].map(described).join(\"\\n\")}\\nConnect isn't shared with the packages it loads, so the build bundles a copy of these modules, apart from the app's state. Import @powerhousedao/connect-core instead; a later version fails the build.`,\n );\n },\n };\n}\n\nexport async function runBuild(args: BuildArgs) {\n const { outDir } = args;\n const projectRoot = process.cwd();\n\n // Fail fast if the manifest name and package.json name have drifted apart.\n await assertManifestNameMatchesPackage(projectRoot);\n\n const target = {\n projectRoot,\n outDir,\n pieces: planPieces(projectRoot, outDir),\n };\n // Before any bundler runs: an out-dir a host will never read from is worth\n // nothing built, and the failure names what the contract is.\n assertPiecesOutDir(target);\n const sharedDeps = !args.noSharedDeps;\n\n const detectResult = await detect();\n const agent = detectResult?.agent ?? \"npm\";\n\n // Project routes type-check against the tree generated from them. The\n // probes mirror resolveConnectRoutesDir, so builder-tools loads only when needed.\n const routeProbes = [\n HOST_ROUTES_DIR,\n \".ph/connect-routes.gen.ts\",\n OFFERED_ROUTES_MODULE,\n ];\n if (routeProbes.some((p) => existsSync(join(projectRoot, p)))) {\n const { resolveConnectRoutesDir, syncConnectRoutes } =\n await import(\"@powerhousedao/builder-tools\");\n await syncConnectRoutes(projectRoot, resolveConnectRoutesDir(projectRoot));\n }\n // Connect reads the manifest's flag to load the package's routes.\n const offersRoutes = existsSync(join(projectRoot, OFFERED_ROUTES_MODULE));\n\n // Before any bundler runs, so declining leaves nothing half built.\n const typesOk = emitTypes(agent, outDir, projectRoot);\n if (!typesOk && !args.ignoreTypeErrors) {\n await confirmBuildDespiteTypeErrors();\n }\n\n // Shared by the browser, node and piece builds: nothing is traced twice.\n const detection = createDetectionCache();\n const trace = createTraceFiles();\n const routesEntry = join(projectRoot, OFFERED_ROUTES_MODULE);\n // Everything in the browser build is code Connect can load: native fails it.\n await tsdownBuild({\n ...buildBrowserBuildConfig({\n sharedDeps,\n plugins: [\n externalDepsPlugin(trace, new Map(), {\n root: projectRoot,\n browser: true,\n cache: detection,\n }),\n offeredRoutesManifest(projectRoot, offersRoutes),\n noConnectImports(routesEntry, join(projectRoot, HOST_ROUTES_DIR)),\n ],\n }),\n // The offered routes in the package's build: a module both import is one\n // chunk, which other Connects evaluate once. Absolute: a relative entry\n // is a glob, and globs skip `.ph`.\n ...(offersRoutes\n ? { entry: [...browserEntry, { \"connect-routes\": routesEntry }] }\n : {}),\n outDir: join(outDir, \"browser\"),\n });\n\n // Advisory: a shared dep the source imports but the output no longer\n // references as a bare import was inlined despite the external set.\n if (sharedDeps) {\n const imported = findSharedImportsInSources(projectRoot, browserEntry);\n const bundled = findBundledSharedDeps(\n imported,\n readDistBrowserFiles(join(outDir, \"browser\")),\n );\n if (bundled.length > 0) {\n console.warn(\n `⚠ shared deps bundled instead of externalized: ${bundled.join(\", \")} — check your neverBundle config`,\n );\n }\n }\n\n const external = new Map<string, ExternalDependency>();\n await tsdownBuild({\n ...buildNodeBuildConfig({\n sharedDeps,\n plugins: [\n // Editors never run on a host; document models run in Connect too.\n externalDepsPlugin(trace, external, {\n root: projectRoot,\n ignoreDirs: [\"editors\"],\n forbidDirs: [\"document-models\"],\n cache: detection,\n }),\n ],\n }),\n outDir: join(outDir, \"node\"),\n });\n const pkg = await readPackage({ cwd: projectRoot });\n assertExternalDependenciesDeclared(projectRoot, [...external.values()], pkg);\n\n // After the node build: it cleans <outDir>/node, where the pieces land. The\n // built list is the gate, so a `bundle:` entry is validated with no piece dir.\n let built: BuiltPiece[] = [];\n if (existsSync(pieceListPath(target))) {\n built = await buildPieces(\n target,\n {\n name: pkg.name,\n version: pkg.version,\n license: typeof pkg.license === \"string\" ? pkg.license : undefined,\n },\n { bundle: tsdownBuild, trace, cache: detection },\n );\n }\n syncDistManifest(\n target,\n built,\n externalDependencyVersions(external.values()),\n );\n markOfferedRoutes(outDir, offersRoutes);\n\n buildPackageStylesheet(agent, projectRoot, join(outDir, \"browser\"));\n\n // Last, so it is the line a finished build leaves on screen.\n if (!typesOk) console.warn(`\\n${UNSAFE_BUILD_WARNING}`);\n}\n\n// A package with a native addon or WebAssembly module stays external, so the\n// package's consumers must install it: devDependencies are skipped by every install.\nexport function assertExternalDependenciesDeclared(\n projectRoot: string,\n found: ExternalDependency[],\n pkg: Parameters<typeof undeclaredExternalDependencies>[1],\n) {\n for (const dep of found) {\n console.log(\n `${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`,\n );\n }\n const undeclared = undeclaredExternalDependencies(found, pkg);\n if (undeclared.length === 0) return;\n const lines = undeclared.map(\n (dep) =>\n ` ${dep.name}${dep.importer ? ` (imported by ${projectPath(projectRoot, dep.importer)})` : \"\"}`,\n );\n throw new Error(\n `Packages with native addons or WebAssembly modules must be listed in package.json \"dependencies\", \"optionalDependencies\" or \"peerDependencies\":\\n` +\n `${lines.join(\"\\n\")}\\n\\n` +\n `They stay external to the build, and installs of this package skip devDependencies.`,\n );\n}\n\n// tsc's build info outlives a deleted dist; with the declarations gone, tsc\n// would call the project up to date and emit nothing.\nfunction declarationsMissing(agent: Agent, projectRoot: string): boolean {\n const showConfig = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--showConfig\",\n ]);\n if (showConfig === null) return false;\n let options: {\n declaration?: boolean;\n composite?: boolean;\n declarationDir?: string;\n outDir?: string;\n };\n try {\n const output = execSync(\n `${showConfig.command} ${showConfig.args.join(\" \")}`,\n {\n cwd: projectRoot,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n },\n );\n options =\n (JSON.parse(output) as { compilerOptions?: typeof options })\n .compilerOptions ?? {};\n } catch {\n return false;\n }\n const dir = options.declarationDir ?? options.outDir;\n if (!dir || !(options.declaration || options.composite)) return false;\n const path = resolve(projectRoot, dir);\n return !existsSync(path) || readdirSync(path).length === 0;\n}\n\n// Runs tsc, which checks the project and writes its declarations either way.\n// Returns whether it reported no type errors.\nfunction emitTypes(agent: Agent, outDir: string, projectRoot: string): boolean {\n const force = declarationsMissing(agent, projectRoot);\n const tscCommand = resolveCommand(agent, \"execute-local\", [\n \"tsc\",\n \"--build\",\n ...(force ? [\"--force\"] : []),\n ]);\n if (tscCommand === null) {\n console.error(\n \"You need to have typescript installed to use the `build` command.\",\n );\n process.exit(1);\n }\n console.log(\"\\n▶ Type-checking and emitting types via tsc...\");\n try {\n execSync(`${tscCommand.command} ${tscCommand.args.join(\" \")}`, {\n stdio: \"inherit\",\n });\n console.log(\"✔ Types emitted to\", join(outDir, \"types\"));\n return true;\n } catch {\n return false;\n }\n}\n\n// The classes the browser build uses, and the package's tokens and rules, against\n// Connect's theme: the Connect that loads it has Tailwind's reset and Connect's classes.\nfunction buildPackageStylesheet(\n agent: Agent,\n projectRoot: string,\n browserDir: string,\n) {\n const command = resolveCommand(agent, \"execute-local\", [\n \"tailwindcss\",\n \"--input\",\n \"-\",\n \"--minify\",\n ]);\n if (command === null) {\n console.error(\n \"You need to have tailwindcss installed to use the `build` command.\",\n );\n process.exit(1);\n }\n const stylePath = join(projectRoot, \"style.css\");\n const style = existsSync(stylePath)\n ? readFileSync(stylePath, \"utf-8\")\n : undefined;\n const compiled = execSync(`${command.command} ${command.args.join(\" \")}`, {\n cwd: projectRoot,\n input: packageStyleEntry(style, {\n browserDir: sourcePath(projectRoot, browserDir),\n localPackages: localPackageNames(projectRoot),\n }),\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n // A package that imports large vendor CSS outgrows the 1 MB default.\n maxBuffer: 64 * 1024 * 1024,\n });\n // `ph build` with another out-dir (the switchboard runner's) leaves no dist/.\n mkdirSync(join(projectRoot, \"dist\"), { recursive: true });\n writeFileSync(\n join(projectRoot, \"dist/style.css\"),\n packageStylesheet(compiled),\n );\n}\n\n// A path for `@source`, relative to the project, with forward slashes.\nfunction sourcePath(projectRoot: string, path: string) {\n return `./${relative(projectRoot, resolve(projectRoot, path)).replaceAll(\"\\\\\", \"/\")}`;\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nconst TYPE_ERROR_RISK =\n \"A package built with type errors can load and still fail at runtime.\";\n\nconst UNSAFE_BUILD_WARNING =\n \"⚠ Built despite type errors. \" +\n TYPE_ERROR_RISK +\n \" Fix them before you publish or deploy it.\";\n\nasync function confirmBuildDespiteTypeErrors(): Promise<void> {\n const hint =\n \"Fix them and build again. --ignore-type-errors skips this check, at the risk of shipping that failure.\";\n if (!isInteractive()) {\n console.error(\n `\\n✘ tsc reported the type errors above. ${TYPE_ERROR_RISK}\\n${hint}`,\n );\n process.exit(1);\n }\n const enquirer = await import(\"enquirer\");\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `tsc reported the type errors above. ${TYPE_ERROR_RISK} Build anyway?`,\n initial: false,\n });\n confirmed = answer.confirmed;\n } catch {\n // Ctrl-C at the prompt is a decline.\n confirmed = false;\n }\n if (!confirmed) {\n console.error(`Build cancelled. ${hint}`);\n process.exit(1);\n }\n}\n\n/**\n * Every shared specifier imported from the entry sources; the post-build\n * scan compares these against the built output.\n *\n * Scoped to the specifiers the build actually externalizes: a specifier the\n * vendor does not publish (the bare `@powerhousedao/shared` root, an\n * unvendored subpath) is deliberately bundled, so reporting it as \"bundled\n * instead of externalized\" would be a false alarm.\n */\nfunction findSharedImportsInSources(root: string, globs: string[]): string[] {\n const found = new Set<string>();\n for (const file of expandEntryGlobs(root, globs)) {\n const src = readFileSync(file, \"utf8\");\n for (const spec of findSharedImports(\n src,\n EXTERNALIZABLE_SHARED_SPECIFIERS,\n )) {\n found.add(spec);\n }\n }\n return [...found].sort();\n}\n\n/**\n * The built JS outputs of a browser build (entry files and chunks).\n */\nfunction readDistBrowserFiles(\n dir: string,\n): { path: string; content: string }[] {\n const out: { path: string; content: string }[] = [];\n if (!existsSync(dir)) return out;\n const walk = (d: string) => {\n for (const e of readdirSync(d, { withFileTypes: true })) {\n const p = join(d, e.name);\n if (e.isDirectory()) walk(p);\n else if (e.isFile() && e.name.endsWith(\".js\")) {\n out.push({ path: p, content: readFileSync(p, \"utf8\") });\n }\n }\n };\n walk(dir);\n return out;\n}\n"],"names":["tsdownBuild"],"mappings":";;;;;;;;;;;;;;AAkDA,SAAgB,mBAA+B;CAC7C,MAAM,QAAQ,CAAC;CACf,QAAQ,SAAS,UAAU,MAAM,KAAK;AACxC;AAIA,eAAe,UAAU,MAAc,OAAe;CACpD,MAAM,EAAE,UAAU,YAAY,MAAM,cAAc,CAAC,IAAI,GAAG;EACxD,MAAM;EACN;CACF,CAAC;CACD,MAAM,YAAY,MAAc,QAAQ,KAAK,CAAC;CAC9C,OAAO;EACL,UAAU,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,QAAQ,CAAC;EAC7C,SAAS,IAAI,IACX,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,YAAY,CAChC,SAAS,CAAC,GACV,EAAE,SAAS,IAAI,IAAI,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,IAAI,QAAQ,CAAC,EAAE,CACxD,CAAC,CACH;CACF;AACF;;;;;;;;AASA,eAAsB,iCAAiC,aAAq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"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkHost, type HostIssue } from \"@powerhousedao/host-core\";\nimport { CALLER_CWD_ENV } from \"@powerhousedao/shared/clis/command-names\";\nimport { loadProjectEnv } from \"@powerhousedao/shared/clis/project-env\";\nimport dotenv from \"dotenv\";\n\nexport interface HostCheckArgs {\n host: string;\n envFile?: string;\n verb?: string;\n projectRoot?: string;\n}\n\n/** Without `envFile`: what `ph run` sees (project .env under process env). */\nasync function checkEnv(\n projectRoot: string,\n envFile: string | undefined,\n): Promise<Record<string, string | undefined>> {\n if (envFile === undefined) {\n loadProjectEnv(projectRoot);\n // A snapshot: a .env a runner's checkBoot loads later never reaches it.\n return { ...process.env };\n }\n const from = process.env[CALLER_CWD_ENV] ?? process.cwd();\n try {\n return dotenv.parse(await readFile(path.resolve(from, envFile), \"utf8\"));\n } catch (error) {\n throw new Error(\n `Cannot read the env file ${envFile}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function formatHostIssues(\n file: string,\n issues: readonly HostIssue[],\n deferred: number,\n): string {\n if (issues.length === 0) {\n const note =\n deferred > 0\n ? `\\n ${deferred} output token(s) checked declared-only`\n : \"\";\n return `${file}: ok${note}`;\n }\n const byFile = new Map<string, HostIssue[]>();\n for (const issue of issues) {\n byFile.set(issue.file, [...(byFile.get(issue.file) ?? []), issue]);\n }\n const blocks = [...byFile].map(([at, found]) => {\n const lines = found.flatMap((issue) => {\n const where = issue.path ? `${issue.path}: ` : \"\";\n const line = ` ${issue.stage} ${where}${issue.message.replaceAll(\"\\n\", \"\\n \")}`;\n return issue.hint ? [line, ` hint: ${issue.hint}`] : [line];\n });\n return [at, ...lines].join(\"\\n\");\n });\n return blocks.join(\"\\n\\n\");\n}\n\n/** `ph host check <host>`: every issue `ph run` would hit; exits 1 on any. */\nexport async function runHostCheck(\n args: HostCheckArgs,\n): Promise<{ output: string; exitCode: number }> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const env = await checkEnv(projectRoot, args.envFile);\n const { issues, deferred } = await checkHost(args.host, {\n projectRoot,\n env,\n ...(args.verb !== undefined ? { verb: args.verb } : {}),\n });\n return {\n output: formatHostIssues(\n `hosts/${args.host}/host.js`,\n issues,\n deferred.length,\n ),\n exitCode: issues.length > 0 ? 1 : 0,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;AAeA,eAAe,SACb,aACA,SAC6C;CAC7C,IAAI,YAAY,KAAA,GAAW;EACzB,eAAe,WAAW;EAE1B,OAAO,EAAE,GAAG,QAAQ,IAAI;CAC1B;CACA,MAAM,OAAO,QAAQ,IAAI,mBAAmB,QAAQ,IAAI;CACxD,IAAI;EACF,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,QAAQ,MAAM,OAAO,GAAG,MAAM,CAAC;CACzE,SAAS,OAAO;EACd,MAAM,IAAI,MACR,4BAA4B,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC7F,EAAE,OAAO,MAAM,CACjB;CACF;AACF;AAEA,SAAgB,iBACd,MACA,QACA,UACQ;CACR,IAAI,OAAO,WAAW,GAKpB,OAAO,GAAG,KAAK,MAHb,WAAW,IACP,OAAO,SAAS,0CAChB;CAGR,MAAM,yBAAS,IAAI,IAAyB;CAC5C,KAAK,MAAM,SAAS,QAClB,OAAO,IAAI,MAAM,MAAM,CAAC,GAAI,OAAO,IAAI,MAAM,IAAI,KAAK,CAAC,GAAI,KAAK,CAAC;CAUnE,OARe,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,WAAW;EAM9C,OAAO,CAAC,IAAI,GALE,MAAM,SAAS,UAAU;GACrC,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,KAAK,MAAM;GAC/C,MAAM,OAAO,KAAK,MAAM,MAAM,IAAI,QAAQ,MAAM,QAAQ,WAAW,MAAM,QAAQ;GACjF,OAAO,MAAM,OAAO,CAAC,MAAM,aAAa,MAAM,MAAM,IAAI,CAAC,IAAI;EAC/D,CACmB,CAAC,CAAC,CAAC,KAAK,IAAI;CACjC,CACY,CAAC,CAAC,KAAK,MAAM;AAC3B;;AAGA,eAAsB,aACpB,MAC+C;CAC/C,MAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;CACpD,MAAM,MAAM,MAAM,SAAS,aAAa,KAAK,OAAO;CACpD,MAAM,EAAE,QAAQ,aAAa,MAAM,UAAU,KAAK,MAAM;EACtD;EACA;EACA,GAAI,KAAK,SAAS,KAAA,IAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;CACvD,CAAC;CACD,OAAO;EACL,QAAQ,iBACN,SAAS,KAAK,KAAK,WACnB,QACA,SAAS,MACX;EACA,UAAU,OAAO,SAAS,IAAI,IAAI;CACpC;AACF","debug_id":"02f160a6-a4c4-522b-a029-b4fe81ed743c"}
@@ -1,39 +0,0 @@
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]="16b692d9-f93e-5f41-ba91-7769dbfcbd4e")}catch(e){}}();
3
- import { r as buildStudioConnectOverride } from "./cli-connect-override-C65On7dE.mjs";
4
- import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
5
- import { createServer, mergeConfig } from "vite";
6
- //#region src/services/connect-studio.ts
7
- async function runConnectStudio(args, customLogger, callerOverride, { routes, cacheDir } = {}) {
8
- const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } = args;
9
- const mode = "development";
10
- const dirname = process.cwd();
11
- const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);
12
- const baseConfig = getConnectBaseViteConfig({
13
- mode,
14
- dirname,
15
- cliConnectOverride,
16
- routes,
17
- cacheDir
18
- });
19
- const config = mergeConfig(baseConfig, {
20
- server: {
21
- port,
22
- host,
23
- open,
24
- cors,
25
- strictPort
26
- },
27
- customLogger
28
- });
29
- const server = await createServer(config);
30
- await server.listen();
31
- if (printUrls) server.printUrls();
32
- if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });
33
- return server;
34
- }
35
- //#endregion
36
- export { runConnectStudio as t };
37
-
38
- //# sourceMappingURL=connect-studio-CEpyVlJ_.mjs.map
39
- //# debugId=16b692d9-f93e-5f41-ba91-7769dbfcbd4e
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-studio-CEpyVlJ_.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type { InlineConfig, Logger } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\n\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?: PHConnectRuntimeConfig,\n { routes, cacheDir }: { routes?: string | false; cacheDir?: string } = {},\n) {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n\n const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride,\n routes,\n cacheDir,\n });\n\n const devServerConfig: InlineConfig = {\n server: { port, host, open, cors, strictPort },\n customLogger,\n };\n\n const config = mergeConfig(baseConfig, devServerConfig);\n\n const server = await createServer(config);\n\n await server.listen();\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n return server;\n}\n"],"names":[],"mappings":";;;;;;AAOA,eAAsB,iBACpB,MACA,cACA,gBACA,EAAE,QAAQ,aAA6D,CAAC,GACxE;CACA,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAE5B,MAAM,qBAAqB,2BAA2B,MAAM,cAAc;CAE1E,MAAM,aAAa,yBAAyB;EAC1C;EACA;EACA;EACA;EACA;CACF,CAAC;CAOD,MAAM,SAAS,YAAY,YAAY;EAJrC,QAAQ;GAAE;GAAM;GAAM;GAAM;GAAM;EAAW;EAC7C;CAGmD,CAAC;CAEtD,MAAM,SAAS,MAAM,aAAa,MAAM;CAExC,MAAM,OAAO,OAAO;CAEpB,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;CAC7D,OAAO;AACT","debug_id":"16b692d9-f93e-5f41-ba91-7769dbfcbd4e"}