@powerhousedao/ph-cli 6.2.3-dev.77 → 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.
- package/dist/{build-Dj8qfSSe.mjs → build-DUzhIPb7.mjs} +8 -55
- package/dist/build-DUzhIPb7.mjs.map +1 -0
- package/dist/build-FoZl36TM.mjs +4 -0
- package/dist/{check-9KDSF1Wj.mjs → check-DDy1o6Vr.mjs} +10 -7
- package/dist/check-DDy1o6Vr.mjs.map +1 -0
- package/dist/{cli-connect-override-BrS-X8Rs.mjs → cli-connect-override-By7u9IVR.mjs} +4 -4
- package/dist/{cli-connect-override-BrS-X8Rs.mjs.map → cli-connect-override-By7u9IVR.mjs.map} +1 -1
- package/dist/cli.mjs +6 -10
- package/dist/cli.mjs.map +1 -1
- package/dist/{compound-Gjt5rBfF-BmSW1XPB.mjs → compound-Cfqa5Jal-B5rkCmIj.mjs} +24 -39
- package/dist/compound-Cfqa5Jal-B5rkCmIj.mjs.map +1 -0
- package/dist/{connect-build-B5nYqlLc.mjs → connect-build-BBAZuqpo.mjs} +5 -5
- package/dist/{connect-build-B5nYqlLc.mjs.map → connect-build-BBAZuqpo.mjs.map} +1 -1
- package/dist/{connect-config-Bi95JhNG.mjs → connect-config-ghJlOd-x.mjs} +4 -4
- package/dist/{connect-config-Bi95JhNG.mjs.map → connect-config-ghJlOd-x.mjs.map} +1 -1
- package/dist/{connect-plugin-configs-BwYEbQSY.mjs → connect-plugin-configs-BoPbxD9u.mjs} +4 -4
- package/dist/{connect-plugin-configs-BwYEbQSY.mjs.map → connect-plugin-configs-BoPbxD9u.mjs.map} +1 -1
- package/dist/connect-studio-BaVeuul3.mjs +78 -0
- package/dist/connect-studio-BaVeuul3.mjs.map +1 -0
- package/dist/{connect-studio-Co_UNyEC.mjs → connect-studio-CfggUldW.mjs} +3 -3
- package/dist/{dist-BVqNlv1z.mjs → dist-Bd6sSt7Y.mjs} +120 -21
- package/dist/dist-Bd6sSt7Y.mjs.map +1 -0
- package/dist/{explain-CPD1tzoV.mjs → explain-C9zER5xn.mjs} +6 -17
- package/dist/explain-C9zER5xn.mjs.map +1 -0
- package/dist/export-CrIz2spe.mjs +42 -0
- package/dist/export-CrIz2spe.mjs.map +1 -0
- package/dist/{generate-all-CaAHbviS.mjs → generate-all-DgEFOXwU.mjs} +4 -4
- package/dist/{generate-all-CaAHbviS.mjs.map → generate-all-DgEFOXwU.mjs.map} +1 -1
- package/dist/{generate-desktop-shell-BdXDiS5o.mjs → generate-desktop-shell-BXcGvbms.mjs} +4 -4
- package/dist/{generate-desktop-shell-BdXDiS5o.mjs.map → generate-desktop-shell-BXcGvbms.mjs.map} +1 -1
- package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
- package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
- package/dist/{generate-piece-U3tP-Sex.mjs → generate-piece-C6ymlErL.mjs} +6 -6
- package/dist/{generate-piece-U3tP-Sex.mjs.map → generate-piece-C6ymlErL.mjs.map} +1 -1
- package/dist/{generate-piece-action-DbxrzfKY.mjs → generate-piece-action-uYRdKtQA.mjs} +5 -5
- package/dist/{generate-piece-action-DbxrzfKY.mjs.map → generate-piece-action-uYRdKtQA.mjs.map} +1 -1
- package/dist/{generate-piece-trigger-CqVOcL9g.mjs → generate-piece-trigger-CZaDD-cc.mjs} +5 -5
- package/dist/{generate-piece-trigger-CqVOcL9g.mjs.map → generate-piece-trigger-CZaDD-cc.mjs.map} +1 -1
- package/dist/{generate-processor-B9Umgjy9.mjs → generate-processor-BVjOsfjJ.mjs} +5 -5
- package/dist/{generate-processor-B9Umgjy9.mjs.map → generate-processor-BVjOsfjJ.mjs.map} +1 -1
- package/dist/{generate-subgraph-DRrInOOv.mjs → generate-subgraph-CrHbYK91.mjs} +5 -5
- package/dist/{generate-subgraph-DRrInOOv.mjs.map → generate-subgraph-CrHbYK91.mjs.map} +1 -1
- package/dist/get-version-_coBX13A.mjs +11 -0
- package/dist/get-version-_coBX13A.mjs.map +1 -0
- package/dist/{index-7hbcAZpm.d.mts → index-DdpGYzN0.d.mts} +4 -20
- package/dist/{index-7hbcAZpm.d.mts.map → index-DdpGYzN0.d.mts.map} +1 -1
- package/dist/{init-ScuT3z7P.mjs → init-Ch1rCksS.mjs} +12 -10
- package/dist/{init-ScuT3z7P.mjs.map → init-Ch1rCksS.mjs.map} +1 -1
- package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
- package/dist/mcp-CZ02pj76.mjs +262 -0
- package/dist/mcp-CZ02pj76.mjs.map +1 -0
- package/dist/member-config-8Vwys-4O.mjs +154 -0
- package/dist/member-config-8Vwys-4O.mjs.map +1 -0
- package/dist/{migrate-b38W7NH_.mjs → migrate-CIJaE3iZ.mjs} +4 -4
- package/dist/{migrate-b38W7NH_.mjs.map → migrate-CIJaE3iZ.mjs.map} +1 -1
- package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
- package/dist/{ph-cli-commands-kRpc2dhi.mjs → ph-cli-commands-B37zr8uN.mjs} +121 -39
- package/dist/ph-cli-commands-B37zr8uN.mjs.map +1 -0
- package/dist/ph-cli-commands-S3ArIR8q.mjs +4 -0
- package/dist/{run-sugar-BJxPKwlM.mjs → run-sugar-BzGnofrW.mjs} +4 -4
- package/dist/{run-sugar-BJxPKwlM.mjs.map → run-sugar-BzGnofrW.mjs.map} +1 -1
- package/dist/runners/connect.d.mts +5 -33
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +6 -6
- package/dist/runners/switchboard.d.mts +1161 -37
- package/dist/runners/switchboard.d.mts.map +1 -1
- package/dist/runners/switchboard.mjs +52 -69
- package/dist/runners/switchboard.mjs.map +1 -1
- package/dist/{schemas-D5N5U_Mf.mjs → schemas-Cnv5AnQT.mjs} +18 -4
- package/dist/{schemas-D5N5U_Mf.mjs.map → schemas-Cnv5AnQT.mjs.map} +1 -1
- package/dist/scripts/generate-commands-docs.ts +4 -0
- package/dist/{start-run-CDZ3YAr9.mjs → start-run-BAQDM5Bu.mjs} +4 -4
- package/dist/{start-run-CDZ3YAr9.mjs.map → start-run-BAQDM5Bu.mjs.map} +1 -1
- package/dist/{switchboard-h4-XgP1h.mjs → switchboard-BI35F5H7.mjs} +40 -8
- package/dist/switchboard-BI35F5H7.mjs.map +1 -0
- package/dist/switchboard-DohZ1tbp.mjs +4 -0
- package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
- package/dist/{vetra-DO5eUgAo.mjs → vetra-C9fsChId.mjs} +75 -127
- package/dist/vetra-C9fsChId.mjs.map +1 -0
- package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
- package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
- package/package.json +15 -13
- package/dist/build-C78yPntL.mjs +0 -4
- package/dist/build-Dj8qfSSe.mjs.map +0 -1
- package/dist/check-9KDSF1Wj.mjs.map +0 -1
- package/dist/compound-Gjt5rBfF-BmSW1XPB.mjs.map +0 -1
- package/dist/connect-studio-DGWUidCV.mjs +0 -39
- package/dist/connect-studio-DGWUidCV.mjs.map +0 -1
- package/dist/dist-BVqNlv1z.mjs.map +0 -1
- package/dist/explain-CPD1tzoV.mjs.map +0 -1
- package/dist/install-added-dependencies-DVSbzler.mjs +0 -33
- package/dist/install-added-dependencies-DVSbzler.mjs.map +0 -1
- package/dist/ph-cli-commands-BQU6lpyM.mjs +0 -4
- package/dist/ph-cli-commands-kRpc2dhi.mjs.map +0 -1
- package/dist/switchboard-C5zgkRl2.mjs +0 -4
- package/dist/switchboard-h4-XgP1h.mjs.map +0 -1
- package/dist/vetra-DO5eUgAo.mjs.map +0 -1
|
@@ -0,0 +1,262 @@
|
|
|
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]="e8873125-e6ea-5129-a5d2-7b611d83498f")}catch(e){}}();
|
|
3
|
+
import { t as getVersion } from "./get-version-_coBX13A.mjs";
|
|
4
|
+
import { i as restartVetra, l as readVetraRuntime, n as currentPhCliVetraCommand, r as ensureVetra, t as VetraStartError } from "./vetra-launch-DQDZxGTV.mjs";
|
|
5
|
+
import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
9
|
+
import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
10
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
11
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
12
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
13
|
+
import { CallToolRequestSchema, CallToolResultSchema, ListResourceTemplatesRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
14
|
+
import { createServer } from "@powerhousedao/reactor-mcp";
|
|
15
|
+
//#region src/services/mcp.ts
|
|
16
|
+
const CALL_TIMEOUT_MS = 6e5;
|
|
17
|
+
const CONFIG_FILE = "powerhouse.config.json";
|
|
18
|
+
/** The nearest directory at or above `start` holding powerhouse.config.json. */
|
|
19
|
+
function findProjectDir(start) {
|
|
20
|
+
let dir = path.resolve(start);
|
|
21
|
+
for (;;) {
|
|
22
|
+
if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;
|
|
23
|
+
const parent = path.dirname(dir);
|
|
24
|
+
if (parent === dir) return void 0;
|
|
25
|
+
dir = parent;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const reactorlessClient = new Proxy({}, { get(_target, property) {
|
|
29
|
+
if (property === "then") return void 0;
|
|
30
|
+
return () => {
|
|
31
|
+
throw new Error("reactor-mcp's local tool list has no reactor");
|
|
32
|
+
};
|
|
33
|
+
} });
|
|
34
|
+
/** reactor-mcp's own server, in-process, for the tool list and resources. */
|
|
35
|
+
async function connectLocalReactorMcp() {
|
|
36
|
+
const server = await createServer({ client: reactorlessClient });
|
|
37
|
+
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
|
|
38
|
+
await server.connect(serverSide);
|
|
39
|
+
const client = new Client({
|
|
40
|
+
name: "ph-mcp",
|
|
41
|
+
version: getVersion()
|
|
42
|
+
});
|
|
43
|
+
await client.connect(clientSide);
|
|
44
|
+
return client;
|
|
45
|
+
}
|
|
46
|
+
function toolError(message) {
|
|
47
|
+
return {
|
|
48
|
+
isError: true,
|
|
49
|
+
content: [{
|
|
50
|
+
type: "text",
|
|
51
|
+
text: message
|
|
52
|
+
}]
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** The call never reached a live session: Vetra is down, or restarted since. */
|
|
56
|
+
function isStaleConnection(error) {
|
|
57
|
+
if (error instanceof StreamableHTTPError) return error.code === 404 || error.code === 400;
|
|
58
|
+
for (let e = error; e instanceof Error; e = e.cause) if (e.code === "ECONNREFUSED") return true;
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
const restartVetraTool = {
|
|
62
|
+
name: "restartVetra",
|
|
63
|
+
description: "Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. Use it after a change Vetra reads only at startup, such as the reactor or packages settings in powerhouse.config.json; Studio restarts by itself for connect.* changes. Returns the new Connect, Switchboard and MCP URLs.",
|
|
64
|
+
inputSchema: {
|
|
65
|
+
type: "object",
|
|
66
|
+
properties: {}
|
|
67
|
+
},
|
|
68
|
+
outputSchema: {
|
|
69
|
+
type: "object",
|
|
70
|
+
properties: {
|
|
71
|
+
pid: { type: "number" },
|
|
72
|
+
connectUrl: { type: "string" },
|
|
73
|
+
switchboardUrl: { type: "string" },
|
|
74
|
+
mcpUrl: { type: "string" }
|
|
75
|
+
},
|
|
76
|
+
required: ["pid", "mcpUrl"]
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
function vetraUrls(record) {
|
|
80
|
+
return {
|
|
81
|
+
pid: record.pid,
|
|
82
|
+
...record.connectUrl ? { connectUrl: record.connectUrl } : {},
|
|
83
|
+
switchboardUrl: record.switchboardUrl ?? `http://localhost:${record.switchboardPort}/graphql`,
|
|
84
|
+
mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function projectName(projectDir) {
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).name;
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
var Upstream = class {
|
|
95
|
+
projectDir;
|
|
96
|
+
options;
|
|
97
|
+
#client;
|
|
98
|
+
/** The Vetra the client talks to; another pid in the record means it restarted. */
|
|
99
|
+
#pid;
|
|
100
|
+
/** The calls waiting on the connection, told how Vetra's start goes. */
|
|
101
|
+
#waiting = /* @__PURE__ */ new Set();
|
|
102
|
+
constructor(projectDir, options) {
|
|
103
|
+
this.projectDir = projectDir;
|
|
104
|
+
this.options = options;
|
|
105
|
+
}
|
|
106
|
+
get(onProgress) {
|
|
107
|
+
if (this.#client && this.#pid !== void 0 && this.projectDir) {
|
|
108
|
+
if (readVetraRuntime(this.projectDir)?.pid !== this.#pid) this.reset();
|
|
109
|
+
}
|
|
110
|
+
this.#client ??= this.#connect(ensureVetra).catch((error) => {
|
|
111
|
+
this.#client = void 0;
|
|
112
|
+
throw error;
|
|
113
|
+
});
|
|
114
|
+
return this.#waitWith(this.#client, onProgress);
|
|
115
|
+
}
|
|
116
|
+
async #waitWith(task, onProgress) {
|
|
117
|
+
if (onProgress) this.#waiting.add(onProgress);
|
|
118
|
+
try {
|
|
119
|
+
return await task;
|
|
120
|
+
} finally {
|
|
121
|
+
if (onProgress) this.#waiting.delete(onProgress);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
#report = (message) => {
|
|
125
|
+
for (const progress of this.#waiting) progress(message);
|
|
126
|
+
};
|
|
127
|
+
reset() {
|
|
128
|
+
const stale = this.#client;
|
|
129
|
+
this.#client = void 0;
|
|
130
|
+
this.#pid = void 0;
|
|
131
|
+
stale?.then((client) => client.close()).catch(() => {});
|
|
132
|
+
}
|
|
133
|
+
/** Restarts Vetra and connects to the new one; resolves to its record. */
|
|
134
|
+
async restart(onProgress) {
|
|
135
|
+
this.reset();
|
|
136
|
+
let record;
|
|
137
|
+
const connected = this.#connect(async (options) => {
|
|
138
|
+
record = await restartVetra(options);
|
|
139
|
+
return record;
|
|
140
|
+
});
|
|
141
|
+
this.#client = connected.catch((error) => {
|
|
142
|
+
this.#client = void 0;
|
|
143
|
+
throw error;
|
|
144
|
+
});
|
|
145
|
+
await this.#waitWith(this.#client, onProgress);
|
|
146
|
+
return record;
|
|
147
|
+
}
|
|
148
|
+
async #connect(start) {
|
|
149
|
+
const { projectDir } = this;
|
|
150
|
+
if (!projectDir) throw new VetraStartError(`No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \`ph mcp\` inside the project, or pass --project-dir.`);
|
|
151
|
+
const name = projectName(projectDir);
|
|
152
|
+
if (!name) throw new VetraStartError(`${projectDir} has no package.json name.`);
|
|
153
|
+
console.error(`[ph mcp] connecting to Vetra for ${name}...`);
|
|
154
|
+
const record = await start({
|
|
155
|
+
projectDir,
|
|
156
|
+
projectName: name,
|
|
157
|
+
switchboardPort: resolveSwitchboardPortDefault(),
|
|
158
|
+
command: this.options.vetraCommand ?? currentPhCliVetraCommand(),
|
|
159
|
+
timeoutMs: this.options.startTimeoutSeconds * 1e3,
|
|
160
|
+
onProgress: this.#report
|
|
161
|
+
});
|
|
162
|
+
const { mcpUrl } = vetraUrls(record);
|
|
163
|
+
const client = new Client({
|
|
164
|
+
name: "ph-mcp",
|
|
165
|
+
version: getVersion()
|
|
166
|
+
});
|
|
167
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));
|
|
168
|
+
this.#pid = record.pid;
|
|
169
|
+
console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);
|
|
170
|
+
return client;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
async function forwardToolCall(upstream, params, signal, onProgress) {
|
|
174
|
+
for (let attempt = 0;; attempt++) {
|
|
175
|
+
const client = await upstream.get(onProgress);
|
|
176
|
+
try {
|
|
177
|
+
return await client.request({
|
|
178
|
+
method: "tools/call",
|
|
179
|
+
params
|
|
180
|
+
}, CallToolResultSchema, {
|
|
181
|
+
signal,
|
|
182
|
+
timeout: CALL_TIMEOUT_MS
|
|
183
|
+
});
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (attempt > 0 || !isStaleConnection(error)) throw error;
|
|
186
|
+
upstream.reset();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */
|
|
191
|
+
async function startMcpLauncher(options) {
|
|
192
|
+
console.log = console.error;
|
|
193
|
+
console.info = console.error;
|
|
194
|
+
const projectDir = findProjectDir(options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd());
|
|
195
|
+
if (projectDir) process.chdir(projectDir);
|
|
196
|
+
const local = await connectLocalReactorMcp();
|
|
197
|
+
const upstream = new Upstream(projectDir, options);
|
|
198
|
+
const server = new Server(local.getServerVersion() ?? {
|
|
199
|
+
name: "reactor-mcp-server",
|
|
200
|
+
version: ""
|
|
201
|
+
}, {
|
|
202
|
+
capabilities: {
|
|
203
|
+
tools: {},
|
|
204
|
+
resources: {}
|
|
205
|
+
},
|
|
206
|
+
instructions: local.getInstructions()
|
|
207
|
+
});
|
|
208
|
+
server.setRequestHandler(ListToolsRequestSchema, async (request) => {
|
|
209
|
+
const listed = await local.listTools(request.params);
|
|
210
|
+
return {
|
|
211
|
+
...listed,
|
|
212
|
+
tools: [...listed.tools, restartVetraTool]
|
|
213
|
+
};
|
|
214
|
+
});
|
|
215
|
+
server.setRequestHandler(ListResourcesRequestSchema, (request) => local.listResources(request.params));
|
|
216
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) => local.listResourceTemplates(request.params));
|
|
217
|
+
server.setRequestHandler(ReadResourceRequestSchema, (request) => local.readResource(request.params));
|
|
218
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
219
|
+
const token = request.params._meta?.progressToken;
|
|
220
|
+
let progress = 0;
|
|
221
|
+
const onProgress = (message) => {
|
|
222
|
+
if (token === void 0) {
|
|
223
|
+
console.error(`[ph mcp] ${message}`);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
extra.sendNotification({
|
|
227
|
+
method: "notifications/progress",
|
|
228
|
+
params: {
|
|
229
|
+
progressToken: token,
|
|
230
|
+
progress: ++progress,
|
|
231
|
+
message
|
|
232
|
+
}
|
|
233
|
+
}).catch(() => {});
|
|
234
|
+
};
|
|
235
|
+
try {
|
|
236
|
+
if (request.params.name === "restartVetra") {
|
|
237
|
+
const urls = vetraUrls(await upstream.restart(onProgress));
|
|
238
|
+
return {
|
|
239
|
+
content: [{
|
|
240
|
+
type: "text",
|
|
241
|
+
text: JSON.stringify(urls)
|
|
242
|
+
}],
|
|
243
|
+
structuredContent: urls
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
return await forwardToolCall(upstream, request.params, extra.signal, onProgress);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
if (error instanceof McpError) throw error;
|
|
249
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
250
|
+
return toolError(error instanceof VetraStartError ? message : `reactor-mcp request failed: ${message}`);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
const transport = new StdioServerTransport();
|
|
254
|
+
transport.onclose = () => process.exit(0);
|
|
255
|
+
process.stdin.once("end", () => process.exit(0));
|
|
256
|
+
await server.connect(transport);
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
|
259
|
+
export { startMcpLauncher };
|
|
260
|
+
|
|
261
|
+
//# sourceMappingURL=mcp-CZ02pj76.mjs.map
|
|
262
|
+
//# debugId=e8873125-e6ea-5129-a5d2-7b611d83498f
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-CZ02pj76.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ,OAAO,KAAA;CAChC,aAAa;EACX,MAAM,IAAI,MAAM,8CAA8C;CAChE;AACF,EACF,CAAC;;AAGD,eAAe,yBAA0C;CACvD,MAAM,SAAS,MAAM,aAAa,EAAE,QAAQ,kBAAkB,CAAC;CAC/D,MAAM,CAAC,YAAY,cAAc,kBAAkB,iBAAiB;CACpE,MAAM,OAAO,QAAQ,UAAU;CAC/B,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAU,SAAS,WAAW;CAAE,CAAC;CACnE,MAAM,OAAO,QAAQ,UAAU;CAC/B,OAAO;AACT;AAEA,SAAS,UAAU,SAAiC;CAClD,OAAO;EAAE,SAAS;EAAM,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;CAAE;AACrE;;AAGA,SAAS,kBAAkB,OAAyB;CAClD,IAAI,iBAAiB,qBACnB,OAAO,MAAM,SAAS,OAAO,MAAM,SAAS;CAE9C,KAAK,IAAI,IAAI,OAAO,aAAa,OAAO,IAAI,EAAE,OAC5C,IAAK,EAA4B,SAAS,gBAAgB,OAAO;CAEnE,OAAO;AACT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AAM,CACnC;CACA,OAAO,kBAAkB,uBAAuB,OAAO,SAAS,UAAU;EAExE,MAAM,QAAQ,QAAQ,OAAO,OAAO;EACpC,IAAI,WAAW;EACf,MAAM,cAAwB,YAAY;GACxC,IAAI,UAAU,KAAA,GAAW;IACvB,QAAQ,MAAM,YAAY,SAAS;IACnC;GACF;GACA,MACG,iBAAiB;IAChB,QAAQ;IACR,QAAQ;KAAE,eAAe;KAAO,UAAU,EAAE;KAAU;IAAQ;GAChE,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EACnB;EACA,IAAI;GACF,IAAI,QAAQ,OAAO,SAAA,gBAA6B;IAC9C,MAAM,OAAO,UAAU,MAAM,SAAS,QAAQ,UAAU,CAAC;IACzD,OAAO;KACL,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"e8873125-e6ea-5129-a5d2-7b611d83498f"}
|
|
@@ -0,0 +1,154 @@
|
|
|
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]="712c7d89-0f2a-5dd8-9a25-a6d072f14933")}catch(e){}}();
|
|
3
|
+
import { c as primaryBackend, f as protocolEnv, p as reactorBlockToSwitchboardConfig, t as assertProtocolConsistency } from "./dist-Bd6sSt7Y.mjs";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { mergeSwitchboardConfig, switchboardConfigLayerSchema } from "@powerhousedao/switchboard/config";
|
|
7
|
+
import { envNamesBeforeProjectEnv, isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
8
|
+
import dotenv from "dotenv";
|
|
9
|
+
//#region src/runners/member-config.ts
|
|
10
|
+
function readDotenv(cwd) {
|
|
11
|
+
try {
|
|
12
|
+
return dotenv.parse(fs.readFileSync(path.join(cwd, ".env")));
|
|
13
|
+
} catch {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const shellNamesByEnv = /* @__PURE__ */ new WeakMap();
|
|
18
|
+
/** Records which names of `env` the shell set, before a `.env` loads into it. */
|
|
19
|
+
function rememberShellNames(env, names) {
|
|
20
|
+
shellNamesByEnv.set(env, new Set(names));
|
|
21
|
+
}
|
|
22
|
+
function shellNamesOf(env) {
|
|
23
|
+
let names = shellNamesByEnv.get(env);
|
|
24
|
+
if (!names) {
|
|
25
|
+
names = (env === process.env ? envNamesBeforeProjectEnv() : void 0) ?? new Set(Object.keys(env));
|
|
26
|
+
shellNamesByEnv.set(env, names);
|
|
27
|
+
}
|
|
28
|
+
return names;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Splits `env` into the shell's values and the `.env` the switchboard server
|
|
32
|
+
* loads from `cwd` (the same file). A name the shell set stays the shell's,
|
|
33
|
+
* whatever the file says.
|
|
34
|
+
*/
|
|
35
|
+
function memberEnvOf(env, cwd = process.cwd()) {
|
|
36
|
+
const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);
|
|
37
|
+
const shellNames = shellNamesOf(env);
|
|
38
|
+
const shell = {};
|
|
39
|
+
for (const [name, value] of Object.entries(env)) if (file[name] === void 0 || shellNames.has(name)) shell[name] = value;
|
|
40
|
+
const fromFile = {};
|
|
41
|
+
for (const [name, value] of Object.entries(file)) if (!shellNames.has(name)) fromFile[name] = value;
|
|
42
|
+
return {
|
|
43
|
+
shell,
|
|
44
|
+
dotenv: fromFile
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The env vars the block sets, which a `.env` value does not override. */
|
|
48
|
+
function blockEnvNames(reactor) {
|
|
49
|
+
const block = reactorBlockToSwitchboardConfig(reactor);
|
|
50
|
+
return [
|
|
51
|
+
...Object.keys(protocolEnv(reactor?.protocol)),
|
|
52
|
+
...block.packages?.dynamic ? ["DYNAMIC_MODEL_LOADING"] : [],
|
|
53
|
+
...block.features ? ["PH_WORKFLOWS_ENABLED"] : []
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
/** `config.switchboard`: a member's own switchboard config. The omitted keys
|
|
57
|
+
* live in the reactor block (storage, protocol, dynamic packages) or the
|
|
58
|
+
* runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */
|
|
59
|
+
const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([
|
|
60
|
+
"logLevel",
|
|
61
|
+
"server.port",
|
|
62
|
+
"server.dev",
|
|
63
|
+
"storage.reactor",
|
|
64
|
+
"storage.readModel",
|
|
65
|
+
"protocol",
|
|
66
|
+
"packages.dynamic",
|
|
67
|
+
"drive",
|
|
68
|
+
"remoteDrives",
|
|
69
|
+
"features.pluginHost",
|
|
70
|
+
"processorConfig"
|
|
71
|
+
]);
|
|
72
|
+
function isPlainObject(value) {
|
|
73
|
+
return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
|
|
74
|
+
}
|
|
75
|
+
/** The dotted keys both layers set. */
|
|
76
|
+
function overlappingKeys(a, b, path = "") {
|
|
77
|
+
return Object.entries(b).flatMap(([key, value]) => {
|
|
78
|
+
const other = a[key];
|
|
79
|
+
if (value === void 0 || other === void 0) return [];
|
|
80
|
+
const at = path ? `${path}.${key}` : key;
|
|
81
|
+
return isPlainObject(value) && isPlainObject(other) ? overlappingKeys(other, value, at) : [at];
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Each `config.switchboard` key the reactor block already sets. */
|
|
85
|
+
function reactorBlockConflicts(member) {
|
|
86
|
+
const own = member.config?.switchboard;
|
|
87
|
+
if (!own) return [];
|
|
88
|
+
return overlappingKeys(reactorBlockToSwitchboardConfig(member.reactor), own).map((key) => `config.switchboard.${key} is also set by the reactor block; set it in one place.`);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The deprecation notice for a block whose `readModel.url` still names the
|
|
92
|
+
* reactor store too: nothing else names the store, as it did when
|
|
93
|
+
* readModel.url rode `dbPath`.
|
|
94
|
+
*/
|
|
95
|
+
function readModelAsReactorStore(reactor, env, hostFileLabel) {
|
|
96
|
+
const storage = reactorBlockToSwitchboardConfig(reactor).storage;
|
|
97
|
+
const url = storage?.readModel?.url;
|
|
98
|
+
if (!url || storage.reactor || env.PH_REACTOR_DATABASE_URL !== void 0 || env.PH_SWITCHBOARD_DATABASE_URL !== void 0) return;
|
|
99
|
+
return {
|
|
100
|
+
url,
|
|
101
|
+
warning: `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).`
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The member's switchboard config under the runner's own arguments: its
|
|
106
|
+
* reactor block, then `config.switchboard`, then the env over both, mapped
|
|
107
|
+
* once as the server read it (the shell over the `.env`, whose values for the
|
|
108
|
+
* block's own vars are dropped). The block keeps the precedence it had as
|
|
109
|
+
* set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL
|
|
110
|
+
* overrides its store, and no env var overrides its read model. Writes nothing.
|
|
111
|
+
*/
|
|
112
|
+
async function memberSwitchboardConfig(member, env, options) {
|
|
113
|
+
const { switchboardConfigFromEnv } = await import("@powerhousedao/switchboard/config/env");
|
|
114
|
+
const block = reactorBlockToSwitchboardConfig(member.reactor);
|
|
115
|
+
const legacy = readModelAsReactorStore(member.reactor, env.shell, "");
|
|
116
|
+
if (legacy) block.storage = {
|
|
117
|
+
...block.storage,
|
|
118
|
+
reactor: { url: legacy.url }
|
|
119
|
+
};
|
|
120
|
+
const dotenvValues = { ...env.dotenv };
|
|
121
|
+
for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];
|
|
122
|
+
const fromEnv = switchboardConfigFromEnv({
|
|
123
|
+
...dotenvValues,
|
|
124
|
+
...env.shell
|
|
125
|
+
}, { logger: options.logger });
|
|
126
|
+
const storage = { ...fromEnv.storage };
|
|
127
|
+
if (block.storage?.reactor && env.shell.PH_REACTOR_DATABASE_URL === void 0) delete storage.reactor;
|
|
128
|
+
if (block.storage?.readModel) delete storage.readModel;
|
|
129
|
+
return mergeSwitchboardConfig(block, member.config?.switchboard ?? {}, {
|
|
130
|
+
...fromEnv,
|
|
131
|
+
storage
|
|
132
|
+
}, options.pluginHost ? { features: { pluginHost: true } } : {});
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Fails when the operator's env contradicts the member's protocol block, then
|
|
136
|
+
* creates the block's path-storage dir (the server's own mkdir is not
|
|
137
|
+
* recursive).
|
|
138
|
+
*/
|
|
139
|
+
function prepareMemberStorage(reactor, env, hostFileLabel) {
|
|
140
|
+
assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);
|
|
141
|
+
const storage = primaryBackend(reactor)?.storage;
|
|
142
|
+
if (storage?.kind !== "path" || !storage.dataDir) return;
|
|
143
|
+
if (/\$\{(userData|projectRoot)\}/.test(storage.dataDir)) throw new Error(`${hostFileLabel}: storage.dataDir "${storage.dataDir}" was not resolved; resolve the host (resolveHostOutputs) before starting it.`);
|
|
144
|
+
fs.mkdirSync(storage.dataDir, { recursive: true });
|
|
145
|
+
}
|
|
146
|
+
/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */
|
|
147
|
+
function switchboardDevMode(devVerb, runner) {
|
|
148
|
+
return devVerb || runner.dev === true;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
export { reactorBlockConflicts as a, switchboardDevMode as c, prepareMemberStorage as i, memberSwitchboardConfig as n, readModelAsReactorStore as o, memberSwitchboardConfigSchema as r, rememberShellNames as s, memberEnvOf as t };
|
|
152
|
+
|
|
153
|
+
//# sourceMappingURL=member-config-8Vwys-4O.mjs.map
|
|
154
|
+
//# debugId=712c7d89-0f2a-5dd8-9a25-a6d072f14933
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"member-config-8Vwys-4O.mjs","sources":["../src/runners/member-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n protocolEnv,\n reactorBlockToSwitchboardConfig,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigLayerSchema,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport {\n envNamesBeforeProjectEnv,\n isDotenvDisabled,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport type { ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The operator's env, split by where each value came from. */\nexport interface MemberEnv {\n /** Set by the shell: wins over the host file. */\n shell: Env;\n /** Only in the project `.env`: the host file's keys win over these. */\n dotenv: Env;\n}\n\n// The server's dotenv.config() ignores a file it cannot read.\nfunction readDotenv(cwd: string): Record<string, string> {\n try {\n return dotenv.parse(fs.readFileSync(path.join(cwd, \".env\")));\n } catch {\n return {};\n }\n}\n\nconst shellNamesByEnv = new WeakMap<object, ReadonlySet<string>>();\n\n/** Records which names of `env` the shell set, before a `.env` loads into it. */\nexport function rememberShellNames(env: Env, names: Iterable<string>): void {\n shellNamesByEnv.set(env, new Set(names));\n}\n\n// Taken the first time an env is seen: before the first member's server\n// import loads the .env into it, and reused for every later member.\nfunction shellNamesOf(env: Env): ReadonlySet<string> {\n let names = shellNamesByEnv.get(env);\n if (!names) {\n names =\n (env === process.env ? envNamesBeforeProjectEnv() : undefined) ??\n new Set(Object.keys(env));\n shellNamesByEnv.set(env, names);\n }\n return names;\n}\n\n/**\n * Splits `env` into the shell's values and the `.env` the switchboard server\n * loads from `cwd` (the same file). A name the shell set stays the shell's,\n * whatever the file says.\n */\nexport function memberEnvOf(env: Env, cwd: string = process.cwd()): MemberEnv {\n const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);\n const shellNames = shellNamesOf(env);\n const shell: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (file[name] === undefined || shellNames.has(name)) shell[name] = value;\n }\n const fromFile: Record<string, string> = {};\n for (const [name, value] of Object.entries(file)) {\n if (!shellNames.has(name)) fromFile[name] = value;\n }\n return { shell, dotenv: fromFile };\n}\n\n/** The env vars the block sets, which a `.env` value does not override. */\nfunction blockEnvNames(reactor: ReactorConfig | undefined): string[] {\n const block = reactorBlockToSwitchboardConfig(reactor);\n return [\n ...Object.keys(protocolEnv(reactor?.protocol)),\n ...(block.packages?.dynamic ? [\"DYNAMIC_MODEL_LOADING\"] : []),\n ...(block.features ? [\"PH_WORKFLOWS_ENABLED\"] : []),\n ];\n}\n\n/** `config.switchboard`: a member's own switchboard config. The omitted keys\n * live in the reactor block (storage, protocol, dynamic packages) or the\n * runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */\nexport const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([\n \"logLevel\",\n \"server.port\",\n \"server.dev\",\n \"storage.reactor\",\n \"storage.readModel\",\n \"protocol\",\n \"packages.dynamic\",\n \"drive\",\n \"remoteDrives\",\n \"features.pluginHost\",\n \"processorConfig\",\n]);\n\nexport interface SwitchboardMember {\n reactor?: ReactorConfig;\n config?: { switchboard?: SwitchboardConfigInput };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** The dotted keys both layers set. */\nexport function overlappingKeys(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n path = \"\",\n): string[] {\n return Object.entries(b).flatMap(([key, value]) => {\n const other = a[key];\n if (value === undefined || other === undefined) return [];\n const at = path ? `${path}.${key}` : key;\n return isPlainObject(value) && isPlainObject(other)\n ? overlappingKeys(other, value, at)\n : [at];\n });\n}\n\n/** Each `config.switchboard` key the reactor block already sets. */\nexport function reactorBlockConflicts(member: SwitchboardMember): string[] {\n const own = member.config?.switchboard;\n if (!own) return [];\n return overlappingKeys(\n reactorBlockToSwitchboardConfig(member.reactor) as Record<string, unknown>,\n own as Record<string, unknown>,\n ).map(\n (key) =>\n `config.switchboard.${key} is also set by the reactor block; set it in one place.`,\n );\n}\n\n/**\n * The deprecation notice for a block whose `readModel.url` still names the\n * reactor store too: nothing else names the store, as it did when\n * readModel.url rode `dbPath`.\n */\nexport function readModelAsReactorStore(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): { url: string; warning: string } | undefined {\n const storage = reactorBlockToSwitchboardConfig(reactor).storage;\n const url = storage?.readModel?.url;\n if (\n !url ||\n storage.reactor ||\n env.PH_REACTOR_DATABASE_URL !== undefined ||\n env.PH_SWITCHBOARD_DATABASE_URL !== undefined\n ) {\n return undefined;\n }\n return {\n url,\n warning:\n `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. ` +\n \"This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).\",\n };\n}\n\n/**\n * The member's switchboard config under the runner's own arguments: its\n * reactor block, then `config.switchboard`, then the env over both, mapped\n * once as the server read it (the shell over the `.env`, whose values for the\n * block's own vars are dropped). The block keeps the precedence it had as\n * set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL\n * overrides its store, and no env var overrides its read model. Writes nothing.\n */\nexport async function memberSwitchboardConfig(\n member: SwitchboardMember,\n env: MemberEnv,\n options: { pluginHost: boolean; logger?: ILogger },\n): Promise<SwitchboardConfigInput> {\n // Lazy: the env mapping loads reactor-api, which the runner module must not.\n const { switchboardConfigFromEnv } =\n await import(\"@powerhousedao/switchboard/config/env\");\n const block = reactorBlockToSwitchboardConfig(member.reactor);\n const legacy = readModelAsReactorStore(member.reactor, env.shell, \"\");\n if (legacy) {\n block.storage = { ...block.storage, reactor: { url: legacy.url } };\n }\n // One env, as the server read it: the .env under the block's own vars,\n // the shell over both.\n const dotenvValues: Record<string, string | undefined> = { ...env.dotenv };\n for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];\n const fromEnv = switchboardConfigFromEnv(\n { ...dotenvValues, ...env.shell },\n { logger: options.logger },\n );\n const storage = { ...fromEnv.storage };\n if (\n block.storage?.reactor &&\n env.shell.PH_REACTOR_DATABASE_URL === undefined\n ) {\n delete storage.reactor;\n }\n if (block.storage?.readModel) delete storage.readModel;\n return mergeSwitchboardConfig(\n block,\n member.config?.switchboard ?? {},\n { ...fromEnv, storage },\n // A declared composition turns the plugin host on, whatever the env says.\n options.pluginHost ? { features: { pluginHost: true } } : {},\n );\n}\n\n/**\n * Fails when the operator's env contradicts the member's protocol block, then\n * creates the block's path-storage dir (the server's own mkdir is not\n * recursive).\n */\nexport function prepareMemberStorage(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): void {\n assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind !== \"path\" || !storage.dataDir) return;\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n"],"names":[],"mappings":";;;;;;;;;AAgCA,SAAS,WAAW,KAAqC;CACvD,IAAI;EACF,OAAO,OAAO,MAAM,GAAG,aAAa,KAAK,KAAK,KAAK,MAAM,CAAC,CAAC;CAC7D,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAM,kCAAkB,IAAI,QAAqC;;AAGjE,SAAgB,mBAAmB,KAAU,OAA+B;CAC1E,gBAAgB,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC;AACzC;AAIA,SAAS,aAAa,KAA+B;CACnD,IAAI,QAAQ,gBAAgB,IAAI,GAAG;CACnC,IAAI,CAAC,OAAO;EACV,SACG,QAAQ,QAAQ,MAAM,yBAAyB,IAAI,KAAA,MACpD,IAAI,IAAI,OAAO,KAAK,GAAG,CAAC;EAC1B,gBAAgB,IAAI,KAAK,KAAK;CAChC;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,KAAU,MAAc,QAAQ,IAAI,GAAc;CAC5E,MAAM,OAAO,iBAAiB,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,WAAW,GAAG;CAC/D,MAAM,aAAa,aAAa,GAAG;CACnC,MAAM,QAA4C,CAAC;CACnD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,GAAG,GAC5C,IAAI,KAAK,UAAU,KAAA,KAAa,WAAW,IAAI,IAAI,GAAG,MAAM,QAAQ;CAEtE,MAAM,WAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,IAAI,GAC7C,IAAI,CAAC,WAAW,IAAI,IAAI,GAAG,SAAS,QAAQ;CAE9C,OAAO;EAAE;EAAO,QAAQ;CAAS;AACnC;;AAGA,SAAS,cAAc,SAA8C;CACnE,M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-5dd8-9a25-a6d072f14933"}
|
|
@@ -1,11 +1,11 @@
|
|
|
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]="
|
|
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]="24b73717-4ab0-54a3-b789-6259175ab4c3")}catch(e){}}();
|
|
3
3
|
import { readFileSync } from "node:fs";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { execSync } from "node:child_process";
|
|
6
|
-
import { detect, resolveCommand } from "package-manager-detector";
|
|
7
6
|
import { fetchPackageVersionFromNpmRegistry, injectPnpmAllowBuilds, spawnAsync } from "@powerhousedao/shared/clis";
|
|
8
7
|
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { detect, resolveCommand } from "package-manager-detector";
|
|
9
9
|
import { compare, minVersion, prerelease, rcompare, valid } from "semver";
|
|
10
10
|
import { ALL_POWERHOUSE_DEPENDENCIES } from "@powerhousedao/shared/constants";
|
|
11
11
|
//#region src/services/migrate.ts
|
|
@@ -173,5 +173,5 @@ async function startMigrate({ versionPositional, version, force, debug }) {
|
|
|
173
173
|
//#endregion
|
|
174
174
|
export { startMigrate };
|
|
175
175
|
|
|
176
|
-
//# sourceMappingURL=migrate-
|
|
177
|
-
//# debugId=
|
|
176
|
+
//# sourceMappingURL=migrate-CIJaE3iZ.mjs.map
|
|
177
|
+
//# debugId=24b73717-4ab0-54a3-b789-6259175ab4c3
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-b38W7NH_.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n spawnAsync,\n} from \"@powerhousedao/shared/clis\";\nimport { ALL_POWERHOUSE_DEPENDENCIES } from \"@powerhousedao/shared/constants\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { compare, minVersion, prerelease, rcompare, valid } from \"semver\";\nimport type { MigrateArgs } from \"../types.js\";\n\n// Dist-tags a prerelease version can name its channel by.\nconst PRERELEASE_TAGS = [\"dev\", \"staging\", \"rc\"];\n\n// Set on the re-executed migrate, so the version check runs once.\nconst VERSION_CHECKED_ENV = \"PH_MIGRATE_VERSION_CHECKED\";\n\ntype ProjectPackageJson = Partial<\n Record<\n \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n Record<string, string>\n >\n>;\n\nfunction readProjectPackageJson(projectDir: string): ProjectPackageJson {\n try {\n return JSON.parse(\n readFileSync(join(projectDir, \"package.json\"), \"utf8\"),\n ) as ProjectPackageJson;\n } catch {\n return {};\n }\n}\n\n/** The newest Powerhouse package version the project's package.json pins */\nexport function newestPowerhouseVersion(packageJson: ProjectPackageJson) {\n const pinned = [\n packageJson.dependencies,\n packageJson.devDependencies,\n packageJson.peerDependencies,\n ].flatMap((deps) =>\n Object.entries(deps ?? {}).flatMap(([name, range]) => {\n if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];\n try {\n const version = minVersion(range)?.version;\n return version ? [{ name, version }] : [];\n } catch {\n // workspace:, catalog: and other non-semver specifiers\n return [];\n }\n }),\n );\n return pinned.sort((a, b) => rcompare(a.version, b.version)).at(0);\n}\n\n/** The dist-tag of the channel the project is on, and why */\nexport function inferReleaseTag(packageJson: ProjectPackageJson): {\n tag: string;\n reason: string;\n} {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) {\n return { tag: \"latest\", reason: \"no Powerhouse package version is pinned\" };\n }\n const channel = prerelease(newest.version)?.[0];\n const pinned = `${newest.name}@${newest.version}`;\n if (typeof channel === \"string\" && PRERELEASE_TAGS.includes(channel)) {\n return { tag: channel, reason: `the project is on ${pinned}` };\n }\n return {\n tag: \"latest\",\n reason: `the project is on ${pinned}, ${channel === undefined ? \"a stable release\" : \"not on a dev, staging or rc channel\"}`,\n };\n}\n\n/** Whether `target` is an older release than `installed`: lower by semver, or\n * published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */\nexport function isOlderRelease(\n installed: string,\n target: string,\n publishTimes: Partial<Record<string, string>> = {},\n): boolean {\n if (!valid(installed) || !valid(target)) return false;\n if (compare(target, installed) < 0) return true;\n const installedAt = publishTimes[installed];\n const targetAt = publishTimes[target];\n if (!installedAt || !targetAt) return false;\n return Date.parse(targetAt) < Date.parse(installedAt);\n}\n\nasync function fetchPublishTimes(\n packageName: string,\n): Promise<Partial<Record<string, string>>> {\n try {\n return JSON.parse(\n await spawnAsync(\"npm\", [\"view\", packageName, \"time\", \"--json\"]),\n ) as Partial<Record<string, string>>;\n } catch {\n return {};\n }\n}\n\nasync function warnIfOlderRelease(\n packageJson: ProjectPackageJson,\n targetVersion: string,\n) {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) return;\n const publishTimes = await fetchPublishTimes(\"@powerhousedao/ph-cli\");\n if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;\n console.warn(\n `⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \\`ph migrate dev\\`) to stay on yours.`,\n );\n}\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const packageJson = readProjectPackageJson(process.cwd());\n let requested = versionPositional ?? version;\n if (requested === undefined) {\n const inferred = inferReleaseTag(packageJson);\n requested = inferred.tag;\n console.log(\n `No version given; migrating to \"${inferred.tag}\" because ${inferred.reason}.`,\n );\n }\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n if (targetVersion && !process.env[VERSION_CHECKED_ENV]) {\n await warnIfOlderRelease(packageJson, targetVersion);\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, {\n stdio: \"inherit\",\n env: { ...process.env, [VERSION_CHECKED_ENV]: \"1\" },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAeA,MAAM,kBAAkB;CAAC;CAAO;CAAW;AAAI;AAG/C,MAAM,sBAAsB;AAS5B,SAAS,uBAAuB,YAAwC;CACtE,IAAI;EACF,OAAO,KAAK,MACV,aAAa,KAAK,YAAY,cAAc,GAAG,MAAM,CACvD;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,wBAAwB,aAAiC;CAiBvE,OAhBe;EACb,YAAY;EACZ,YAAY;EACZ,YAAY;CACd,CAAC,CAAC,SAAS,SACT,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,WAAW;EACpD,IAAI,CAAC,4B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O;EACP,KAAK;GAAE,GAAG,QAAQ;IAAM,sBAAsB;EAAI;CACpD,CAAC;AACH","debug_id":"c044c223-f97f-5822-8974-54d5e4214104"}
|
|
1
|
+
{"version":3,"file":"migrate-CIJaE3iZ.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n spawnAsync,\n} from \"@powerhousedao/shared/clis\";\nimport { ALL_POWERHOUSE_DEPENDENCIES } from \"@powerhousedao/shared/constants\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { compare, minVersion, prerelease, rcompare, valid } from \"semver\";\nimport type { MigrateArgs } from \"../types.js\";\n\n// Dist-tags a prerelease version can name its channel by.\nconst PRERELEASE_TAGS = [\"dev\", \"staging\", \"rc\"];\n\n// Set on the re-executed migrate, so the version check runs once.\nconst VERSION_CHECKED_ENV = \"PH_MIGRATE_VERSION_CHECKED\";\n\ntype ProjectPackageJson = Partial<\n Record<\n \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n Record<string, string>\n >\n>;\n\nfunction readProjectPackageJson(projectDir: string): ProjectPackageJson {\n try {\n return JSON.parse(\n readFileSync(join(projectDir, \"package.json\"), \"utf8\"),\n ) as ProjectPackageJson;\n } catch {\n return {};\n }\n}\n\n/** The newest Powerhouse package version the project's package.json pins */\nexport function newestPowerhouseVersion(packageJson: ProjectPackageJson) {\n const pinned = [\n packageJson.dependencies,\n packageJson.devDependencies,\n packageJson.peerDependencies,\n ].flatMap((deps) =>\n Object.entries(deps ?? {}).flatMap(([name, range]) => {\n if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];\n try {\n const version = minVersion(range)?.version;\n return version ? [{ name, version }] : [];\n } catch {\n // workspace:, catalog: and other non-semver specifiers\n return [];\n }\n }),\n );\n return pinned.sort((a, b) => rcompare(a.version, b.version)).at(0);\n}\n\n/** The dist-tag of the channel the project is on, and why */\nexport function inferReleaseTag(packageJson: ProjectPackageJson): {\n tag: string;\n reason: string;\n} {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) {\n return { tag: \"latest\", reason: \"no Powerhouse package version is pinned\" };\n }\n const channel = prerelease(newest.version)?.[0];\n const pinned = `${newest.name}@${newest.version}`;\n if (typeof channel === \"string\" && PRERELEASE_TAGS.includes(channel)) {\n return { tag: channel, reason: `the project is on ${pinned}` };\n }\n return {\n tag: \"latest\",\n reason: `the project is on ${pinned}, ${channel === undefined ? \"a stable release\" : \"not on a dev, staging or rc channel\"}`,\n };\n}\n\n/** Whether `target` is an older release than `installed`: lower by semver, or\n * published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */\nexport function isOlderRelease(\n installed: string,\n target: string,\n publishTimes: Partial<Record<string, string>> = {},\n): boolean {\n if (!valid(installed) || !valid(target)) return false;\n if (compare(target, installed) < 0) return true;\n const installedAt = publishTimes[installed];\n const targetAt = publishTimes[target];\n if (!installedAt || !targetAt) return false;\n return Date.parse(targetAt) < Date.parse(installedAt);\n}\n\nasync function fetchPublishTimes(\n packageName: string,\n): Promise<Partial<Record<string, string>>> {\n try {\n return JSON.parse(\n await spawnAsync(\"npm\", [\"view\", packageName, \"time\", \"--json\"]),\n ) as Partial<Record<string, string>>;\n } catch {\n return {};\n }\n}\n\nasync function warnIfOlderRelease(\n packageJson: ProjectPackageJson,\n targetVersion: string,\n) {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) return;\n const publishTimes = await fetchPublishTimes(\"@powerhousedao/ph-cli\");\n if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;\n console.warn(\n `⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \\`ph migrate dev\\`) to stay on yours.`,\n );\n}\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const packageJson = readProjectPackageJson(process.cwd());\n let requested = versionPositional ?? version;\n if (requested === undefined) {\n const inferred = inferReleaseTag(packageJson);\n requested = inferred.tag;\n console.log(\n `No version given; migrating to \"${inferred.tag}\" because ${inferred.reason}.`,\n );\n }\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n if (targetVersion && !process.env[VERSION_CHECKED_ENV]) {\n await warnIfOlderRelease(packageJson, targetVersion);\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, {\n stdio: \"inherit\",\n env: { ...process.env, [VERSION_CHECKED_ENV]: \"1\" },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAeA,MAAM,kBAAkB;CAAC;CAAO;CAAW;AAAI;AAG/C,MAAM,sBAAsB;AAS5B,SAAS,uBAAuB,YAAwC;CACtE,IAAI;EACF,OAAO,KAAK,MACV,aAAa,KAAK,YAAY,cAAc,GAAG,MAAM,CACvD;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF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AAO,QAAQ;CAErC,MAAM,UAAU,GAAG,SAAS,QAAQ,GAAG,SAAS,KAAK,KAAK,GAAG;CAC7D,IAAI,OAAO;EACT,QAAQ,IAAI,uCAAuC,OAAO;EAC1D,QAAQ,IAAI,2BAA2B,SAAS;CAClD;CACA,SAAS,SAAS;EAChB,OAAO;EACP,KAAK;GAAE,GAAG,QAAQ;IAAM,sBAAsB;EAAI;CACpD,CAAC;AACH","debug_id":"24b73717-4ab0-54a3-b789-6259175ab4c3"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { n as checkOfferedRoutesImports } from "./offered-routes-imports-CalXK9dh.mjs";
|
|
2
|
+
export { checkOfferedRoutesImports };
|
|
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]="98fd0401-72de-5587-ae2a-f8145c1170c8")}catch(e){}}();
|
|
4
|
+
//# debugId=98fd0401-72de-5587-ae2a-f8145c1170c8
|