@powerhousedao/ph-cli 6.4.0-next.3 → 6.4.0-next.5
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/auth-5bqHASGL.mjs +4 -0
- package/dist/auth-DYknkWfW.mjs +23 -0
- package/dist/auth-DYknkWfW.mjs.map +1 -0
- package/dist/{build-B-rPwjM8.mjs → build-CBKlv5E3.mjs} +8 -8
- package/dist/{build-B-rPwjM8.mjs.map → build-CBKlv5E3.mjs.map} +1 -1
- package/dist/build-Dr1lnv4h.mjs +4 -0
- package/dist/{check-B7C3Vi_b.mjs → check-CW81vbe9.mjs} +4 -4
- package/dist/{check-B7C3Vi_b.mjs.map → check-CW81vbe9.mjs.map} +1 -1
- package/dist/{check-DM7UdFTK.mjs → check-Cx_AeBQe.mjs} +7 -7
- package/dist/check-Cx_AeBQe.mjs.map +1 -0
- package/dist/{check-DeUTd514.mjs → check-DhFd9tO8.mjs} +3 -3
- package/dist/{cli-connect-override-Bx_g3-ZE.mjs → cli-connect-override-DKxY3lCi.mjs} +4 -4
- package/dist/{cli-connect-override-Bx_g3-ZE.mjs.map → cli-connect-override-DKxY3lCi.mjs.map} +1 -1
- package/dist/cli.mjs +9 -8
- package/dist/cli.mjs.map +1 -1
- package/dist/{compound-Q9sZSEZF-DQvtoigb.mjs → compound-g6x_KkWp-Bs7olmlI.mjs} +465 -361
- package/dist/compound-g6x_KkWp-Bs7olmlI.mjs.map +1 -0
- package/dist/{connect-build-CaTxdYcc.mjs → connect-build-DpGUrtct.mjs} +5 -5
- package/dist/{connect-build-CaTxdYcc.mjs.map → connect-build-DpGUrtct.mjs.map} +1 -1
- package/dist/{connect-config-A-U83U8U.mjs → connect-config-BpzwJln3.mjs} +4 -4
- package/dist/{connect-config-A-U83U8U.mjs.map → connect-config-BpzwJln3.mjs.map} +1 -1
- package/dist/{connect-preview-BvxXGo_W.mjs → connect-preview-B_E4SIV6.mjs} +21 -4
- package/dist/connect-preview-B_E4SIV6.mjs.map +1 -0
- package/dist/connect-studio-BPZOcwUM.mjs +214 -0
- package/dist/connect-studio-BPZOcwUM.mjs.map +1 -0
- package/dist/credentials-CmtYywgk.mjs +132 -0
- package/dist/credentials-CmtYywgk.mjs.map +1 -0
- package/dist/definitions-worker.mjs +4 -4
- package/dist/definitions-worker.mjs.map +1 -1
- package/dist/{dev-host-RhWeATKB.mjs → dev-host-CM-Jg2kY.mjs} +4 -4
- package/dist/{dev-host-RhWeATKB.mjs.map → dev-host-CM-Jg2kY.mjs.map} +1 -1
- package/dist/{dist-D_UjZsgt.mjs → dist-DPj_FB8H.mjs} +5 -5
- package/dist/dist-DPj_FB8H.mjs.map +1 -0
- package/dist/{explain-DbbHpa61.mjs → explain-DQ5ymlco.mjs} +5 -5
- package/dist/{explain-DbbHpa61.mjs.map → explain-DQ5ymlco.mjs.map} +1 -1
- package/dist/{export-FduYVQEM.mjs → export-CzeF8pob.mjs} +4 -4
- package/dist/{export-FduYVQEM.mjs.map → export-CzeF8pob.mjs.map} +1 -1
- package/dist/{files-DEHg350R.mjs → files-D6_euBBn.mjs} +4 -4
- package/dist/{files-DEHg350R.mjs.map → files-D6_euBBn.mjs.map} +1 -1
- package/dist/{generate-all-BE8UmbJv.mjs → generate-all-B9MwWXlq.mjs} +4 -4
- package/dist/{generate-all-BE8UmbJv.mjs.map → generate-all-B9MwWXlq.mjs.map} +1 -1
- package/dist/{generate-document-model-DSYPTMZg.mjs → generate-document-model-D3LKY1D7.mjs} +6 -8
- package/dist/generate-document-model-D3LKY1D7.mjs.map +1 -0
- package/dist/{generate-subgraph-EQ2ZjMp9.mjs → generate-subgraph-Q1VLh3SC.mjs} +10 -17
- package/dist/generate-subgraph-Q1VLh3SC.mjs.map +1 -0
- package/dist/{get-version-7oKMD8Gt.mjs → get-version-CTP__ORu.mjs} +4 -4
- package/dist/{get-version-7oKMD8Gt.mjs.map → get-version-CTP__ORu.mjs.map} +1 -1
- package/dist/identity-DXZFeQfC.mjs +137 -0
- package/dist/identity-DXZFeQfC.mjs.map +1 -0
- package/dist/{index-Bs1PfL3W.d.mts → index-aosqo7aM.d.mts} +5 -4
- package/dist/index-aosqo7aM.d.mts.map +1 -0
- package/dist/{inspect-CulIpVsF.mjs → inspect-BgKI8Fhd.mjs} +6 -6
- package/dist/{inspect-CulIpVsF.mjs.map → inspect-BgKI8Fhd.mjs.map} +1 -1
- package/dist/{keyframes-bFo9iDhT.mjs → keyframes-BkeORfEu.mjs} +4 -4
- package/dist/{keyframes-bFo9iDhT.mjs.map → keyframes-BkeORfEu.mjs.map} +1 -1
- package/dist/{mcp-CcZT9zT9.mjs → mcp-gcG7SW9L.mjs} +149 -7
- package/dist/mcp-gcG7SW9L.mjs.map +1 -0
- package/dist/{migrate-Ddr7YAtM.mjs → migrate-BaWZhorc.mjs} +4 -4
- package/dist/{migrate-Ddr7YAtM.mjs.map → migrate-BaWZhorc.mjs.map} +1 -1
- package/dist/{migrate-document-models-X_mVTljj.mjs → migrate-document-models-DYmkJzq3.mjs} +5 -6
- package/dist/migrate-document-models-DYmkJzq3.mjs.map +1 -0
- package/dist/{migrate-subgraphs-Ffwwm7Oy.mjs → migrate-subgraphs-BUgTeHcm.mjs} +6 -7
- package/dist/migrate-subgraphs-BUgTeHcm.mjs.map +1 -0
- package/dist/migrate-subgraphs-ChhXynqd.mjs +4 -0
- package/dist/{ph-cli-commands-D4Z6YSwd.mjs → ph-cli-commands-B5VkGW99.mjs} +161 -107
- package/dist/ph-cli-commands-B5VkGW99.mjs.map +1 -0
- package/dist/ph-cli-commands-CGXSo1wx.mjs +4 -0
- package/dist/{registry-auth-Bm5AR-fB.mjs → registry-auth-C8D5cno2.mjs} +4 -4
- package/dist/{registry-auth-Bm5AR-fB.mjs.map → registry-auth-C8D5cno2.mjs.map} +1 -1
- package/dist/render-BQE20Cnd.mjs +4 -0
- package/dist/{render-SVfj3m8A.mjs → render-CQdi685k.mjs} +6 -6
- package/dist/render-CQdi685k.mjs.map +1 -0
- package/dist/{run-LRGy7zGo.mjs → run-C6Vha5VN.mjs} +3 -3
- package/dist/{run--de_-WAz.mjs → run-sVzTTEUx.mjs} +5 -36
- package/dist/run-sVzTTEUx.mjs.map +1 -0
- package/dist/{run-sugar-CkuGJuPg.mjs → run-sugar-BuxOaRzE.mjs} +5 -5
- package/dist/{run-sugar-CkuGJuPg.mjs.map → run-sugar-BuxOaRzE.mjs.map} +1 -1
- package/dist/{run-sugar-Dd_Mu058.mjs → run-sugar-Dz-rpeMO.mjs} +3 -3
- package/dist/runners/connect.d.mts +20 -3
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +37 -15
- package/dist/runners/connect.mjs.map +1 -1
- package/dist/runners/switchboard.d.mts +1 -1
- package/dist/runners/switchboard.mjs +3 -3
- package/dist/scripts/generate-commands-docs.ts +12 -0
- package/dist/{subgraphs-7OYWwP-C.mjs → subgraphs-Bm9NHTCn.mjs} +5 -38
- package/dist/subgraphs-Bm9NHTCn.mjs.map +1 -0
- package/dist/{sugar-checks-CAtgUIem.mjs → sugar-checks-DL-J3l2y.mjs} +6 -6
- package/dist/{sugar-checks-CAtgUIem.mjs.map → sugar-checks-DL-J3l2y.mjs.map} +1 -1
- package/dist/{verify-DXrs0JUp.mjs → verify-BLn76w09.mjs} +5 -5
- package/dist/{verify-DXrs0JUp.mjs.map → verify-BLn76w09.mjs.map} +1 -1
- package/dist/{vetra-gateway-BHuz7pvS.mjs → vetra-gateway-D30pZgha.mjs} +5 -5
- package/dist/{vetra-gateway-BHuz7pvS.mjs.map → vetra-gateway-D30pZgha.mjs.map} +1 -1
- package/dist/vetra-gateway-DE5Hc0Fp.mjs +4 -0
- package/dist/vetra-host-0rSW35_r.mjs +230 -0
- package/dist/vetra-host-0rSW35_r.mjs.map +1 -0
- package/dist/{vetra-launcher-B5L3yXPo.mjs → vetra-launcher-6NKfi6Au.mjs} +45 -5
- package/dist/vetra-launcher-6NKfi6Au.mjs.map +1 -0
- package/dist/vetra-launcher-XMk_Hv0c.mjs +4 -0
- package/package.json +17 -15
- package/dist/auth-BFUq7CvE.mjs +0 -18
- package/dist/auth-BFUq7CvE.mjs.map +0 -1
- package/dist/auth-CNhbN5UM.mjs +0 -4
- package/dist/build-DuwAPWMY.mjs +0 -4
- package/dist/check-DM7UdFTK.mjs.map +0 -1
- package/dist/compound-Q9sZSEZF-DQvtoigb.mjs.map +0 -1
- package/dist/connect-preview-BvxXGo_W.mjs.map +0 -1
- package/dist/connect-studio-B2gugCJU.mjs +0 -106
- package/dist/connect-studio-B2gugCJU.mjs.map +0 -1
- package/dist/dist-D_UjZsgt.mjs.map +0 -1
- package/dist/generate-document-model-DSYPTMZg.mjs.map +0 -1
- package/dist/generate-subgraph-EQ2ZjMp9.mjs.map +0 -1
- package/dist/index-Bs1PfL3W.d.mts.map +0 -1
- package/dist/mcp-CcZT9zT9.mjs.map +0 -1
- package/dist/migrate-document-models-X_mVTljj.mjs.map +0 -1
- package/dist/migrate-subgraphs-DEqWkLoh.mjs +0 -4
- package/dist/migrate-subgraphs-Ffwwm7Oy.mjs.map +0 -1
- package/dist/ph-cli-commands-D4Z6YSwd.mjs.map +0 -1
- package/dist/ph-cli-commands-p9cO6MsE.mjs +0 -4
- package/dist/render-3M3DwFzO.mjs +0 -4
- package/dist/render-SVfj3m8A.mjs.map +0 -1
- package/dist/run--de_-WAz.mjs.map +0 -1
- package/dist/subgraphs-7OYWwP-C.mjs.map +0 -1
- package/dist/vetra-gateway-ag33E_Ta.mjs +0 -4
- package/dist/vetra-host-CYdbd3J3.mjs +0 -111
- package/dist/vetra-host-CYdbd3J3.mjs.map +0 -1
- package/dist/vetra-launcher-B5L3yXPo.mjs.map +0 -1
- package/dist/vetra-launcher-BUO9e74r.mjs +0 -4
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect-preview-BvxXGo_W.mjs","sources":["../src/services/connect-preview.ts"],"sourcesContent":["import {\n assertConnectBuild,\n cacheHeaders,\n connectBaseOf,\n overrideFromEnv,\n precompressedAssets,\n resolveServedFiles,\n servedFilesStep,\n serveOverrideStep,\n shellSwapFor,\n type ConnectMiddleware,\n type ConnectServeOverride,\n} from \"@powerhousedao/ph-run/connect-serve\";\nimport path from \"node:path\";\nimport type { InlineConfig, Plugin } from \"vite\";\nimport type { ConnectPreviewArgs } from \"../types.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\n\nexport * from \"@powerhousedao/ph-run/connect-serve\";\n\nexport async function runConnectPreview(\n args: ConnectPreviewArgs,\n serveOverride?: ConnectServeOverride,\n dirname = process.cwd(),\n {\n proxy,\n serveFiles,\n }: {\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n /** Files served by name, read against `dirname` (runner.serveFiles). */\n serveFiles?: Readonly<Record<string, string>>;\n } = {},\n) {\n // A supervisor can drive the preview via env when no explicit override is\n // passed.\n serveOverride ??= overrideFromEnv();\n const {\n outDir,\n port,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n } = args;\n\n const mode = \"production\";\n\n const outDirAbs = path.resolve(dirname, outDir);\n assertConnectBuild(outDir, outDirAbs, dirname);\n const base = connectBaseOf(args, outDirAbs, dirname);\n\n // Build tooling, so only here: a packaged app doesn't have it.\n const { preview } = await import(\"vite\");\n const previewPlugin = (name: string, step: ConnectMiddleware): Plugin => ({\n name,\n configurePreviewServer(server) {\n server.middlewares.use(step);\n },\n });\n\n const previewConfig: InlineConfig = {\n configFile: false,\n mode,\n base,\n build: {\n outDir: outDirAbs,\n },\n preview: {\n cors,\n port,\n strictPort,\n host,\n open,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n plugins: [\n previewPlugin(\"ph:preview-cache-headers\", cacheHeaders(outDirAbs, base)),\n previewPlugin(\n \"ph:precompressed-assets\",\n precompressedAssets(outDirAbs, base),\n ),\n ...(serveOverride\n ? [\n previewPlugin(\n \"ph:serve-override\",\n serveOverrideStep(\n outDirAbs,\n serveOverride,\n base,\n shellSwapFor(outDirAbs, serveOverride, base),\n proxy !== undefined,\n ),\n ),\n ]\n : []),\n ...(serveFiles\n ? [\n previewPlugin(\n \"ph:serve-files\",\n servedFilesStep(resolveServedFiles(serveFiles, dirname), base),\n ),\n ]\n : []),\n ],\n };\n\n const server = await preview(previewConfig);\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n return server;\n}\n"],"names":[],"mappings":";;;;;;;AAoBA,eAAsB,kBACpB,MACA,eACA,UAAU,QAAQ,IAAI,GACtB,EACE,OACA,eAME,CAAC,GACL;CAGA,kBAAkB,gBAAgB;CAClC,MAAM,EACJ,QACA,MACA,MACA,MACA,MACA,YACA,WACA,qBACE;CAEJ,MAAM,OAAO;CAEb,MAAM,YAAY,KAAK,QAAQ,SAAS,MAAM;CAC9C,mBAAmB,QAAQ,WAAW,OAAO;CAC7C,MAAM,OAAO,cAAc,MAAM,WAAW,OAAO;CAGnD,MAAM,EAAE,YAAY,MAAM,OAAO;CACjC,MAAM,iBAAiB,MAAc,UAAqC;EACxE;EACA,uBAAuB,QAAQ;GAC7B,OAAO,YAAY,IAAI,IAAI;EAC7B;CACF;CAgDA,MAAM,SAAS,MAAM,QAAQ;EA7C3B,YAAY;EACZ;EACA;EACA,OAAO,EACL,QAAQ,UACV;EACA,SAAS;GACP;GACA;GACA;GACA;GACA;GACA,GAAI,QAAQ,EAAE,OAAO,iBAAiB,KAAK,EAAE,IAAI,CAAC;EACpD;EACA,SAAS;GACP,cAAc,4BAA4B,aAAa,WAAW,IAAI,CAAC;GACvE,cACE,2BACA,oBAAoB,WAAW,IAAI,CACrC;GACA,GAAI,gBACA,CACE,cACE,qBACA,kBACE,WACA,eACA,MACA,aAAa,WAAW,eAAe,IAAI,GAC3C,UAAU,KAAA,CACZ,CACF,CACF,IACA,CAAC;GACL,GAAI,aACA,CACE,cACE,kBACA,gBAAgB,mBAAmB,YAAY,OAAO,GAAG,IAAI,CAC/D,CACF,IACA,CAAC;EACP;CAGuC,CAAC;CAE1C,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;CAC7D,OAAO;AACT","debug_id":"55e66fe2-d7a0-50f0-b3cb-77f5aa83d6e3"}
|
|
@@ -1,106 +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]="45f8b5d8-1060-52b3-9245-0bfc43a7542e")}catch(e){}}();
|
|
3
|
-
import { r as buildStudioConnectOverride } from "./cli-connect-override-Bx_g3-ZE.mjs";
|
|
4
|
-
import { t as switchboardProxy } from "./switchboard-proxy-CGfMtENM.mjs";
|
|
5
|
-
import { readFileSync, watch } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
7
|
-
import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
|
|
8
|
-
import { createServer, mergeConfig } from "vite";
|
|
9
|
-
import { resolveServedFiles, servedFilesStep } from "@powerhousedao/ph-run/connect-serve";
|
|
10
|
-
import { isDeepStrictEqual } from "node:util";
|
|
11
|
-
//#region src/services/connect-studio.ts
|
|
12
|
-
const CONFIG_FILE = "powerhouse.config.json";
|
|
13
|
-
const RELOAD_DEBOUNCE_MS = 200;
|
|
14
|
-
function readConfig(file) {
|
|
15
|
-
try {
|
|
16
|
-
return JSON.parse(readFileSync(file, "utf8"));
|
|
17
|
-
} catch {
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */
|
|
22
|
-
async function runConnectStudio(args, customLogger, callerOverride, { routes, cacheDir, reloadOnConfigChange, proxy, serveFiles, beforeRestart, restartWith, exposeStop } = {}) {
|
|
23
|
-
const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } = args;
|
|
24
|
-
const mode = "development";
|
|
25
|
-
const dirname = process.cwd();
|
|
26
|
-
const configFile = join(dirname, CONFIG_FILE);
|
|
27
|
-
const servedFiles = serveFiles && {
|
|
28
|
-
name: "ph:serve-files",
|
|
29
|
-
configureServer(server) {
|
|
30
|
-
server.middlewares.use(servedFilesStep(resolveServedFiles(serveFiles, dirname), server.config.base));
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
const start = async (first) => {
|
|
34
|
-
const override = typeof callerOverride === "function" ? callerOverride() : callerOverride;
|
|
35
|
-
const baseConfig = getConnectBaseViteConfig({
|
|
36
|
-
mode,
|
|
37
|
-
dirname,
|
|
38
|
-
cliConnectOverride: buildStudioConnectOverride(args, override),
|
|
39
|
-
routes,
|
|
40
|
-
cacheDir
|
|
41
|
-
});
|
|
42
|
-
const devServerConfig = {
|
|
43
|
-
server: {
|
|
44
|
-
port,
|
|
45
|
-
host,
|
|
46
|
-
open: first && open,
|
|
47
|
-
cors,
|
|
48
|
-
strictPort,
|
|
49
|
-
...proxy ? { proxy: switchboardProxy(proxy) } : {}
|
|
50
|
-
},
|
|
51
|
-
customLogger,
|
|
52
|
-
...servedFiles ? { plugins: [servedFiles] } : {}
|
|
53
|
-
};
|
|
54
|
-
const server = await createServer(mergeConfig(baseConfig, devServerConfig));
|
|
55
|
-
await server.listen();
|
|
56
|
-
if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });
|
|
57
|
-
return server;
|
|
58
|
-
};
|
|
59
|
-
let loaded = reloadOnConfigChange ? readConfig(configFile) : void 0;
|
|
60
|
-
const first = await start(true);
|
|
61
|
-
if (printUrls) first.printUrls();
|
|
62
|
-
if (!reloadOnConfigChange) {
|
|
63
|
-
exposeStop?.(() => first.close());
|
|
64
|
-
return first;
|
|
65
|
-
}
|
|
66
|
-
let server = first;
|
|
67
|
-
let timer;
|
|
68
|
-
let restarts = Promise.resolve();
|
|
69
|
-
let stopped = false;
|
|
70
|
-
const restart = async () => {
|
|
71
|
-
if (stopped) return;
|
|
72
|
-
const current = readConfig(configFile);
|
|
73
|
-
if (current === void 0 || isDeepStrictEqual(current, loaded)) return;
|
|
74
|
-
loaded = current;
|
|
75
|
-
server.config.logger.info(`[connect] ${CONFIG_FILE} changed; restarting Studio with it.`, { timestamp: true });
|
|
76
|
-
await beforeRestart?.();
|
|
77
|
-
await server.close();
|
|
78
|
-
server = await (restartWith ? restartWith(() => start(false)) : start(false));
|
|
79
|
-
};
|
|
80
|
-
const queueRestart = () => {
|
|
81
|
-
clearTimeout(timer);
|
|
82
|
-
timer = setTimeout(() => {
|
|
83
|
-
restarts = restarts.then(restart).catch((error) => {
|
|
84
|
-
server.config.logger.error(`[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`);
|
|
85
|
-
});
|
|
86
|
-
}, RELOAD_DEBOUNCE_MS);
|
|
87
|
-
};
|
|
88
|
-
const watcher = watch(dirname, (_event, file) => {
|
|
89
|
-
if (file === CONFIG_FILE) queueRestart();
|
|
90
|
-
});
|
|
91
|
-
watcher.unref();
|
|
92
|
-
exposeStop?.(async () => {
|
|
93
|
-
stopped = true;
|
|
94
|
-
clearTimeout(timer);
|
|
95
|
-
watcher.close();
|
|
96
|
-
await restarts;
|
|
97
|
-
await server.close();
|
|
98
|
-
});
|
|
99
|
-
queueRestart();
|
|
100
|
-
return first;
|
|
101
|
-
}
|
|
102
|
-
//#endregion
|
|
103
|
-
export { runConnectStudio };
|
|
104
|
-
|
|
105
|
-
//# sourceMappingURL=connect-studio-B2gugCJU.mjs.map
|
|
106
|
-
//# debugId=45f8b5d8-1060-52b3-9245-0bfc43a7542e
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect-studio-B2gugCJU.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport {\n resolveServedFiles,\n servedFilesStep,\n} from \"@powerhousedao/ph-run/connect-serve\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, Plugin, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n /** Files served by name, read against the working directory at each\n * request (runner.serveFiles), as the servers of a build serve them. */\n serveFiles?: Readonly<Record<string, string>>;\n /** Runs before a config change replaces the server, for a caller whose\n * override follows the config too. When it rejects, the server stays. */\n beforeRestart?: () => Promise<void>;\n /** Runs each restart's server start, for a caller that started the first\n * one inside a wrapper of its own. */\n restartWith?: (start: () => Promise<ViteDevServer>) => Promise<ViteDevServer>;\n /** Handed what stops Studio for good, before it resolves: the config\n * watcher and whichever server is current. The first server's own `close`\n * stops neither once a config change has replaced it. */\n exposeStop?: (stop: () => Promise<void>) => void;\n};\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n {\n routes,\n cacheDir,\n reloadOnConfigChange,\n proxy,\n serveFiles,\n beforeRestart,\n restartWith,\n exposeStop,\n }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n // Ahead of vite's own middlewares (its SPA fallback among them), under the\n // base vite serves at.\n const servedFiles: Plugin | undefined = serveFiles && {\n name: \"ph:serve-files\",\n configureServer(server) {\n server.middlewares.use(\n servedFilesStep(\n resolveServedFiles(serveFiles, dirname),\n server.config.base,\n ),\n );\n },\n };\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n ...(servedFiles ? { plugins: [servedFiles] } : {}),\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n let loaded = reloadOnConfigChange ? readConfig(configFile) : undefined;\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) {\n exposeStop?.(() => first.close());\n return first;\n }\n\n let server = first;\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n let stopped = false;\n const restart = async () => {\n if (stopped) return;\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await beforeRestart?.();\n await server.close();\n server = await (restartWith\n ? restartWith(() => start(false))\n : start(false));\n };\n const queueRestart = () => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file === CONFIG_FILE) queueRestart();\n });\n watcher.unref();\n exposeStop?.(async () => {\n stopped = true;\n clearTimeout(timer);\n watcher.close();\n // A restart under way ends first: it leaves the server to close.\n await restarts;\n await server.close();\n });\n // Catch config edits made while the first server was starting.\n queueRestart();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAeA,MAAM,cAAc;AACpB,MAAM,qBAAqB;AAwB3B,SAAS,WAAW,MAAuB;CACzC,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EAEN;CACF;AACF;;AAGA,eAAsB,iBACpB,MACA,cACA,gBAGA,EACE,QACA,UACA,sBACA,OACA,YACA,eACA,aACA,eACwB,CAAC,GACH;CACxB,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,aAAa,KAAK,SAAS,WAAW;CAG5C,MAAM,cAAkC,cAAc;EACpD,MAAM;EACN,gBAAgB,QAAQ;GACtB,OAAO,YAAY,IACjB,gBACE,mBAAmB,YAAY,OAAO,GACtC,OAAO,OAAO,IAChB,CACF;EACF;CACF;CAEA,MAAM,QAAQ,OAAO,UAAmB;EACtC,MAAM,WACJ,OAAO,mBAAmB,aAAa,eAAe,IAAI;EAC5D,MAAM,aAAa,yBAAyB;GAC1C;GACA;GACA,oBAAoB,2BAA2B,MAAM,QAAQ;GAC7D;GACA;EACF,CAAC;EACD,MAAM,kBAAgC;GAEpC,QAAQ;IACN;IACA;IACA,MAAM,SAAS;IACf;IACA;IACA,GAAI,QAAQ,EAAE,OAAO,iBAAiB,KAAK,EAAE,IAAI,CAAC;GACpD;GACA;GACA,GAAI,cA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M;EACN,MAAM,OAAO,MAAM;CACrB,CAAC;CAED,aAAa;CACb,OAAO;AACT","debug_id":"45f8b5d8-1060-52b3-9245-0bfc43a7542e"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dist-D_UjZsgt.mjs","sources":["../../../packages/host-core/dist/index.mjs"],"sourcesContent":["import { $ as computeOutputsHash, $n as runProvideHook, $t as resolveHostPlugins, A as STOP_RUN_TIMEOUT_MS, An as placementKeyIssues, At as resolveHostOutputs, B as probeRun, Bn as runnerKindSchema, Bt as checkTokenSites, C as applyChildWrapper, Cn as emitHostJsonSchema, Ct as packageBuildRefusal, D as COMPOUND_MEMBER_ENV, Dn as makeHostSchemas, Dt as TokenResolutionError, E as spawnHost, En as hostNameSchema, Et as validateHost, F as stopChannelPath, Fn as reactorProtocolSchema, Ft as BUILTIN_ENV_NAMES, G as writeRunRecord, Gn as normalizePluginEntries, Gt as schemaAtPath, H as readRunRecord, Hn as entryActiveForVerb, Ht as outputRefsOf, I as stopRun, In as reactorSchema, It as isBuiltinEnvName, J as checkRunnerArgv, Jn as pluginEntrySchema, Jt as formatPath, K as runRecordMemberSchema, Kn as normalizePluginEntry, Kt as collectTokenSites, L as clearRunRecord, Ln as refineConnectReactor, Lt as substituteBuiltinEnv, M as installStopChannel, Mn as reactorBackendKindSchema, Mt as PlanError, N as listenForStop, Nn as reactorBackendSchema, Nt as memberForRef, O as takeCompoundMember, On as memberProcessSchema, Ot as describeMapElements, P as requestStop, Pn as reactorHostSchema, Pt as planCompound, Q as OUTPUTS_FILE, Qn as runObserveHookSequential, Qt as findDeadConnectConfig, R as isPidAlive, Rn as refineStartOrder, Rt as findRemovedForms, S as resolveUserDataPlaceholders, Sn as defineHostSchemas, Sr as tokenable, St as listVerbs, T as SpawnHostError, Tn as genericCompoundHostSchema, Tt as validateDeclaredHost, U as recordKeyOf, Un as hostTypeSatisfies, Ut as outputSitesOf, V as readProjectName, Vn as PluginError, Vt as envSitesOf, W as runRecordKey, Wn as mergeContributions, Wt as refKey, X as splitCompoundArgv, Xn as resolveOrder, Xt as renderTokens, Y as isRunnerArgsSchema, Yn as registerHostType, Yt as isPlainObject, Z as splitRunArgv, Zn as runObserveHook, Zt as unwrapEscapes, _ as processResolveEnv, _n as compoundHostSchema, _r as mapTokenSchema, _t as getVerb, a as memberProcessOf, an as locateHost, ar as drivesSchema, at as loadHost, b as runnerOutputsSchema, bn as declaredGenericCompoundHostSchema, br as tokenKeyOf, bt as kindShapeIssues, c as prepareMember, cn as CONNECT_PRIMARY_MESSAGE, cr as TOKEN_KEYS, ct as probeHostsFolder, d as takesCspRegistrySync, dn as HOST_NAME_PATTERN, dr as envTokenable, dt as stripComments, en as resolvePluginContributions, er as runTransformHook, et as describeHostOutputs, f as runnerHandleSchema, fn as HOST_REF_MESSAGE, fr as findToken, ft as withoutHostsMessage, g as loadProducers, gn as childrenSchema, gr as keyTokenSchema, gt as STORE_VERBS, h as OUTPUT_DATA_DIRS_ENV, hn as childWrapperSchema, hr as itemTokenSchema, ht as RunnerError, i as memberCycle, in as hostFileLabel, ir as driveDeclarationSchema, it as lintOutputsFile, j as askToStop, jn as profileSchema, jt as unsetEnvMessage, k as STOP_ON_STDIN_ENV, kn as originOrUrlSchema, kt as emptyMaps, l as runCompound, ln as HOST_NAME_MAX_LENGTH, lr as concatTokenSchema, lt as readOutputsFileHash, m as compoundOutputSource, mn as PACKAGE_NAME_PATTERN, mr as isToken, mt as ONE_SHOT_VERBS, n as compoundStartVerb, nn as findHostPackage, nr as defaultConnectComposition, nt as lintHostImportGraph, o as memberVerbOf, on as parseHostRef, or as projectDriveIdWith, ot as loadHostFresh, p as toStartedHandle, pn as HOST_REF_PATTERN, pr as forbidRef, pt as CONNECT_RUNNER, q as runRecordSchema, qn as pluginEntryObjectSchema, qt as describeToken, r as holdStopRequests, rn as formatHostRef, rr as buildDriveDeclarationSchema, rt as lintHostImports, s as planForeground, sn as resolvePackageRoot, sr as TOKEN_ESCAPE_KEY, st as moduleRootOf, t as STOP_STREAM_LIMIT_MS, tn as HostLoadError, tr as CONNECT_PLUGIN_OWNED_SLICES, tt as findNonStaticValue, u as stopStreamOf, un as HOST_NAME_MESSAGE, ur as envTokenSchema, ut as scanHostImports, v as producerOutputsSchemas, vn as compoundWiringSchema, vr as outputTokenSchema, vt as hostSchemaIssues, w as SPAWN_STOPPING_NOTE, wn as emittedHostSchemas, wt as resolveRunnerModule, x as defaultUserDataDir, xn as declaredHostSchemas, xr as tokenSchema, xt as knownVerbIssues, y as runRecordOutputSource, yn as connectReactorIssues, yr as ref, yt as isSchemaLike, z as listRunRecords, zn as runnerBaseSchema, zt as checkOutputPaths } from \"./compound-Q9sZSEZF.mjs\";\nimport { CONTROL_PROTOCOL, ControlError, callControl, closeProcessControlChannel, controlRecordOf, controlRecordSchema, ensureProcessControlChannel, openControlChannel, processControlChannel } from \"./control-channel.mjs\";\nimport { killTree } from \"./kill-tree.mjs\";\nimport crypto from \"node:crypto\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { driveAddressMessage, switchboardOfDrive, switchboardOfDrive as switchboardOfDrive$1 } from \"@powerhousedao/shared/host-tokens\";\nimport { ORIGIN_PLACEHOLDER, SWITCHBOARD_PROXY_PATHS, isHtmlNavigation, isOriginPlaceholderUrl, isSwitchboardProxyPath, resolveOriginPlaceholders, toOriginPlaceholder, withOriginPlaceholders } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { DEFAULT_CONNECT_STUDIO_PORT, DEFAULT_SWITCHBOARD_PORT } from \"@powerhousedao/shared/clis/constants\";\nimport { DRIVE_ICON_MAX_BYTES, resolveImageRef } from \"@powerhousedao/shared/connect/image-ref\";\n//#region src/check-host.ts\n/** The `ph run` pipeline up to the verb, collecting every issue; starts\n* nothing. `name` is a ref: a project host, or `<package>/<host>`. */\nasync function checkHost(name, options) {\n\tconst result = {\n\t\tissues: [],\n\t\twarnings: [],\n\t\tdeferred: []\n\t};\n\tlet file = `hosts/${name}/host.js`;\n\tconst verb = options.verb ?? \"run\";\n\tlet host;\n\tlet runner;\n\tlet hostPackage;\n\ttry {\n\t\tconst loaded = await loadHost(options.projectRoot, name);\n\t\thost = loaded.host;\n\t\thostPackage = loaded.package;\n\t\tfile = hostFileLabel(loaded.name, hostPackage);\n\t\trunner = await resolveRunnerModule(moduleRootOf(options.projectRoot, loaded), host.runner.module);\n\t} catch (error) {\n\t\tissuer(result, file)(\"load\", \"\", error);\n\t\treturn result;\n\t}\n\tconst specifier = host.runner.module;\n\tif (hostPackage && ONE_SHOT_VERBS.has(verb)) {\n\t\tissuer(result, file)(\"declared\", packageBuildRefusal(name, hostPackage, verb));\n\t\treturn result;\n\t}\n\tif (runner.kind === \"compound\") {\n\t\tawait checkCompound(result, options, {\n\t\t\tfile,\n\t\t\thost,\n\t\t\trunner,\n\t\t\tspecifier,\n\t\t\tverb,\n\t\t\thostPackage\n\t\t});\n\t\treturn result;\n\t}\n\tconst refs = outputRefsOf(host);\n\tconst producers = await loadProducers(options.projectRoot, refs, hostPackage);\n\tawait checkSubject(result, options, {\n\t\tfile,\n\t\thost,\n\t\trunner,\n\t\tspecifier,\n\t\tverb,\n\t\thostPackage,\n\t\toutputsSchemaOf: producerOutputsSchemas(producers),\n\t\tself: \"outputs\"\n\t});\n\treturn result;\n}\n/** Declared validation; returns whether its tokens and its shape passed. */\nfunction checkDeclared(result, subject, outputsSchemaOf) {\n\tconst issue = issuer(result, subject.file);\n\tconst { host, runner, specifier } = subject;\n\ttry {\n\t\tgetVerb(runner, specifier, subject.verb);\n\t} catch (error) {\n\t\tissue(\"declared\", \"\", error);\n\t}\n\tconst tokenIssues = [\n\t\t...findRemovedForms(host),\n\t\t...checkTokenSites(host),\n\t\t...outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []\n\t];\n\tfor (const i of tokenIssues) issue(\"declared\", i);\n\tconst shapeIssues = runner.declaredHostSchema ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true) : kindShapeIssues(runner.kind, specifier, host);\n\tfor (const i of shapeIssues) issue(\"declared\", i);\n\treturn {\n\t\ttokens: tokenIssues.length === 0,\n\t\tshape: shapeIssues.length === 0\n\t};\n}\nfunction schemaIssuesOf(runner, schema, specifier, host, allowTokens) {\n\tconst checked = hostSchemaIssues(runner, schema, specifier, host, { tokens: allowTokens ? \"allow\" : \"forbid\" });\n\treturn [...checked.issues, ...checked.schemaIssues ?? []];\n}\nasync function checkSubject(result, options, subject) {\n\tconst issue = issuer(result, subject.file);\n\tconst { runner, specifier, file } = subject;\n\tconst declared = checkDeclared(result, subject, subject.outputsSchemaOf);\n\tconst resolveEnv = processResolveEnv(options.projectRoot, options.env, subject.hostPackage);\n\tconst patch = subject.patch ?? ((host) => host);\n\tif (ONE_SHOT_VERBS.has(subject.verb)) {\n\t\tif (!declared.tokens || !declared.shape) return;\n\t\tconst host = patch(substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}));\n\t\tconst schema = runner.declaredHostSchema ?? runner.hostSchema;\n\t\tfor (const i of schemaIssuesOf(runner, schema, specifier, host, true)) issue(\"resolved\", i);\n\t\treturn;\n\t}\n\tconst unset = envSitesOf(subject.host).filter((site) => !site.optional && !isBuiltinEnvName(site.name) && options.env[site.name] === void 0);\n\tfor (const site of unset) issue(\"resolve\", {\n\t\tpath: site.path,\n\t\tmessage: unsetEnvMessage(site.name)\n\t});\n\tif (!declared.tokens || unset.length > 0) return;\n\tlet resolved;\n\tlet deferred = [];\n\ttry {\n\t\tif (options.outputs) resolved = resolveHostOutputs(subject.host, {\n\t\t\toutputs: options.outputs,\n\t\t\t...resolveEnv\n\t\t});\n\t\telse {\n\t\t\tconst partial = resolveHostOutputs(subject.host, resolveEnv, { deferSelf: subject.self });\n\t\t\tresolved = partial.host;\n\t\t\tdeferred = partial.deferred;\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof TokenResolutionError && error.detail) issue(\"resolve\", {\n\t\t\tpath: error.detail.path,\n\t\t\tmessage: error.detail.reason\n\t\t});\n\t\telse issue(\"resolve\", \"\", error);\n\t\treturn;\n\t}\n\tresult.deferred.push(...deferred.map((d) => ({\n\t\t...d,\n\t\tfile\n\t})));\n\tif (!declared.shape) return;\n\tconst allow = deferred.length > 0;\n\tconst schema = allow ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema;\n\tconst checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), { tokens: allow ? \"allow\" : \"forbid\" });\n\tconst resolvedIssues = [...checked.issues, ...checked.schemaIssues ?? []];\n\tfor (const i of resolvedIssues) issue(\"resolved\", i);\n\tif (resolvedIssues.length > 0 || !runner.checkBoot) return;\n\ttry {\n\t\tconst boot = await runner.checkBoot(checked.data, {\n\t\t\tprojectRoot: options.projectRoot,\n\t\t\tverb: subject.verb,\n\t\t\tenv: options.env,\n\t\t\tfile\n\t\t});\n\t\tfor (const i of boot) issue(\"boot\", {\n\t\t\t...i,\n\t\t\tpath: i.path ?? \"\"\n\t\t});\n\t} catch (error) {\n\t\tissue(\"boot\", \"\", error);\n\t}\n}\nasync function checkCompound(result, options, subject) {\n\tconst issue = issuer(result, subject.file);\n\tconst { host, runner, specifier } = subject;\n\tconst declared = checkDeclared(result, subject);\n\tif (!declared.tokens || !declared.shape) return;\n\tif (!runner.declaredHostSchema) {\n\t\tconst own = schemaIssuesOf(runner, runner.hostSchema, specifier, host, true);\n\t\tfor (const i of own) issue(\"resolved\", i);\n\t\tif (own.length > 0) return;\n\t}\n\tconst children = isPlainObject(host.children) ? host.children : {};\n\tconst wiring = isPlainObject(host.config) ? host.config : {};\n\tconst verb = compoundStartVerb(subject.verb, host.runner);\n\tconst prepared = [];\n\tfor (const [key, member] of Object.entries(children)) try {\n\t\tprepared.push(await prepareMember(options.projectRoot, key, member, subject.hostPackage));\n\t} catch (error) {\n\t\tissuer(result, `hosts/${member.host}/host.js`)(\"load\", \"\", error);\n\t}\n\ttry {\n\t\tconst cycle = await memberCycle(options.projectRoot, prepared);\n\t\tif (cycle) issue(\"declared\", {\n\t\t\tpath: \"children\",\n\t\t\tmessage: `compound member cycle: ${cycle.join(\" -> \")}.`,\n\t\t\thint: \"A compound cannot run itself, directly or through another compound.\"\n\t\t});\n\t} catch (error) {\n\t\tissue(\"load\", \"children\", error);\n\t}\n\tconst members = Object.entries(children).map(([key, m]) => ({\n\t\tkey,\n\t\thost: m.host\n\t}));\n\tlet foreground;\n\tif (prepared.length === members.length) try {\n\t\tconst plan = planCompound(prepared.map((m) => ({\n\t\t\tkey: m.key,\n\t\t\thost: m.member.host,\n\t\t\trefs: outputSitesOf(m.draft).map(({ ref, path }) => ({\n\t\t\t\tref,\n\t\t\t\tpath\n\t\t\t}))\n\t\t})), wiring.startOrder);\n\t\tconst planned = planForeground(prepared, plan, wiring);\n\t\tfor (const i of planned.issues) issue(\"declared\", i);\n\t\tforeground = planned.foreground;\n\t} catch (error) {\n\t\tissue(\"declared\", \"\", error);\n\t}\n\tresult.warnings.push(...sharedPortWarnings(subject.file, prepared));\n\tconst byKey = new Map(prepared.map((m) => [m.key, m]));\n\tconst outputsSchemaOf = (ref) => {\n\t\tconst target = memberForRef(ref, members);\n\t\tif (\"error\" in target) return { error: target.error };\n\t\tconst producer = byKey.get(target.key);\n\t\treturn producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member \"${target.key}\"`) : { error: `names member \"${target.key}\", which was not prepared.` };\n\t};\n\tfor (const m of prepared) {\n\t\tconst isForeground = m.key === foreground;\n\t\tif (isForeground && ONE_SHOT_VERBS.has(verb)) continue;\n\t\tif (m.hostPackage && ONE_SHOT_VERBS.has(verb)) {\n\t\t\tissue(\"declared\", {\n\t\t\t\t...packageBuildRefusal(m.ref, m.hostPackage, verb),\n\t\t\t\tpath: `children.${m.key}`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);\n\t\tawait checkSubject(result, options, {\n\t\t\tfile: m.file,\n\t\t\thost: m.draft,\n\t\t\trunner: m.runner,\n\t\t\tspecifier: m.specifier,\n\t\t\t...m.hostPackage ? { hostPackage: m.hostPackage } : {},\n\t\t\tverb: isForeground ? m.draft.runner.defaultVerb ?? \"run\" : memberVerbOf(verb, m.draft.runner),\n\t\t\toutputsSchemaOf,\n\t\t\tself: { members },\n\t\t\t...csp ? { patch: (resolved) => ({\n\t\t\t\t...resolved,\n\t\t\t\trunner: {\n\t\t\t\t\t...resolved.runner,\n\t\t\t\t\tcspRegistrySync: true\n\t\t\t\t}\n\t\t\t}) } : {}\n\t\t});\n\t}\n}\nconst SWITCHBOARD_RUNNER = \"@powerhousedao/ph-cli/runners/switchboard\";\n/** The port a member binds: its own literal, else its ph-cli runner's default. */\nfunction boundPortOf(m) {\n\tconst port = m.draft.runner.port;\n\tif (port === void 0) {\n\t\tif (m.specifier === \"@powerhousedao/ph-cli/runners/connect\") return DEFAULT_CONNECT_STUDIO_PORT;\n\t\tif (m.specifier === SWITCHBOARD_RUNNER) return DEFAULT_SWITCHBOARD_PORT;\n\t\treturn;\n\t}\n\treturn typeof port === \"number\" && Number.isInteger(port) && port > 0 ? port : void 0;\n}\n/** Members binding one port: under `ph run` the later one moves or fails. */\nfunction sharedPortWarnings(file, prepared) {\n\tconst owners = /* @__PURE__ */ new Map();\n\tconst warnings = [];\n\tfor (const m of prepared) {\n\t\tconst port = boundPortOf(m);\n\t\tif (port === void 0) continue;\n\t\tconst other = owners.get(port);\n\t\tif (!other) {\n\t\t\towners.set(port, m);\n\t\t\tcontinue;\n\t\t}\n\t\tconst connects = m.specifier === \"@powerhousedao/ph-cli/runners/connect\" && other.specifier === \"@powerhousedao/ph-cli/runners/connect\";\n\t\twarnings.push({\n\t\t\tstage: \"declared\",\n\t\t\tfile,\n\t\t\tpath: `children.${m.key}.runner.port`,\n\t\t\tmessage: connects ? `${other.key} and ${m.key} both use port ${port}. One will move to the next free port and lose its browser data.` : `${other.key} and ${m.key} both use port ${port}. One will move to the next free port or fail to start.`\n\t\t});\n\t}\n\treturn warnings;\n}\nfunction issuer(result, file) {\n\treturn (stage, found, error) => {\n\t\tif (typeof found !== \"string\") {\n\t\t\tconst { path, message, hint } = found;\n\t\t\tresult.issues.push({\n\t\t\t\tstage,\n\t\t\t\tfile,\n\t\t\t\tpath,\n\t\t\t\tmessage,\n\t\t\t\t...hint ? { hint } : {}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst [message, hint] = (error instanceof Error ? error.message : String(error)).split(\"\\n Hint: \");\n\t\tresult.issues.push({\n\t\t\tstage,\n\t\t\tfile,\n\t\t\tpath: found,\n\t\t\tmessage,\n\t\t\t...hint ? { hint } : {}\n\t\t});\n\t};\n}\n//#endregion\n//#region src/host-export-schema.ts\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction childFolders$1(host) {\n\tif (!isRecord$1(host) || !isRecord$1(host.children)) return [];\n\treturn Object.entries(host.children).flatMap(([key, child]) => isRecord$1(child) && typeof child.host === \"string\" ? [[key, child.host]] : []);\n}\nconst declaredHostSchema = z.custom().superRefine((host, ctx) => {\n\tconst result = (isRecord$1(host) && \"children\" in host ? declaredHostSchemas.compoundHostSchema : declaredHostSchemas.reactorHostSchema).safeParse(host);\n\tif (result.success) return;\n\tfor (const issue of result.error.issues) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: issue.message,\n\t\tpath: issue.path\n\t});\n});\n/** `ph host export`: a declared host plus its members, keyed by folder. */\nconst hostExportSchema = z.strictObject({\n\tformat: z.literal(\"ph-host-export\"),\n\tversion: z.literal(1),\n\tproject: z.strictObject({\n\t\tname: z.string().min(1),\n\t\troot: z.string().min(1)\n\t}),\n\tname: z.string().min(1),\n\thost: declaredHostSchema,\n\tmembers: z.record(z.string(), declaredHostSchema)\n}).superRefine((value, ctx) => {\n\tconst reached = /* @__PURE__ */ new Set();\n\tconst pending = [[[\"host\"], value.host]];\n\tfor (let next = pending.shift(); next; next = pending.shift()) {\n\t\tconst [at, host] = next;\n\t\tfor (const [key, folder] of childFolders$1(host)) {\n\t\t\tif (!(folder in value.members)) {\n\t\t\t\tctx.addIssue({\n\t\t\t\t\tcode: \"custom\",\n\t\t\t\t\tpath: [\n\t\t\t\t\t\t...at,\n\t\t\t\t\t\t\"children\",\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\"host\"\n\t\t\t\t\t],\n\t\t\t\t\tmessage: `Member folder \"${folder}\" is missing from members.`\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (reached.has(folder)) continue;\n\t\t\treached.add(folder);\n\t\t\tpending.push([[\"members\", folder], value.members[folder]]);\n\t\t}\n\t}\n\tfor (const folder of Object.keys(value.members)) {\n\t\tif (reached.has(folder)) continue;\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"members\", folder],\n\t\t\tmessage: `Member \"${folder}\" is not reached from the host's children.`\n\t\t});\n\t}\n});\n//#endregion\n//#region src/host-export.ts\nfunction checkHint(name) {\n\treturn `Run \\`ph host check ${name}\\`.`;\n}\nfunction childFolders(host, name) {\n\tif (!(\"children\" in host)) return [];\n\tconst parsed = declaredHostSchemas.childrenSchema.safeParse(host.children);\n\tif (!parsed.success) throw new HostLoadError(`hosts/${name}/host.js: invalid \\`children\\`:\\n${z.prettifyError(parsed.error)}`, checkHint(name));\n\treturn Object.values(parsed.data).map((child) => child.host);\n}\n/** A host as declared and every member it reaches, raw `loadHost` bodies. */\nasync function exportHost(projectRoot, name) {\n\tconst root = path.resolve(projectRoot);\n\tconst { host } = await loadHost(root, name);\n\tconst members = {};\n\tconst visit = async (folders) => {\n\t\tfor (const folder of folders) {\n\t\t\tif (folder in members) continue;\n\t\t\tconst member = (await loadHost(root, folder)).host;\n\t\t\tmembers[folder] = member;\n\t\t\tawait visit(childFolders(member, folder));\n\t\t}\n\t};\n\tawait visit(childFolders(host, name));\n\tconst envelope = {\n\t\tformat: \"ph-host-export\",\n\t\tversion: 1,\n\t\tproject: {\n\t\t\tname: readProjectName(root),\n\t\t\troot\n\t\t},\n\t\tname,\n\t\thost,\n\t\tmembers\n\t};\n\tconst parsed = hostExportSchema.safeParse(JSON.parse(JSON.stringify(envelope)));\n\tif (!parsed.success) throw new HostLoadError(`hosts/${name}/host.js: the export is not a valid host export:\\n${z.prettifyError(parsed.error)}`, checkHint(name));\n\treturn envelope;\n}\n//#endregion\n//#region src/drives.ts\nconst sha256Hex = (input) => crypto.createHash(\"sha256\").update(input).digest(\"hex\");\nfunction projectDriveId(projectRoot, slug) {\n\treturn projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\nfunction resolveDriveDeclaration(projectRoot, decl) {\n\tconst id = decl.projectHash ? projectDriveId(projectRoot, decl.slug) : decl.id;\n\tconst slug = decl.projectHash === true ? id : decl.slug;\n\tif (decl.remote) return {\n\t\tkind: \"remote\",\n\t\tid,\n\t\tslug,\n\t\tname: decl.name ?? decl.slug,\n\t\tremoteUrl: decl.remote.url,\n\t\tsharingType: decl.sharingType ?? \"public\",\n\t\tavailableOffline: decl.availableOffline ?? true\n\t};\n\treturn {\n\t\tkind: \"local\",\n\t\tid,\n\t\tslug,\n\t\tdocumentType: decl.documentType,\n\t\tname: decl.name ?? decl.slug,\n\t\ticon: resolveImageRef(projectRoot, decl.icon, {\n\t\t\tmaxBytes: DRIVE_ICON_MAX_BYTES,\n\t\t\twarn: (m) => console.warn(m)\n\t\t}),\n\t\tpreferredEditor: decl.preferredEditor,\n\t\tsharingType: decl.sharingType ?? \"public\",\n\t\tavailableOffline: decl.availableOffline ?? true\n\t};\n}\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n* recreated, never mutated — preserveStrategy refinements live here later). */\nasync function seedDrives(client, drives) {\n\tconst result = {\n\t\tcreated: [],\n\t\texisting: [],\n\t\tattached: []\n\t};\n\tfor (const drive of drives) {\n\t\tif (drive.kind === \"remote\") {\n\t\t\tawait client.attachRemoteDrive(drive.remoteUrl);\n\t\t\tresult.attached.push(drive.slug);\n\t\t\tcontinue;\n\t\t}\n\t\tif (await client.findDriveBySlug(drive.slug) !== void 0) {\n\t\t\tresult.existing.push(drive.slug);\n\t\t\tcontinue;\n\t\t}\n\t\tawait client.createDrive(drive);\n\t\tresult.created.push(drive.slug);\n\t}\n\treturn result;\n}\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n* host file wins on conflicts (it is the most explicit source). */\nfunction mergeDrivePlan(projectRoot, hostDeclared, contributed) {\n\tconst plan = /* @__PURE__ */ new Map();\n\tfor (const { declaration, source } of contributed) {\n\t\tconst drive = resolveDriveDeclaration(projectRoot, declaration);\n\t\tplan.set(drive.slug, {\n\t\t\tdrive,\n\t\t\tsource\n\t\t});\n\t}\n\tfor (const declaration of hostDeclared) {\n\t\tconst drive = resolveDriveDeclaration(projectRoot, declaration);\n\t\tplan.set(drive.slug, {\n\t\t\tdrive,\n\t\t\tsource: \"host\"\n\t\t});\n\t}\n\treturn [...plan.values()];\n}\nfunction explainDrivePlan(plan) {\n\tif (plan.length === 0) return \"(no drives declared)\";\n\treturn [\"drives:\", ...plan.map(({ drive, source }) => {\n\t\tconst kind = drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n\t\tconst editor = drive.preferredEditor ? ` editor=${drive.preferredEditor}` : \"\";\n\t\tconst id = drive.id ?? \"generated\";\n\t\treturn ` ${drive.slug} (${kind}, id=${id}${editor}) [${source}]`;\n\t})].join(\"\\n\");\n}\n//#endregion\n//#region src/backend-projection.ts\nfunction projectStorage(name, storage) {\n\tswitch (storage.kind) {\n\t\tcase \"idb\": return { kind: \"idb\" };\n\t\tcase \"memory\": return { kind: \"memory\" };\n\t\tcase \"path\":\n\t\t\tif (!storage.dataDir) throw new Error(`Backend \"${name}\": storage kind \"path\" requires dataDir.`);\n\t\t\treturn {\n\t\t\t\tkind: \"path\",\n\t\t\t\tdataDir: storage.dataDir\n\t\t\t};\n\t\tcase \"postgres\": throw new Error(`Backend \"${name}\": storage kind \"postgres\" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a \"remote\" backend at the switchboard that owns that database instead.`);\n\t}\n}\n/** One backend → one descriptor. The protocol's featureFlags ride every\n* descriptor (they are fleet consensus, not per-backend). A remote backend\n* must carry remote.url — provision() requires it. */\nfunction backendToDescriptor(name, backend, protocol) {\n\tconst descriptor = {\n\t\tkind: backend.kind,\n\t\tname\n\t};\n\tif (descriptor.kind === \"remote\") {\n\t\tconst url = backend.remote?.url;\n\t\tif (!url) throw new Error(`Backend \"${name}\" is kind \"remote\" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);\n\t\tdescriptor.remote = { url };\n\t\treturn descriptor;\n\t}\n\tif (backend.storage) descriptor.storage = projectStorage(name, backend.storage);\n\tif (backend.packages) descriptor.packages = backend.packages;\n\tif (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n\treturn descriptor;\n}\n/** All named backends, in placement-primary-first order (the order a\n* createReactorClients step would provision them). */\nfunction backendsToDescriptors(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return [];\n\tconst names = Object.keys(backends);\n\tconst primary = reactor.placement?.primary;\n\treturn (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));\n}\nconst LOCAL_KINDS = /* @__PURE__ */ new Set([\"in-process\", \"worker\"]);\n/**\n* Structural multi-reactor (phase 4): true when the block names BOTH a local\n* backend (in-process/worker — the tab's own reactor) and a remote one. This\n* is the shape Connect's routing client serves; a lone remote backend is an\n* attach-only host (assistant/agent shape), not a routed tab.\n*/\nfunction isStructuralMultiReactor(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return false;\n\tconst kinds = Object.values(backends).map((b) => b.kind);\n\treturn kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\");\n}\n/** The remote backends' drive addresses, placement order. */\nfunction remoteBackendUrls(reactor) {\n\treturn backendsToDescriptors(reactor).filter((d) => d.kind === \"remote\").map((d) => d.remote?.url).filter((u) => typeof u === \"string\");\n}\n/**\n* The remote backends by host key, placement order, each with the\n* connection settings it sets. A url that is not a string yet (an output\n* token, unresolved when a host builds) is skipped, as in remoteBackendUrls.\n*/\nfunction remoteBackends(reactor) {\n\treturn backendsToDescriptors(reactor).flatMap((d) => {\n\t\tconst remote = reactor?.backends?.[d.name]?.remote;\n\t\tif (d.kind !== \"remote\" || typeof d.remote?.url !== \"string\" || !remote) return [];\n\t\tconst { requestTimeoutMs, breaker, realtime } = remote;\n\t\treturn [{\n\t\t\tname: d.name,\n\t\t\turl: d.remote.url,\n\t\t\t...requestTimeoutMs !== void 0 ? { requestTimeoutMs } : {},\n\t\t\t...breaker !== void 0 ? { breaker } : {},\n\t\t\t...realtime !== void 0 ? { realtime } : {}\n\t\t}];\n\t});\n}\n//#endregion\n//#region src/reactor-config.ts\n/**\n* The shared `reactor` host-config block and its projections onto the\n* Switchboard config / Connect runtime config. Phase 2 of uniform-runners: makes\n* the reactor block live through the bridge runners, BEFORE track R replaces\n* the projection with reactor-monitor's provision(). The headline is\n* single-sourced `reactor.protocol` — both projections read the same block, so\n* client and server cannot diverge, and a contradicting pre-set env fails boot.\n*/\n/** A switchboard host's own store. Prefers placement.primary, else\n* \"main\"/\"local\", else the first. Connect refuses placement.primary: its\n* reactor is {@link browserBackend}. */\nfunction primaryBackend(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return void 0;\n\tconst names = Object.keys(backends);\n\tif (names.length === 0) return void 0;\n\treturn backends[reactor.placement?.primary ?? (names.includes(\"main\") ? \"main\" : names.includes(\"local\") ? \"local\" : names[0])];\n}\nconst FLAG_ENV = {\n\tdocumentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n\tauthEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n\tauthGroups: \"REACTOR_AUTH_GROUPS\",\n\tauthConditions: \"REACTOR_AUTH_CONDITIONS\",\n\tundoV3: \"REACTOR_UNDO_V3\"\n};\n/** The env vars a protocol block maps onto, with their string values. Only\n* keys the block actually sets appear. */\nfunction protocolEnv(protocol) {\n\tconst env = {};\n\tif (!protocol) return env;\n\tfor (const [key, varName] of Object.entries(FLAG_ENV)) {\n\t\tconst value = protocol.featureFlags?.[key];\n\t\tif (value !== void 0) env[varName] = value ? \"true\" : \"false\";\n\t}\n\tif (protocol.createSignaturePolicy !== void 0) env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n\tif (protocol.unsupportedStoredDocuments !== void 0) env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS = protocol.unsupportedStoredDocuments;\n\treturn env;\n}\n/** The reactor block as a switchboard config layer. The reactor store and the\n* read model are separate fields: `readModel.url` never moves the reactor. */\nfunction reactorBlockToSwitchboardConfig(reactor) {\n\tconst layer = {};\n\tconst backend = primaryBackend(reactor);\n\tconst storage = backend?.storage;\n\tconst reactorUrl = storage?.kind === \"postgres\" ? storage.url : storage?.dataDir;\n\tconst readModelUrl = backend?.readModel?.url;\n\tif (reactorUrl || readModelUrl) layer.storage = {\n\t\t...reactorUrl ? { reactor: { url: reactorUrl } } : {},\n\t\t...readModelUrl ? { readModel: { url: readModelUrl } } : {}\n\t};\n\tif (reactor?.protocol) layer.protocol = reactor.protocol;\n\tif (backend?.packages?.dynamic) layer.packages = { dynamic: true };\n\treturn layer;\n}\nconst LOCAL_BACKEND_KINDS = /* @__PURE__ */ new Set([\"in-process\", \"worker\"]);\n/** Connect's browser reactor: its first in-process or worker backend. */\nfunction browserBackend(reactor) {\n\tconst entry = Object.entries(reactor?.backends ?? {}).find(([, backend]) => LOCAL_BACKEND_KINDS.has(backend.kind));\n\treturn entry ? {\n\t\t...entry[1],\n\t\tname: entry[0]\n\t} : void 0;\n}\n/**\n* Which reactor client the backend topology asks for:\n* - local (in-process/worker) AND remote backends -> `router`\n* - remote backend(s) only -> `remote`\n* - a worker backend -> `worker`\n* - anything else local -> `in-process`\n* `undefined` when no backends are declared: Connect then runs `in-process`.\n*/\nfunction reactorClientMode(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return void 0;\n\tconst kinds = Object.values(backends).map((b) => b.kind);\n\tif (kinds.length === 0) return void 0;\n\tconst hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n\tconst hasRemote = kinds.some((k) => k === \"remote\");\n\tif (hasLocal && hasRemote) return \"router\";\n\tif (hasRemote) return \"remote\";\n\treturn browserBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n/** Served only when `newDrives` names a served remote backend: a local one\n* is the default, and Connect refuses one it has no address for. */\nfunction connectRouterSettings(reactor, served) {\n\tconst newDrives = reactor?.placement?.newDrives;\n\tconst { probeTimeoutMs, provisionalRouteMs } = reactor?.router ?? {};\n\tconst router = {\n\t\t...newDrives !== void 0 && served.some((remote) => remote.name === newDrives) ? { newDrives } : {},\n\t\t...probeTimeoutMs !== void 0 ? { probeTimeoutMs } : {},\n\t\t...provisionalRouteMs !== void 0 ? { provisionalRouteMs } : {}\n\t};\n\treturn Object.keys(router).length > 0 ? router : void 0;\n}\nfunction connectStorage(backend) {\n\tconst kind = backend?.storage?.kind;\n\treturn kind === \"idb\" || kind === \"memory\" ? kind : void 0;\n}\n/** Why the browser reactor's declared store can't be served: Connect keeps\n* IndexedDB instead of a folder or Postgres. */\nfunction unservedConnectStorage(reactor) {\n\tconst browser = browserBackend(reactor);\n\tconst kind = browser?.storage?.kind;\n\tif (!browser || !kind || connectStorage(browser)) return void 0;\n\treturn `reactor.backends.${browser.name}.storage \"${kind}\": Connect's browser reactor can't use it and keeps IndexedDB instead.`;\n}\n/** Project the reactor block onto the Connect runtime config: protocol →\n* connect.reactor (same shape), backend topology → instance.reactorWorker\n* (the browser reactor's kind), instance.reactorClient, instance.storage\n* (the browser reactor's store), and with a\n* switchboard instance.remoteBackends and instance.router. */\nfunction projectReactorToConnect(reactor) {\n\tconst connect = {};\n\tif (reactor?.protocol) connect.reactor = reactor.protocol;\n\tconst mode = reactorClientMode(reactor);\n\tif (mode !== void 0) {\n\t\tconst routed = mode === \"router\" || mode === \"remote\";\n\t\tconst served = routed ? remoteBackends(reactor) : [];\n\t\tconst router = routed ? connectRouterSettings(reactor, served) : void 0;\n\t\tconst browser = browserBackend(reactor);\n\t\tconst storage = connectStorage(browser);\n\t\tconnect.instance = {\n\t\t\treactorWorker: browser?.kind === \"worker\",\n\t\t\treactorClient: mode,\n\t\t\t...storage ? { storage } : {},\n\t\t\t...routed ? { remoteBackends: served } : {},\n\t\t\t...router ? { router } : {}\n\t\t};\n\t}\n\treturn { connect };\n}\n/** Whether an env value means what the host's value does. The switchboard\n* reads REACTOR_UNDO_V3 as on unless it is exactly \"false\". */\nfunction protocolEnvAgrees(varName, envValue, hostValue) {\n\tif (varName === FLAG_ENV.undoV3) return envValue !== \"false\" === (hostValue === \"true\");\n\treturn envValue === hostValue;\n}\n/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n* message naming the var, the host value and the env value. An env var that\n* merely matches, or is unset, is fine. */\nfunction protocolConflicts(protocol, env, hostFile = \"the host file\") {\n\tif (!protocol) return [];\n\treturn Object.entries(protocolEnv(protocol)).flatMap(([varName, hostValue]) => {\n\t\tconst envValue = env[varName];\n\t\tif (envValue === void 0 || protocolEnvAgrees(varName, envValue, hostValue)) return [];\n\t\treturn [`reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`];\n\t});\n}\n/**\n* The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n* the host's protocol block, fail loudly naming the var, the host value, and\n* the env value (phase-2 transition keeps an operator's explicit env as an\n* escape hatch unless it disagrees with the protocol — see the WBS\n* precedence note).\n*/\nfunction assertProtocolConsistency(protocol, env, hostFile = \"the host file\") {\n\tconst conflict = protocolConflicts(protocol, env, hostFile).at(0);\n\tif (conflict) throw new Error(conflict);\n}\n//#endregion\n//#region src/connect-projection.ts\n/**\n* Instance-fact projection for compound hosts: the drives a compound's\n* reactor member created, projected into the Connect member's runtime-config\n* override. Pure functions, moved from ph-cli's vetra service so the generic\n* compound and the classic path share one implementation.\n*/\nfunction isLocalDrive(drive) {\n\treturn \"local\" in drive;\n}\nconst driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n/**\n* Concatenate groups of `connect.drives.defaultDrives` in the order given,\n* de-duplicating by drive identity (URL for remote entries, id for local\n* ones). The first occurrence of a drive wins, so earlier groups keep their\n* position and metadata — e.g. the Vetra drive `ph dev` starts stays first\n* even when the project's `powerhouse.config.json` lists the same drive.\n*/\nfunction mergeDefaultDrives(...groups) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst out = [];\n\tfor (const group of groups) for (const drive of group) {\n\t\tconst key = driveKey(drive);\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tout.push(drive);\n\t}\n\treturn out;\n}\n/**\n* Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n* swaps the loopback origin for the public base. Browser clients behind a\n* reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n* (e.g. a remote drive) are already public and pass through unchanged, as do\n* unparseable ones.\n*/\nfunction rebaseDriveUrl(driveUrl, publicBase) {\n\tlet url;\n\ttry {\n\t\turl = new URL(driveUrl);\n\t} catch {\n\t\treturn driveUrl;\n\t}\n\tif (![\n\t\t\"localhost\",\n\t\t\"127.0.0.1\",\n\t\t\"[::1]\"\n\t].includes(url.hostname)) return driveUrl;\n\treturn `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n/**\n* The compound's drives projection: created drives first (rebased onto the\n* public base when given), then the project's configured drives, de-duplicated\n* — and `preserve-all`, because compound-injected drive lists change per\n* launch context and must never detach drives the user added by hand.\n*/\nfunction projectDrivesIntoConnect(input) {\n\treturn { drives: {\n\t\tdefaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === \"string\" && url.length > 0).map((url) => ({\n\t\t\turl: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n\t\t\tname: null,\n\t\t\ticon: null\n\t\t})), input.configuredDefaultDrives ?? []),\n\t\tpreserveStrategy: \"preserve-all\"\n\t} };\n}\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nfunction servesSlug(declared, served) {\n\treturn served === declared || served.startsWith(`${declared}-`) && /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1));\n}\n/** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */\nfunction placeConnectDrives(reactor, defaultDrives) {\n\tconst remotes = remoteBackends(reactor).flatMap(({ name, url }) => {\n\t\tconst at = switchboardOfDrive$1(url);\n\t\treturn at ? [{\n\t\t\tname,\n\t\t\tbase: at.base\n\t\t}] : [];\n\t});\n\tif (remotes.length === 0) return { defaultDrives: [...defaultDrives] };\n\tconst placement = Object.entries(reactor?.placement?.drives ?? {});\n\tconst matched = /* @__PURE__ */ new Set();\n\tconst placed = defaultDrives.map((drive) => {\n\t\tif (!(\"url\" in drive)) return drive;\n\t\tconst at = switchboardOfDrive$1(drive.url);\n\t\tconst backend = remotes.find((remote) => remote.base === at?.base)?.name;\n\t\tif (!at || !backend) return drive;\n\t\tconst entry = placement.find(([slug]) => servesSlug(slug, at.slug));\n\t\tif (entry) matched.add(entry[0]);\n\t\treturn entry?.[1] === backend ? {\n\t\t\t...drive,\n\t\t\tbackend,\n\t\t\tsync: false\n\t\t} : {\n\t\t\t...drive,\n\t\t\tbackend\n\t\t};\n\t});\n\tconst names = new Set(remotes.map((remote) => remote.name));\n\tconst collections = Object.fromEntries(placement.filter(([slug, backend]) => !matched.has(slug) && names.has(backend)).map(([slug, backend]) => [slug, {\n\t\tbackend,\n\t\tsync: false\n\t}]));\n\treturn Object.keys(collections).length > 0 ? {\n\t\tdefaultDrives: placed,\n\t\tcollections\n\t} : { defaultDrives: placed };\n}\n//#endregion\n//#region src/expect-host.ts\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction runnerOf(host) {\n\treturn isRecord(host.runner) ? host.runner : {};\n}\nfunction defaultVerbOf(host) {\n\tconst verb = runnerOf(host).defaultVerb;\n\treturn typeof verb === \"string\" ? verb : void 0;\n}\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n* compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb, member) {\n\treturn compoundVerb === \"run\" ? defaultVerbOf(member) ?? \"run\" : compoundVerb;\n}\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor) {\n\tconst backends = Object.entries(reactor.backends ?? {});\n\tconst primary = reactor.placement?.primary;\n\treturn [...backends.filter(([name]) => name === primary), ...backends.filter(([name]) => name !== primary)];\n}\nfunction expectBackend(name, backend, reactor) {\n\tconst out = {\n\t\tname,\n\t\tkind: backend.kind\n\t};\n\tif (backend.storage) out.storage = backend.storage.kind;\n\tif (typeof backend.storage?.dataDir === \"string\") out.dataDir = backend.storage.dataDir;\n\ttry {\n\t\tbackendToDescriptor(name, backend, reactor.protocol);\n\t} catch (error) {\n\t\tout.provisionError = error instanceof Error ? error.message : String(error);\n\t}\n\treturn out;\n}\nfunction expectDrive(declaration, source) {\n\tif (typeof declaration.slug !== \"string\") return void 0;\n\tconst remote = isRecord(declaration.remote) ? declaration.remote : void 0;\n\tconst drive = {\n\t\tslug: declaration.slug,\n\t\tkind: remote ? \"remote\" : \"local\",\n\t\tsource\n\t};\n\tif (remote && typeof remote.url === \"string\") drive.url = remote.url;\n\tif (typeof declaration.id === \"string\") drive.id = declaration.id;\n\tconst projectHash = declaration.projectHash;\n\tif (typeof projectHash === \"boolean\" || projectHash === \"id\") drive.projectHash = projectHash;\n\treturn drive;\n}\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n* `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive) {\n\treturn drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n/** Contributions first, then host declarations; keyed by served slug, the\n* host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(reactor, contributed) {\n\tconst plan = /* @__PURE__ */ new Map();\n\tfor (const { declaration, source } of contributed) {\n\t\tconst drive = expectDrive(declaration, source);\n\t\tif (drive) plan.set(servedSlugKey(drive), drive);\n\t}\n\tfor (const declaration of reactor?.drives ?? []) {\n\t\tconst drive = expectDrive(declaration, \"host\");\n\t\tif (drive) plan.set(servedSlugKey(drive), drive);\n\t}\n\treturn [...plan.values()];\n}\n/** Token facts of the host's OWN fields (a compound's `children` are its\n* members' own). */\nfunction tokenFacts(declared, kind) {\n\tconst own = kind === \"compound\" ? Object.fromEntries(Object.entries(declared).filter(([key]) => key !== \"children\")) : declared;\n\tconst sites = outputSitesOf(own);\n\tconst consumes = sites.map(({ path, ref, outputPath }) => ({\n\t\tat: path,\n\t\thost: ref.host,\n\t\t...ref.member !== void 0 ? { member: ref.member } : {},\n\t\tpath: outputPath\n\t}));\n\treturn {\n\t\tdependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n\t\tconsumes,\n\t\tenv: [...new Set(envSitesOf(own).map(({ name }) => name))].sort()\n\t};\n}\nfunction expectOwn(input, verb) {\n\tconst resolved = input.resolved ?? input.declared;\n\tconst expectation = {\n\t\tname: typeof resolved.name === \"string\" ? resolved.name : \"\",\n\t\tkind: input.kind,\n\t\tverb,\n\t\t...tokenFacts(input.declared, input.kind)\n\t};\n\tif (input.kind !== \"reactor\") return expectation;\n\tconst reactor = isRecord(resolved.reactor) ? resolved.reactor : void 0;\n\tconst mode = reactorClientMode(reactor);\n\tif (mode !== void 0) expectation.clientMode = mode;\n\texpectation.multiReactor = isStructuralMultiReactor(reactor);\n\tconst backends = reactor ? orderedBackends(reactor) : [];\n\tif (reactor && backends.length > 0) {\n\t\texpectation.backends = backends.map(([name, backend]) => expectBackend(name, backend, reactor));\n\t\texpectation.remotes = backends.flatMap(([, backend]) => backend.kind === \"remote\" && typeof backend.remote?.url === \"string\" ? [backend.remote.url] : []);\n\t}\n\texpectation.drives = drivePlan(reactor, input.contributed ?? []);\n\treturn expectation;\n}\n/**\n* The expectation for one host. A reactor host's comes from its resolved\n* reactor block and contributed drives; a compound's lists its members in\n* plan order, each with the verb it runs at under the compound's own verb\n* and the members it starts after.\n*/\nfunction expectHost(input) {\n\tconst verb = defaultVerbOf(input.declared) ?? \"run\";\n\tconst expectation = expectOwn(input, verb);\n\tif (input.kind !== \"compound\" || !input.members) return expectation;\n\tconst order = input.plan?.order ?? input.members.map((m) => m.key);\n\tconst edges = input.plan?.edges ?? [];\n\tconst byKey = new Map(input.members.map((m) => [m.key, m]));\n\tconst members = {};\n\tfor (const key of order) {\n\t\tconst member = byKey.get(key);\n\t\tif (!member) continue;\n\t\tmembers[key] = {\n\t\t\thost: member.host,\n\t\t\t...expectOwn(member, memberVerb(verb, member.declared)),\n\t\t\tafter: [...new Set(edges.filter((e) => e.consumer === key).map((e) => e.producer))].sort()\n\t\t};\n\t}\n\texpectation.startOrder = order.filter((key) => byKey.has(key));\n\texpectation.members = members;\n\treturn expectation;\n}\n//#endregion\nexport { BUILTIN_ENV_NAMES, COMPOUND_MEMBER_ENV, CONNECT_PLUGIN_OWNED_SLICES, CONNECT_PRIMARY_MESSAGE, CONNECT_RUNNER, CONTROL_PROTOCOL, ControlError, HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE, HOST_NAME_PATTERN, HOST_REF_MESSAGE, HOST_REF_PATTERN, HostLoadError, ONE_SHOT_VERBS, ORIGIN_PLACEHOLDER, OUTPUTS_FILE, OUTPUT_DATA_DIRS_ENV, PACKAGE_NAME_PATTERN, PlanError, PluginError, RunnerError, SPAWN_STOPPING_NOTE, STOP_ON_STDIN_ENV, STOP_RUN_TIMEOUT_MS, STOP_STREAM_LIMIT_MS, STORE_VERBS, SWITCHBOARD_PROXY_PATHS, SpawnHostError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, applyChildWrapper, askToStop, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, browserBackend, buildDriveDeclarationSchema, callControl, checkHost, checkOutputPaths, checkRunnerArgv, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, closeProcessControlChannel, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, connectReactorIssues, controlRecordOf, controlRecordSchema, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultConnectComposition, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveAddressMessage, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, emptyMaps, ensureProcessControlChannel, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, exportHost, findDeadConnectConfig, findHostPackage, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatHostRef, formatPath, genericCompoundHostSchema, getVerb, holdStopRequests, hostExportSchema, hostFileLabel, hostNameSchema, hostSchemaIssues, hostTypeSatisfies, installStopChannel, isBuiltinEnvName, isHtmlNavigation, isOriginPlaceholderUrl, isPidAlive, isRunnerArgsSchema, isSchemaLike, isStructuralMultiReactor, isSwitchboardProxyPath, isToken, itemTokenSchema, keyTokenSchema, killTree, kindShapeIssues, knownVerbIssues, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, listenForStop, loadHost, loadHostFresh, loadProducers, locateHost, makeHostSchemas, mapTokenSchema, memberCycle, memberForRef, memberProcessOf, memberProcessSchema, mergeContributions, mergeDefaultDrives, mergeDrivePlan, moduleRootOf, normalizePluginEntries, normalizePluginEntry, openControlChannel, originOrUrlSchema, outputRefsOf, outputSitesOf, outputTokenSchema, packageBuildRefusal, parseHostRef, placeConnectDrives, placementKeyIssues, planCompound, planForeground, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processControlChannel, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, protocolConflicts, protocolEnv, protocolEnvAgrees, reactorBackendKindSchema, reactorBackendSchema, reactorBlockToSwitchboardConfig, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, recordKeyOf, ref, refKey, refineConnectReactor, refineStartOrder, registerHostType, remoteBackendUrls, remoteBackends, renderTokens, requestStop, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolveOriginPlaceholders, resolvePackageRoot, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordKey, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, spawnHost, splitCompoundArgv, splitRunArgv, stopChannelPath, stopRun, stopStreamOf, stripComments, substituteBuiltinEnv, switchboardOfDrive, takeCompoundMember, toOriginPlaceholder, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unservedConnectStorage, unwrapEscapes, validateDeclaredHost, validateHost, withOriginPlaceholders, withoutHostsMessage, writeRunRecord };\n\n//# sourceMappingURL=index.mjs.map"],"names":["z.custom","z.strictObject","z.literal","z.string","z.record","z.prettifyError"],"mappings":";;;;;;;;;;;;;AAaA,eAAe,UAAU,MAAM,SAAS;CACvC,MAAM,SAAS;EACd,QAAQ,CAAC;EACT,UAAU,CAAC;EACX,UAAU,CAAC;CACZ;CACA,IAAI,OAAO,SAAS,KAAK;CACzB,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;EACH,MAAM,SAAS,MAAM,SAAS,QAAQ,aAAa,IAAI;EACvD,OAAO,OAAO;EACd,cAAc,OAAO;EACrB,OAAO,cAAc,OAAO,MAAM,WAAW;EAC7C,SAAS,MAAM,oBAAoB,aAAa,QAAQ,aAAa,MAAM,GAAG,KAAK,OAAO,MAAM;CACjG,SAAS,OAAO;EACf,OA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AK,IAAI,GAAG;EACZ,IAAI,KAAK,KAAK;CACf;CACA,OAAO;AACR","debug_id":"b144ae09-3816-51e8-a623-3234baadf9d9"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-document-model-DSYPTMZg.mjs","sources":["../src/services/definitions/code-first-scaffold.ts","../src/services/generate-document-model.ts"],"sourcesContent":["import type { ModelGeneration } from \"@powerhousedao/codegen\";\nimport { capitalCase, kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Project } from \"ts-morph\";\n\nexport async function scaffoldCodeFirstDocumentModel(\n generation: ModelGeneration,\n name: string,\n projectDir: string,\n project: Project,\n) {\n const modelName = name.trim();\n if (modelName === \"\") {\n throw new Error(\"--name needs a document model name.\");\n }\n const namespace = await documentTypeNamespace(projectDir);\n const documentType = `${namespace}/${kebabCase(modelName)}`;\n const editorName = `${capitalCase(modelName)} Editor`;\n const editorDirName = kebabCase(editorName);\n if (existsSync(join(projectDir, \"editors\", editorDirName))) {\n throw new Error(\n `editors/${editorDirName} already exists. Choose another --name, or move that editor first.`,\n );\n }\n\n const result = await generation.scaffoldDocumentModel(\n {\n name: modelName,\n documentType,\n author: { name: namespace, website: null },\n },\n project,\n );\n for (const path of result.written) {\n console.log(`Wrote ${path}`);\n }\n\n await generation.generateEditor(\n {\n editorName,\n documentTypes: [documentType],\n editorId: editorDirName,\n editorDirName,\n },\n project,\n );\n await project.save();\n console.log(`Generated editor \"${editorName}\" in editors/${editorDirName}`);\n}\n\nasync function documentTypeNamespace(projectDir: string) {\n const { name } = await readPackage({ cwd: projectDir, normalize: false });\n if (!name) {\n throw new Error(\n \"--name puts the document type under the package name. Add a name to package.json.\",\n );\n }\n return name.replace(/^@/, \"\").replaceAll(\"/\", \"-\");\n}\n","import { loadDocumentModel, modelGeneration } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n documentModelsDirOf,\n} from \"@powerhousedao/codegen/utils\";\nimport { handleMutuallyExclusiveOptions } from \"@powerhousedao/shared/clis\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { GenerateDocumentModelArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\nimport { scaffoldCodeFirstDocumentModel } from \"./definitions/code-first-scaffold.js\";\n\n/** The configured documentModelsDir, package-relative, for messages and paths. */\nfunction modelsDirOf(projectDir: string) {\n return relative(projectDir, documentModelsDirOf(projectDir).path).replaceAll(\n \"\\\\\",\n \"/\",\n );\n}\n\nexport async function startGenerateDocumentModel(\n args: GenerateDocumentModelArgs,\n projectDir: string,\n) {\n const { dir, all, name, codeFirst, debug } = args;\n if (debug) {\n console.log({ args });\n }\n if (name !== undefined && !codeFirst) {\n throw new Error(\n \"--name creates a code-first document model. Pass --code-first.\",\n );\n }\n if (codeFirst && name === undefined) {\n throw new Error(\n \"--code-first only chooses how --name creates a model. Existing models of both styles are discovered without it; drop --code-first. To convert a schema-first model, run ph migrate --document-model <dir>.\",\n );\n }\n const project = buildTsMorphProject(projectDir);\n if (name !== undefined) {\n handleMutuallyExclusiveOptions(\n {\n \"--name\": name,\n \"--dir\": dir,\n \"--all\": all || undefined,\n },\n \"generation mode\",\n );\n await scaffoldCodeFirstDocumentModel(\n modelGeneration,\n name,\n projectDir,\n project,\n );\n return;\n }\n if (all) {\n const { documentModels, unreadableDirs, codeFirstDocumentModels } =\n await modelGeneration.generateAllDocumentModels(project);\n await project.save();\n if (\n documentModels.length === 0 &&\n unreadableDirs.length === 0 &&\n codeFirstDocumentModels.length === 0\n ) {\n console.log(`No document models found in ${modelsDirOf(projectDir)}/.`);\n }\n for (const { name } of documentModels) {\n console.log(`Regenerated document model \"${name}\"`);\n }\n for (const { name } of codeFirstDocumentModels) {\n console.log(`Updated the exports of code-first document model \"${name}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped ${modelsDirOf(projectDir)}/${dirName}: it has no readable ${dirName}.json, and no index.ts in it exports a code-first model. Kept the manifest's document models.`,\n );\n }\n await warnSubgraphTypeConflicts(projectDir);\n return;\n }\n if (dir) {\n const modelsDir = modelsDirOf(projectDir);\n const dirName = resolveModuleDirName(\n projectDir,\n modelsDir,\n dir,\n \"my-document-model\",\n );\n const specPath = join(projectDir, modelsDir, dirName, `${dirName}.json`);\n if (!existsSync(specPath)) {\n throw new Error(`${modelsDir}/${dirName} has no ${dirName}.json.`);\n }\n const state = await loadDocumentModel(specPath);\n await modelGeneration.generateDocumentModel(state, project);\n await project.save();\n console.log(\n `Regenerated document model \"${state.name}\" in ${modelsDir}/${dirName}`,\n );\n await warnSubgraphTypeConflicts(projectDir);\n return;\n }\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAOA,eAAsB,+BACpB,YACA,MACA,YACA,SACA;CACA,MAAM,YAAY,KAAK,KAAK;CAC5B,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,YAAY,MAAM,sBAAsB,UAAU;CACxD,MAAM,eAAe,GAAG,UAAU,GAAG,UAAU,SAAS;CACxD,MAAM,aAAa,GAAG,YAAY,SAAS,EAAE;CAC7C,MAAM,gBAAgB,UAAU,UAAU;CAC1C,IAAI,WAAW,KAAK,YAAY,WAAW,aAAa,CAAC,GACvD,MAAM,IAAI,MACR,WAAW,cAAc,mEAC3B;CAGF,MAAM,SAAS,MAAM,WAAW,sBAC9B;EACE,MAAM;EACN;EACA,QAAQ;GAAE,MAAM;GAAW,SAAS;EAAK;CAC3C,GACA,OACF;CACA,KAAK,MAAM,QAAQ,OAAO,SACxB,QAAQ,IAAI,SAAS,MAAM;CAG7B,MAAM,WAAW,eACf;EACE;EACA,eAAe,CAAC,YAAY;EAC5B,UAAU;EACV;CACF,GACA,OACF;CACA,MAAM,QAAQ,KAAK;CACn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Q,KACN,WAAW,YAAY,UAAU,EAAE,GAAG,QAAQ,uBAAuB,QAAQ,8FAC/E;EAEF,MAAM,0BAA0B,UAAU;EAC1C;CACF;CACA,IAAI,KAAK;EACP,MAAM,YAAY,YAAY,UAAU;EACxC,MAAM,UAAU,qBACd,YACA,WACA,KACA,mBACF;EACA,MAAM,WAAW,KAAK,YAAY,WAAW,SAAS,GAAG,QAAQ,MAAM;EACvE,IAAI,CAAC,WAAW,QAAQ,GACtB,MAAM,IAAI,MAAM,GAAG,UAAU,GAAG,QAAQ,UAAU,QAAQ,OAAO;EAEnE,MAAM,QAAQ,MAAM,kBAAkB,QAAQ;EAC9C,MAAM,gBAAgB,sBAAsB,OAAO,OAAO;EAC1D,MAAM,QAAQ,KAAK;EACnB,QAAQ,IACN,+BAA+B,MAAM,KAAK,OAAO,UAAU,GAAG,SAChE;EACA,MAAM,0BAA0B,UAAU;EAC1C;CACF;CACA,QAAQ,IAAI,gDAAgD;AAC9D","debug_id":"20df4d67-b636-5349-964d-d9245a565596"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-subgraph-EQ2ZjMp9.mjs","sources":["../src/services/generate-subgraph.ts"],"sourcesContent":["import {\n detectFeatures,\n generateAllSubgraphs,\n generateSubgraph,\n generateSubgraphDir,\n syncFeatureDependencies,\n} from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n subgraphDirStyle,\n type SubgraphStyle,\n} from \"@powerhousedao/codegen/utils\";\nimport { kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateSubgraphArgs } from \"../types.js\";\nimport { installAddedDependencies } from \"../utils/install-added-dependencies.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { findSubgraphNameConflict } from \"../utils/subgraph-type-lint.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\n\nconst INDEX_FILE_EXPECTATION = {\n \"schema-first\": \"a class extending BaseSubgraph with a string literal `name`\",\n \"code-first\":\n \"a class extending Subgraph with a string literal `static subgraphName`\",\n} satisfies Record<SubgraphStyle, string>;\n\nasync function assertSubgraphNameFree(projectDir: string, name: string) {\n const conflict = await findSubgraphNameConflict(projectDir, name);\n if (conflict) throw new Error(conflict);\n}\n\n/** The notice for `--code-first` on an existing schema-first subgraph, which\n * is then left unchanged. */\nfunction codeFirstOnSchemaFirst(\n args: GenerateSubgraphArgs,\n projectDir: string,\n name: string,\n): string | undefined {\n if (!args.codeFirst) return undefined;\n const subgraphsDir = join(projectDir, \"subgraphs\");\n const dirName = kebabCase(name);\n if (\n !existsSync(join(subgraphsDir, dirName, \"index.ts\")) ||\n subgraphDirStyle(subgraphsDir, dirName) !== \"schema-first\"\n )\n return undefined;\n return `subgraphs/${dirName} is schema-first; --code-first only applies to new subgraphs. To convert it, run ph migrate --subgraph ${dirName}.`;\n}\n\nexport async function startGenerateSubgraph(\n args: GenerateSubgraphArgs,\n projectDir: string,\n) {\n const { name, dir, all, debug } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n const report: string[] = [];\n if (all) {\n const { subgraphNames, unreadableDirs } =\n await generateAllSubgraphs(project);\n if (subgraphNames.length === 0 && unreadableDirs.length === 0) {\n report.push(\"No subgraphs found in subgraphs/.\");\n }\n for (const subgraphName of subgraphNames) {\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION[subgraphDirStyle(join(projectDir, \"subgraphs\"), dirName)]}. Kept the manifest's subgraphs.`,\n );\n }\n } else if (name) {\n const notice = codeFirstOnSchemaFirst(args, projectDir, name);\n if (notice) {\n console.log(notice);\n return;\n }\n await assertSubgraphNameFree(projectDir, name);\n await generateSubgraph(name, project, { codeFirst: args.codeFirst });\n } else if (dir) {\n const dirName = resolveModuleDirName(\n projectDir,\n \"subgraphs\",\n dir,\n \"my-subgraph\",\n );\n if (!existsSync(join(projectDir, \"subgraphs\", dirName, \"index.ts\"))) {\n throw new Error(`subgraphs/${dirName} has no index.ts.`);\n }\n const { subgraphName, style } = await generateSubgraphDir(dirName, project);\n if (!subgraphName) {\n throw new Error(\n `Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION[style]}.`,\n );\n }\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n } else {\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n await warnSubgraphTypeConflicts(projectDir);\n const added = await syncFeatureDependencies(\n detectFeatures(projectDir),\n projectDir,\n );\n await installAddedDependencies(added, projectDir, args.skipInstall);\n}\n"],"names":["installAddedDependencies"],"mappings":";;;;;;;;;;;AAqBA,MAAM,yBAAyB;CAC7B,gBAAgB;CAChB,cACE;AACJ;AAEA,eAAe,uBAAuB,YAAoB,MAAc;CACtE,MAAM,WAAW,MAAM,yBAAyB,YAAY,IAAI;CAChE,IAAI,UAAU,MAAM,IAAI,MAAM,QAAQ;AACxC;;;AAIA,SAAS,uBACP,MACA,YACA,MACoB;CACpB,IAAI,CAAC,KAAK,WAAW,OAAO,KAAA;CAC5B,MAAM,eAAe,KAAK,YAAY,WAAW;CACjD,MAAM,UAAU,UAAU,IAAI;CAC9B,IACE,CAAC,WAAW,KAAK,cAAc,SAAS,UAAU,CAAC,KACnD,iBAAiB,cAAc,OAAO,MAAM,gBAE5C,OAAO,KAAA;CACT,OAAO,aAAa,QAAQ,yGAAyG,QAAQ;AAC/I;AAEA,eAAsB,sBACpB,MACA,YACA;CACA,MAAM,EAAE,MAAM,KAAK,KAAK,UAAU;CAClC,IAAI,OACF,QAAQ,IAAI,EAAE,KAAK,CAAC;CAEtB,MAAM,UAAU,oBAAoB,UAAU;CAC9C,MAAM,SAAmB,CAAC;CAC1B,IAAI,KAAK;EACP,MAAM,EAAE,eAAe,mBACrB,MA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":["../../../packages/host-core/dist/control-channel-eqvyUF03.d.mts","../../../packages/host-core/dist/compound-L62ALvYc.d.mts","../../../packages/host-core/dist/index.d.mts"],"mappings":";;;;;;;cA2Dc,qBAAqB;EACjC,UAAU;EACV,SAAS;EACT,OAAO;GACN;KACE,gBAAgB,cAAe;;;;;UC9C1B;EACR;EACA;;cAykEY,mCAAmC;EAC/C,MAAM;EACN,QAAQ;IACN,QAAQ;IACR,aAAa,YAAc;IAC3B,MAAM,YAAc;IACpB,MAAM,YAAc;IACpB,SAAS,YAAc,SAAW,mBAAqB,WAAa;MAClE,QAAQ;MACR,SAAS,YAAc;MACvB,OAAO,YAAc,mBAAqB,iBAAmB,SAAW;MACxE,QAAQ,YAAc,UAAY,WAAa;OAC9C;KACF;EACH,UAAU,UAAY,WAAa;IACjC,MAAM;IACN,QAAQ,YAAc;MACpB,QAAQ,YAAc;MACtB,aAAa,YAAc,YAAc;MACzC,MAAM,YAAc,YAAc;MAClC,SAAS,YAAc,YAAc,SAAW,mBAAqB,WAAa;QAChF,QAAQ;QACR,SAAS,YAAc;QACvB,OAAO,YAAc,mBAAqB,iBAAmB,SAAW;QACxE,QAAQ,YAAc,UAAY,WAAa;SAC9C;MACH,MAAM,YAAc;OACnB;IACH,QAAQ,YAAc,cAAgB;IACtC,SAAS,YAAc;MACrB,UAAU,YAAc,UAAY,WAAa;QAC/C,MAAM;UACJ;UACA;UACA;;QAEF,SAAS,YAAc;UACrB,MAAM;YACJ;YACA;YACA;YACA;;UAEF,SAAS,YAAc,gBAAgB,WAAa;UACpD,KAAK,YAAc;WAClB;QACH,WAAW,YAAc;UACvB,KAAK,YAAc;WAClB;QACH,UAAU,YAAc;UACtB,QAAQ,YAAc;UACtB,OAAO,YAAc,SAAW;UAChC,SAAS,YAAc;WACtB;QACH,QAAQ,YAAc;UACpB,KAAK,gBAAgB,mBAAqB,QAAU;UACpD,kBAAkB,YAAc;UAChC,SAAS,YAAc,mBAAqB,mBAAqB;YAC/D,UAAU,YAA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EAEA;EACA;EACA;;EAEA;;EAEA,WAAW;;EAEX;EACA;;;;;;;;;;UA8MQ,aAAa,IAAI;EACzB,SAAS;;EAET,OAAO;;EAEP,YAAY;;;;;;QCx+DN;;;YAGI;;YAEA;;QA0CJ;YACI;IACR;MACE,MAAM,aAAe;MACrB,SAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-CcZT9zT9.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 ensureVetra,\n restartVetra,\n currentPhCliRunVetraCommand,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launcher.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to {@link currentPhCliRunVetraCommand}. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's dev stack (its Switchboard and Connect, what `ph dev` runs) and wait until it is ready. \" +\n \"Use it after a change the stack reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Connect restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** 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:\n this.options.vetraCommand ?? currentPhCliRunVetraCommand(projectDir),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n 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 run dev` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const 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}\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Y;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":"3310b97c-72c7-576c-91fb-40abfcad6119"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-document-models-X_mVTljj.mjs","sources":["../src/services/migrate-document-models.ts"],"sourcesContent":["import {\n assertDocumentModelBarrelsWritable,\n type DocumentModelMigration,\n type DocumentModelMigrationFile,\n type DocumentModelMigrationReference,\n migrateDocumentModel,\n regenerateDocumentModelBarrels,\n} from \"@powerhousedao/codegen\";\nimport { documentModelsDirOf } from \"@powerhousedao/codegen/utils\";\nimport type {\n DocumentModelDefinition,\n DocumentModelModuleDefinition,\n DocumentModelOperationDefinition,\n DocumentModelSpecificationDefinition,\n StateDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n discoverDocumentModelDirectories,\n inspectProjectDefinitions,\n} from \"document-model/tooling\";\nimport { statSync } from \"node:fs\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { outdatedDependency } from \"./installed-version.js\";\nimport { unifiedDiff } from \"./migrate-subgraphs.js\";\nimport { readProjectDefinitions } from \"./model/project.js\";\nimport { projectModuleReferences } from \"./project-module-references.js\";\nimport {\n assertChangesWritable,\n errorText,\n type FileBackup,\n readProjectFiles,\n restoreChanges,\n toPosix,\n writeChanges,\n} from \"./project-files.js\";\n\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?|json|graphql)$/;\nexport type MigrateDocumentModelsOptions = {\n readonly projectDir: string;\n /** Model directories to convert; empty converts every schema-first one. */\n readonly dirs: readonly string[];\n readonly dryRun: boolean;\n /** Renames a type named like a scalar instead of refusing its model. */\n readonly renameConflictingTypes?: boolean;\n readonly out?: (text: string) => void;\n};\n\ntype Definitions = ReadonlyMap<number, unknown>;\n\n/**\n * `ph migrate --document-models`: converts schema-first document models into\n * code-first ones. Each converted model is loaded again as `ph model inspect`\n * loads it, and every version must keep the definition it had: the same\n * state, operations, inputs and errors. Otherwise its files are restored.\n * Returns the exit code: 0 when every requested model converted or was\n * already code-first, 1 otherwise.\n */\nexport async function migrateDocumentModels(\n options: MigrateDocumentModelsOptions,\n): Promise<0 | 1> {\n const out =\n options.out ?? ((text: string) => void process.stdout.write(text));\n const { projectDir } = options;\n let resolved: { readonly path: string };\n try {\n resolved = documentModelsDirOf(projectDir);\n } catch (error) {\n out(`${errorText(error)}\\n`);\n return 1;\n }\n const modelsDir = toPosix(relative(projectDir, resolved.path));\n const directories = new Map(\n discoverDocumentModelDirectories(projectDir, resolved.path).directories.map(\n (directory) => [directory.name, directory.kind] as const,\n ),\n );\n let failed = false;\n const requested: string[] = [];\n if (options.dirs.length === 0) {\n for (const [name, kind] of directories) {\n if (kind === \"stored\") requested.push(name);\n }\n }\n for (const dir of options.dirs) {\n const name = basename(dir.replace(/[\\\\/]+$/, \"\"));\n // A path names a directory of the models directory, not any directory.\n if (\n /[\\\\/]/.test(dir.replace(/[\\\\/]+$/, \"\")) &&\n resolve(projectDir, dir, \"..\") !== resolved.path\n ) {\n out(\n `${dir}: not a directory of ${modelsDir}/. Name a model directory, such as ${modelsDir}/${name}.\\n`,\n );\n failed = true;\n continue;\n }\n if (!requested.includes(name)) requested.push(name);\n }\n if (requested.length === 0 && !failed) {\n out(\"No schema-first document models to convert.\\n\");\n return 0;\n }\n\n const pending: string[] = [];\n for (const dirName of requested) {\n const label = `${modelsDir}/${dirName}`;\n const kind = directories.get(dirName);\n if (kind === undefined || kind === \"none\" || kind === \"invalid\") {\n out(\n `${label}: not found. Name a directory of ${modelsDir}/ that holds a document model.\\n`,\n );\n failed = true;\n } else if (kind === \"module\") {\n out(`${label}: already code-first\\n`);\n } else if (kind === \"generated\") {\n out(\n `${label}: not converted. It has generated code but no ${dirName}.json, so its specification cannot be read. Restore ${dirName}.json, then migrate again.\\n`,\n );\n failed = true;\n } else {\n pending.push(dirName);\n }\n }\n if (pending.length === 0) return failed ? 1 : 0;\n // The barrels are regenerated after the models are written, so a barrel\n // codegen would refuse to rewrite stops the run before anything changes.\n try {\n assertChangesWritable(projectDir, [\n { path: \"document-models/index.ts\" },\n { path: \"document-models/document-models.ts\" },\n { path: \"document-models/upgrade-manifests.ts\" },\n { path: \"powerhouse.manifest.json\" },\n ]);\n assertDocumentModelBarrelsWritable(projectDir);\n } catch (error) {\n out(`No document model was converted. ${errorText(error)}\\n`);\n return 1;\n }\n\n let moduleReferences: readonly DocumentModelMigrationReference[];\n try {\n moduleReferences = projectModuleReferences(projectDir).map((reference) => ({\n file: reference.file,\n specifier: reference.specifier,\n targets: reference.targets\n .filter((target) =>\n statSync(resolve(projectDir, target.path), {\n throwIfNoEntry: false,\n })?.isFile(),\n )\n .map((target) => target.path),\n }));\n } catch (error) {\n out(`No document model was converted. ${errorText(error)}\\n`);\n return 1;\n }\n const outdated = outdatedDependency(projectDir, \"document-model\");\n const run: ModelRun = {\n projectDir,\n modelsDir,\n pending,\n renameConflictingTypes: options.renameConflictingTypes ?? false,\n moduleReferences,\n out,\n };\n if (options.dryRun) {\n if (outdated !== undefined) {\n out(`Note: ${outdated} Until then, a real run converts nothing.\\n`);\n }\n return (await previewModels(run)) || failed ? 1 : 0;\n }\n if (outdated !== undefined) {\n out(`No document model was converted. ${outdated}\\n`);\n return 1;\n }\n return (await convertModels(run)) || failed ? 1 : 0;\n}\n\ntype ModelRun = {\n readonly moduleReferences: readonly DocumentModelMigrationReference[];\n readonly projectDir: string;\n readonly modelsDir: string;\n readonly pending: readonly string[];\n readonly renameConflictingTypes: boolean;\n readonly out: (text: string) => void;\n};\n\n/** `--dry-run`: prints what each conversion would write. Returns whether one was refused. */\nasync function previewModels(run: ModelRun): Promise<boolean> {\n const { out } = run;\n let files = readSourceTexts(run.projectDir);\n let refused = false;\n const notes = new Set<string>();\n for (const dirName of run.pending) {\n const label = `${run.modelsDir}/${dirName}`;\n let migration: DocumentModelMigration;\n try {\n migration = await migrateDocumentModel({\n documentModelsDir: run.modelsDir,\n dirName,\n files,\n moduleReferences: run.moduleReferences,\n renameConflictingTypes: run.renameConflictingTypes,\n });\n if (migration.kind === \"converted\") {\n assertChangesWritable(run.projectDir, migration.files);\n }\n } catch (error) {\n out(\n `${label}: would not convert. The conversion failed unexpectedly: ${errorText(error)}\\n`,\n );\n refused = true;\n continue;\n }\n if (migration.kind !== \"converted\") {\n out(`${label}: ${refusalText(migration)}\\n`);\n refused = true;\n continue;\n }\n out(\n `${label}: would convert ${migration.documentType} (versions ${migration.versions.join(\", \")}) to code-first, if the converted model keeps its definition when loaded\\n`,\n );\n for (const file of migration.files) out(fileDiff(file));\n for (const note of migration.notes) notes.add(note);\n files = applied(files, migration.files);\n }\n for (const note of notes) out(`Note: ${note}\\n`);\n return refused;\n}\n\n/**\n * Converts each model, writes it, loads it again and keeps it only when every\n * version has its stored definition; then regenerates the barrels. Returns\n * whether a model was not converted.\n */\nasync function convertModels(run: ModelRun): Promise<boolean> {\n const { projectDir, out } = run;\n let files = readSourceTexts(projectDir);\n const before = await storedDefinitions(\n projectDir,\n run.modelsDir,\n run.pending,\n files,\n );\n let failed = false;\n const converted = new Set<string>();\n const notes = new Set<string>();\n for (const dirName of run.pending) {\n const label = `${run.modelsDir}/${dirName}`;\n let outcome: ModelOutcome;\n try {\n outcome = await convertModel(run, dirName, files, before);\n } catch (error) {\n outcome = {\n ok: false,\n text: `not converted; its files are unchanged. The conversion failed unexpectedly: ${errorText(error)}`,\n };\n }\n if (!outcome.ok) {\n out(`${label}: ${outcome.text}\\n`);\n failed = true;\n continue;\n }\n const { migration } = outcome;\n files = applied(files, migration.files);\n out(\n `${label}: converted ${migration.documentType} (versions ${migration.versions.join(\", \")}) to code-first; every version keeps its definition\\n`,\n );\n for (const note of migration.notes) notes.add(note);\n converted.add(dirName);\n }\n for (const note of notes) out(`Note: ${note}\\n`);\n if (converted.size > 0) {\n try {\n const changed = await regenerateDocumentModelBarrels(\n projectDir,\n converted,\n );\n if (changed.length > 0) {\n out(`Regenerated ${changed.join(\", \")}.\\n`);\n }\n } catch (error) {\n out(\n `The converted models are written, but the document-models barrels could not be regenerated: ${errorText(error)}\\nFix that, then run ph generate.\\n`,\n );\n failed = true;\n }\n }\n return failed;\n}\n\ntype ModelOutcome =\n | {\n readonly ok: true;\n readonly migration: Extract<\n DocumentModelMigration,\n { kind: \"converted\" }\n >;\n }\n | { readonly ok: false; readonly text: string };\n\n/** Converts, writes and verifies one model, restoring its files when it fails. */\nasync function convertModel(\n run: ModelRun,\n dirName: string,\n files: ReadonlyMap<string, string>,\n before: StoredDefinitions,\n): Promise<ModelOutcome> {\n const migration = await migrateDocumentModel({\n documentModelsDir: run.modelsDir,\n dirName,\n files,\n moduleReferences: run.moduleReferences,\n renameConflictingTypes: run.renameConflictingTypes,\n });\n if (migration.kind !== \"converted\") {\n return { ok: false, text: refusalText(migration) };\n }\n const stored = before.definitions.get(dirName);\n const unread = migration.versions.filter(\n (version) => stored?.has(version) !== true,\n );\n if (stored === undefined || unread.length > 0) {\n return {\n ok: false,\n text: `not converted. Version ${unread.join(\", \")} of its stored definition could not be read, so the conversion could not be checked. Run ph model check to see why.`,\n };\n }\n let backup: FileBackup;\n try {\n backup = writeChanges(run.projectDir, migration.files);\n } catch (error) {\n return {\n ok: false,\n text: `not converted; its files are restored. Writing them failed: ${errorText(error)}`,\n };\n }\n let verification: Awaited<ReturnType<typeof verify>>;\n try {\n verification = await verify(\n run.projectDir,\n migration.documentType,\n renameTypes(stored, migration.renamedTypes),\n before.known,\n );\n } catch (error) {\n verification = {\n ok: false,\n reason: `Checking the converted model failed: ${errorText(error)}`,\n };\n }\n if (!verification.ok) {\n restoreChanges(run.projectDir, backup);\n return {\n ok: false,\n text: `not converted; its files are restored. ${verification.reason}`,\n };\n }\n return { ok: true, migration };\n}\n\n/** The package's source files as text, by project-relative POSIX path. */\nfunction readSourceTexts(projectDir: string): Map<string, string> {\n return new Map(\n [...readProjectFiles(projectDir, SOURCE_FILE)].map(([path, bytes]) => [\n path,\n bytes.toString(\"utf8\"),\n ]),\n );\n}\n\nfunction applied(\n files: ReadonlyMap<string, string>,\n changes: readonly DocumentModelMigrationFile[],\n): Map<string, string> {\n const next = new Map(files);\n for (const file of changes) {\n if (file.after === null) next.delete(file.path);\n else next.set(file.path, file.after);\n }\n return next;\n}\n\ntype StoredDefinitions = {\n readonly definitions: ReadonlyMap<string, Definitions>;\n /** The errors the project reported before anything was written. */\n readonly known: ReadonlySet<string>;\n};\n\n/** The stored versions of each model, read before anything is written. */\nasync function storedDefinitions(\n projectDir: string,\n modelsDir: string,\n dirNames: readonly string[],\n files: ReadonlyMap<string, string>,\n): Promise<StoredDefinitions> {\n const wanted = dirNames.flatMap((dirName) => {\n const text = files.get(`${modelsDir}/${dirName}/${dirName}.json`);\n if (text === undefined) return [];\n try {\n const stored = JSON.parse(text) as {\n id: string;\n specifications: { version: number }[];\n };\n return [\n {\n dirName,\n documentType: stored.id,\n versions: stored.specifications.map(({ version }) => version),\n },\n ];\n } catch {\n // The migration refuses a specification that is not JSON, and says why.\n return [];\n }\n });\n return await readProjectDefinitions(projectDir, (project) => {\n const result = new Map<string, Definitions>();\n const known = new Set<string>();\n for (const { dirName, documentType, versions } of wanted) {\n const definitions = new Map<number, unknown>();\n for (const version of versions) {\n const report = inspectProjectDefinitions(project, {\n selection: { documentType, version },\n });\n if (\"definition\" in report) definitions.set(version, report.definition);\n for (const message of errorMessages(report.diagnostics)) {\n known.add(message);\n }\n }\n result.set(dirName, definitions);\n }\n return { definitions: result, known };\n });\n}\n\nfunction errorMessages(\n diagnostics: readonly {\n readonly severity: string;\n readonly message: string;\n readonly repair?: string;\n }[],\n): string[] {\n return diagnostics\n .filter(({ severity }) => severity === \"error\")\n .map(({ message, repair }) => `${message} ${repair ?? \"\"}`.trim());\n}\n\ntype Verification =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * The stored definitions with the types the conversion renamed off a\n * scalar's name renamed too, so the comparison expects the new names. The\n * stored definition also lists the scalar the type's name collided with,\n * which the converted model no longer names.\n */\nfunction renameTypes(\n definitions: Definitions,\n renamed: readonly { version: number; from: string; to: string }[],\n): Definitions {\n if (renamed.length === 0) return definitions;\n const result = new Map<number, unknown>();\n for (const [version, definition] of definitions) {\n const names = new Map(\n renamed\n .filter((entry) => entry.version === version)\n .map(({ from, to }) => [from, to] as const),\n );\n // A type is named by `name` in its definition and in every reference;\n // unions and interfaces list members and implemented types by name.\n const walk = (value: unknown, key?: string): unknown => {\n if (key === \"scalars\" && Array.isArray(value)) {\n return value.filter(\n (scalar) =>\n !(\n isRecord(scalar) &&\n typeof scalar.name === \"string\" &&\n names.has(scalar.name)\n ),\n );\n }\n if (Array.isArray(value)) {\n return value.map((item) =>\n (key === \"members\" || key === \"implements\") &&\n typeof item === \"string\"\n ? (names.get(item) ?? item)\n : walk(item),\n );\n }\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value).map(([entryKey, entry]) => [\n entryKey,\n entryKey === \"name\" &&\n typeof entry === \"string\" &&\n typeof value.kind === \"string\"\n ? (names.get(entry) ?? entry)\n : walk(entry, entryKey),\n ]),\n );\n };\n result.set(version, walk(definition));\n }\n return result;\n}\n\n/** Loads the converted model and compares each version with its stored definition. */\nasync function verify(\n projectDir: string,\n documentType: string,\n expected: Definitions,\n known: ReadonlySet<string>,\n): Promise<Verification> {\n let actual: ReadonlyMap<number, unknown>;\n let problems: readonly string[];\n try {\n [actual, problems] = await readProjectDefinitions(projectDir, (project) => {\n const definitions = new Map<number, unknown>();\n const errors: string[] = [];\n for (const version of expected.keys()) {\n const report = inspectProjectDefinitions(project, {\n selection: { documentType, version },\n });\n if (\"definition\" in report) definitions.set(version, report.definition);\n for (const message of errorMessages(report.diagnostics)) {\n // Errors the project had before, such as another model's, are not this conversion's.\n if (!known.has(message)) errors.push(message);\n }\n }\n return [definitions, errors] as const;\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n reason: `The converted model does not load: ${message.replaceAll(projectDir, \".\")}`,\n };\n }\n if (problems.length > 0) {\n return {\n ok: false,\n reason: `The converted model does not pass ph model check:\\n${[...new Set(problems)].map((problem) => ` ${problem}`).join(\"\\n\")}`,\n };\n }\n for (const [version, stored] of expected) {\n const converted = actual.get(version);\n if (converted === undefined) {\n return {\n ok: false,\n reason: `The converted model exports no version ${version} of ${documentType}.`,\n };\n }\n const differences = definitionDifferences(stored, converted);\n if (differences.length > 0) {\n return {\n ok: false,\n reason: `Version ${version} of the converted model has a different definition:\\n${differences\n .slice(0, 20)\n .map((line) => ` ${line}`)\n .join(\"\\n\")}`,\n };\n }\n }\n return { ok: true };\n}\n\n/**\n * What a stored definition and the code-first one differ in. IDs, the\n * stored names of modules and operations, the reducer and template text, and\n * the GraphQL text a schema-first model keeps derive from the authoring\n * style, so they are not compared. The model, every named type (operation\n * inputs included), the state roots and initial values, and each operation's\n * key, action type, scope, input and errors are.\n */\nexport function definitionDifferences(\n stored: unknown,\n converted: unknown,\n): string[] {\n const differences: string[] = [];\n const walk = (left: unknown, right: unknown, path: string) => {\n if (differences.length >= 50) return;\n if (Array.isArray(left) && Array.isArray(right)) {\n if (left.length !== right.length) {\n differences.push(\n `${path}: ${left.length} entries stored, ${right.length} converted`,\n );\n }\n for (\n let index = 0;\n index < Math.min(left.length, right.length);\n index++\n ) {\n walk(left[index], right[index], `${path}[${index}]`);\n }\n return;\n }\n if (isRecord(left) && isRecord(right)) {\n for (const key of new Set([\n ...Object.keys(left),\n ...Object.keys(right),\n ])) {\n walk(left[key], right[key], path === \"\" ? key : `${path}.${key}`);\n }\n return;\n }\n if (JSON.stringify(left) !== JSON.stringify(right)) {\n differences.push(\n `${path}: stored ${JSON.stringify(left)}, converted ${JSON.stringify(right)}`,\n );\n }\n };\n walk(canonical(stored), canonical(converted), \"\");\n return differences;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The records of a list, or none when it is not one. */\nfunction records(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\n/** Empty text and null both mean \"none\" in a stored model. */\nconst text = (value: unknown): unknown => (value === \"\" ? null : value);\n\n/** Members whose empty text means none, as the stored format writes it. */\nconst TEXT_KEYS = new Set([\"description\", \"deprecated\", \"template\"]);\n\n/** `value` with empty text read as none, and without `keys`, at any depth. */\nfunction normalized(value: unknown, keys: readonly string[] = []): unknown {\n if (Array.isArray(value)) return value.map((item) => normalized(item, keys));\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => !keys.includes(key))\n .map(([key, entry]) => [\n key,\n TEXT_KEYS.has(key) ? text(entry) : normalized(entry, keys),\n ]),\n );\n}\n\n/**\n * How one member of a definition is compared: `ignore` leaves it out, a\n * function maps it to what is compared. The tables are exhaustive over the\n * definition types, so a member added to them must be classified here; a\n * member the loaded definition has and a table lacks is compared as is.\n */\ntype Rule = \"ignore\" | ((value: unknown) => unknown);\ntype Rules<T> = { readonly [Key in keyof Required<T>]: Rule };\n\nconst same = (value: unknown) => normalized(value);\nconst exampleValues = (value: unknown) =>\n records(value).map((example) => example.value);\n\nfunction compared<T>(value: unknown, rules: Rules<T>): unknown {\n if (!isRecord(value)) return value;\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const rule = (rules as Readonly<Record<string, Rule | undefined>>)[key];\n if (rule === \"ignore\") continue;\n result[key] = (rule ?? same)(entry);\n }\n return result;\n}\n\nconst STATE_RULES: Rules<StateDefinition> = {\n root: same,\n initialValue: (value) => value ?? {},\n examples: exampleValues,\n unknownKeys: same,\n // The GraphQL and JSON text the state is materialized from.\n materialized: \"ignore\",\n};\n\nconst OPERATION_RULES: Rules<DocumentModelOperationDefinition> = {\n id: \"ignore\",\n // The stored operation name; the key and action type derive from it.\n name: \"ignore\",\n key: same,\n description: text,\n actionType: same,\n creatorKey: same,\n scope: same,\n // Compared among the specification's types.\n input: (value) => (isRecord(value) ? value.name : null),\n errors: (value) => normalized(value, [\"id\", \"key\"]),\n examples: exampleValues,\n template: \"ignore\",\n reducer: \"ignore\",\n};\n\nconst MODULE_RULES: Rules<DocumentModelModuleDefinition> = {\n id: \"ignore\",\n // The stored module name; the key derives from it.\n name: \"ignore\",\n key: same,\n description: text,\n operations: (value) =>\n records(value).map((operation) => compared(operation, OPERATION_RULES)),\n};\n\n/** The named types of a specification, operation inputs included, by name. */\nfunction namedTypes(specification: Record<string, unknown>): unknown {\n const types = new Map<string, unknown>();\n const add = (type: unknown) => {\n if (isRecord(type) && typeof type.name === \"string\") {\n types.set(type.name, normalized(type, [\"key\"]));\n }\n };\n for (const type of records(specification.types)) add(type);\n for (const module of records(specification.modules)) {\n for (const operation of records(module.operations)) add(operation.input);\n }\n return Object.fromEntries(\n [...types].sort(([left], [right]) => left.localeCompare(right)),\n );\n}\n\nconst SPECIFICATION_RULES: Rules<DocumentModelSpecificationDefinition> = {\n version: same,\n changeLog: same,\n scalars: same,\n // The GraphQL text a schema-first model keeps.\n graphQLCompatibility: \"ignore\",\n types: \"ignore\",\n state: (value) =>\n isRecord(value)\n ? {\n global: compared(value.global, STATE_RULES),\n local: compared(value.local, STATE_RULES),\n }\n : value,\n modules: (value) =>\n records(value).map((module) => compared(module, MODULE_RULES)),\n};\n\nconst DEFINITION_RULES: Rules<DocumentModelDefinition> = {\n kind: same,\n formatVersion: same,\n // How identities and serialization derive differs by authoring style.\n compatibility: (value) =>\n isRecord(value) ? { scalarCoercion: value.scalarCoercion } : value,\n model: same,\n specifications: (value) =>\n records(value).map((specification) => {\n const result = compared(specification, SPECIFICATION_RULES);\n return isRecord(result)\n ? { ...result, types: namedTypes(specification) }\n : result;\n }),\n};\n\n/** The parts of a definition both authoring styles must agree on. */\nfunction canonical(definition: unknown): unknown {\n return compared(definition, DEFINITION_RULES);\n}\n\nfunction fileDiff(file: DocumentModelMigrationFile): string {\n if (file.after === null)\n return `--- a/${file.path}\\n+++ /dev/null\\n(deleted)\\n`;\n return unifiedDiff({\n path: file.path,\n before: file.before,\n after: file.after,\n });\n}\n\nfunction refusalText(\n migration: Extract<DocumentModelMigration, { kind: \"refused\" }>,\n): string {\n return `not converted\\n${migration.refusals\n .map(\n ({ file, line, reason, repair }) =>\n ` ${file}${line === undefined ? \"\" : `:${line}`}: ${reason}\\n ${repair}`,\n )\n .join(\"\\n\")}`;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAoCA,MAAM,cAAc;;;;;;;;;AAqBpB,eAAsB,sBACpB,SACgB;CAChB,MAAM,MACJ,QAAQ,SAAS,SAAiB,KAAK,QAAQ,OAAO,MAAM,IAAI;CAClE,MAAM,EAAE,eAAe;CACvB,IAAI;CACJ,IAAI;EACF,WAAW,oBAAoB,UAAU;CAC3C,SAAS,OAAO;EACd,IAAI,GAAG,UAAU,KAAK,E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;CAEf,gBAAgB,UACd,SAAS,KAAK,IAAI,EAAE,gBAAgB,MAAM,eAAe,IAAI;CAC/D,OAAO;CACP,iBAAiB,UACf,QAAQ,KAAK,CAAC,CAAC,KAAK,kBAAkB;EACpC,MAAM,SAAS,SAAS,eAAe,mBAAmB;EAC1D,OAAO,SAAS,MAAM,IAClB;GAAE,GAAG;GAAQ,OAAO,WAAW,aAAa;EAAE,IAC9C;CACN,CAAC;AACL;;AAGA,SAAS,UAAU,YAA8B;CAC/C,OAAO,SAAS,YAAY,gBAAgB;AAC9C;AAEA,SAAS,SAAS,MAA0C;CAC1D,IAAI,KAAK,UAAU,MACjB,OAAO,SAAS,KAAK,KAAK;CAC5B,OAAO,YAAY;EACjB,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,OAAO,KAAK;CACd,CAAC;AACH;AAEA,SAAS,YACP,WACQ;CACR,OAAO,kBAAkB,UAAU,SAChC,KACE,EAAE,MAAM,MAAM,QAAQ,aACrB,KAAK,OAAO,SAAS,KAAA,IAAY,KAAK,IAAI,OAAO,IAAI,OAAO,QAAQ,QACxE,CAAC,CACA,KAAK,IAAI;AACd","debug_id":"6e348e7c-4716-5f2b-9fc1-bdaa5d327671"}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { t as migrateSubgraphs } from "./migrate-subgraphs-Ffwwm7Oy.mjs";
|
|
2
|
-
export { migrateSubgraphs };
|
|
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]="4f68f50c-fc0e-5a47-bcfd-21263292763d")}catch(e){}}();
|
|
4
|
-
//# debugId=4f68f50c-fc0e-5a47-bcfd-21263292763d
|