@powerhousedao/ph-run 6.2.3-dev.93 → 6.2.3-dev.95
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/{connect-serve-0fIQ7xCs.mjs → connect-serve-1WAi0KJL.mjs} +15 -4
- package/dist/connect-serve-1WAi0KJL.mjs.map +1 -0
- package/dist/{connect-serve-B2u6WAdw.d.mts → connect-serve-COWXf_41.d.mts} +4 -2
- package/dist/{connect-serve-B2u6WAdw.d.mts.map → connect-serve-COWXf_41.d.mts.map} +1 -1
- package/dist/{member-config-BcEWRVq4.mjs → member-config-Bs3yOT6y.mjs} +10 -4
- package/dist/{member-config-BcEWRVq4.mjs.map → member-config-Bs3yOT6y.mjs.map} +1 -1
- package/dist/runners/connect.d.mts +3 -1
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +5 -3
- package/dist/runners/connect.mjs.map +1 -1
- package/dist/runners/member-config.d.mts +2 -0
- package/dist/runners/member-config.d.mts.map +1 -1
- package/dist/runners/member-config.mjs +4 -4
- package/dist/runners/switchboard.d.mts.map +1 -1
- package/dist/runners/switchboard.mjs +10 -3
- package/dist/runners/switchboard.mjs.map +1 -1
- package/dist/services/connect-serve.d.mts +2 -2
- package/dist/services/connect-serve.mjs +4 -4
- package/dist/services/connect-server.d.mts +1 -1
- package/dist/services/connect-server.d.mts.map +1 -1
- package/dist/services/connect-server.mjs +4 -3
- package/dist/services/connect-server.mjs.map +1 -1
- package/package.json +7 -7
- package/dist/connect-serve-0fIQ7xCs.mjs.map +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="152aac10-515c-55ef-9f11-64c6a3fbff77")}catch(e){}}();
|
|
3
|
+
import { DEFAULT_CONNECT_OUTDIR } from "@powerhousedao/shared/clis";
|
|
3
4
|
import { isHtmlNavigation, isSwitchboardProxyPath } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { existsSync, readFileSync } from "node:fs";
|
|
@@ -178,13 +179,23 @@ function precompressedAssets(outDir, base = "/") {
|
|
|
178
179
|
});
|
|
179
180
|
};
|
|
180
181
|
}
|
|
182
|
+
/** Throws, naming the missing file and the build, when `outDirAbs` holds no build. */
|
|
183
|
+
function assertConnectBuild(outDirArg, outDirAbs, dirname) {
|
|
184
|
+
const file = path.join(outDirAbs, "index.html");
|
|
185
|
+
if (existsSync(file)) return;
|
|
186
|
+
const relative = path.relative(dirname, file);
|
|
187
|
+
const shown = (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) ? file : relative).split(path.sep).join("/");
|
|
188
|
+
const project = path.resolve(outDirAbs, "../../..");
|
|
189
|
+
const build = path.resolve(project, DEFAULT_CONNECT_OUTDIR) !== outDirAbs ? `\`ph connect build --outDir ${JSON.stringify(outDirArg)}\`` : project === path.resolve(dirname) ? "`ph connect build`" : `\`ph connect build\` in ${project.split(path.sep).join("/")}`;
|
|
190
|
+
throw new Error(`No Connect build to serve: ${shown} is missing. Build it first with ${build}, or \`ph run <host> build\` for a host's Connect.`);
|
|
191
|
+
}
|
|
181
192
|
/** The served base: `--base`, else what the dist or the project was built with. */
|
|
182
193
|
function connectBaseOf(args, outDirAbs, dirname) {
|
|
183
194
|
const sourceBasePath = getConfig(path.join(dirname, "powerhouse.config.json")).connect?.app?.basePath;
|
|
184
195
|
return resolvePreviewBase(args.connectBasePath, outDirAbs) ?? (sourceBasePath ? normalizeBasePath(sourceBasePath) : "/");
|
|
185
196
|
}
|
|
186
197
|
//#endregion
|
|
187
|
-
export {
|
|
198
|
+
export { isProxiedRequest as a, precompressedAssets as c, serveOverrideStep as d, shellSwapFor as f, connectBaseOf as i, previewCacheControl as l, assertConnectBuild as n, overrideFromEnv as o, stripBase as p, cacheHeaders as r, patchCspScriptSrc as s, PRECOMPRESS_EXTENSIONS as t, resolvePreviewBase as u };
|
|
188
199
|
|
|
189
|
-
//# sourceMappingURL=connect-serve-
|
|
190
|
-
//# debugId=
|
|
200
|
+
//# sourceMappingURL=connect-serve-1WAi0KJL.mjs.map
|
|
201
|
+
//# debugId=152aac10-515c-55ef-9f11-64c6a3fbff77
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-serve-1WAi0KJL.mjs","sources":["../src/services/connect-serve.ts"],"sourcesContent":["import { getConfig } from \"@powerhousedao/config/node\";\nimport {\n DEFAULT_CONNECT_OUTDIR,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { deepMerge, normalizeBasePath } from \"@powerhousedao/shared/connect\";\nimport {\n APP_SHELLS_FILE,\n appShellVariant,\n appShellVariantOf,\n readShellPluginsIn,\n swapAppShell,\n withShellAppName,\n type AppShells,\n} from \"@powerhousedao/shared/connect/app-shell\";\nimport {\n isHtmlNavigation,\n isSwitchboardProxyPath,\n} from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport path from \"node:path\";\nimport sirv from \"sirv\";\nimport type { ConnectPreviewArgs } from \"./classic-args.js\";\n\n/**\n * Runtime shaping for a served (built) Connect, desktop shape: the compound\n * projects the live switchboard's drive into the connect member's config, and\n * this override makes the STATIC dist serve it — the built\n * powerhouse.config.json is baked, so without this the drive injection never\n * reaches the SPA. `cspRegistrySync` additionally patches the baked CSP's\n * script-src with the runtime registry (the build bakes the CSP for the\n * registry it was built against; setting the registry at run time breaks that\n * coupling and every package import gets blocked otherwise).\n */\nexport interface ConnectServeOverride {\n connect?: PHConnectRuntimeConfig;\n cspRegistrySync?: boolean;\n /** Overrides the baked top-level packageRegistryUrl in the served config. */\n packageRegistryUrl?: string;\n}\n\n/**\n * The env contract a supervisor can drive the preview with — the same\n * variables the Docker entrypoint and clint's service manager already speak:\n * PH_CONNECT_DEFAULT_DRIVES_URL (comma-separated drive urls, injected into\n * drives.defaultDrives), PH_CONNECT_DRIVES_PRESERVE_STRATEGY, and\n * PH_CONNECT_PACKAGES_REGISTRY (runtime registry: served config + baked-CSP\n * patch). Lets `ph connect preview` replace hand-rolled static servers\n * (clint's connect-server, the ph-win sidecar) without losing injection.\n */\nexport function overrideFromEnv(\n env: Record<string, string | undefined> = process.env,\n): ConnectServeOverride | undefined {\n const drivesUrl = env.PH_CONNECT_DEFAULT_DRIVES_URL;\n const registry = env.PH_CONNECT_PACKAGES_REGISTRY;\n if (!drivesUrl && !registry) return undefined;\n const override: ConnectServeOverride = {};\n if (drivesUrl) {\n override.connect = {\n drives: {\n defaultDrives: drivesUrl\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null })),\n preserveStrategy:\n env.PH_CONNECT_DRIVES_PRESERVE_STRATEGY ?? \"preserve-all\",\n },\n } as PHConnectRuntimeConfig;\n }\n if (registry) {\n override.packageRegistryUrl = registry;\n override.cspRegistrySync = true;\n }\n return override;\n}\n\nfunction mergedConfigBody(\n outDir: string,\n override: ConnectServeOverride,\n): string {\n const file = path.join(outDir, \"powerhouse.config.json\");\n const baked = existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>)\n : {};\n const connect = override.connect\n ? deepMerge(\n (baked.connect ?? {}) as PHConnectRuntimeConfig,\n override.connect,\n )\n : baked.connect;\n return JSON.stringify({\n ...baked,\n connect,\n ...(override.packageRegistryUrl\n ? { packageRegistryUrl: override.packageRegistryUrl }\n : {}),\n });\n}\n\n/**\n * Append the registry origin to the baked CSP's script-src. The attribute\n * value is HTML-escaped (every CSP keyword is `'`-quoted, which contains a\n * semicolon), so decode before touching directives and re-escape after —\n * ported from the ph-win-desktop sidecar, which this path replaces.\n */\nexport function patchCspScriptSrc(html: string, registryUrl: string): string {\n return html.replace(\n /(<meta\\s+http-equiv=\"Content-Security-Policy\"\\s+content=\")([^\"]*)(\")/i,\n (_match, open: string, escaped: string, close: string) => {\n const policy = escaped.replace(/&/g, \"&\").replace(/'/g, \"'\");\n if (policy.includes(registryUrl)) return open + escaped + close;\n const patched = policy.replace(\n /script-src\\s+([^;]*)/i,\n (_directive, sources: string) =>\n `script-src ${sources.trim()} ${registryUrl}`,\n );\n const reEscaped = patched.replace(/&/g, \"&\").replace(/'/g, \"'\");\n return open + reEscaped + close;\n },\n );\n}\n\n// The serve base: an explicit `--base`, else the basePath the dist was built with.\nexport function resolvePreviewBase(\n argBase: string | undefined,\n outDirAbs: string,\n): string | undefined {\n if (argBase && argBase !== \"/\") return normalizeBasePath(argBase);\n try {\n const built = JSON.parse(\n readFileSync(path.join(outDirAbs, \"powerhouse.config.json\"), \"utf8\"),\n ) as { connect?: { app?: { basePath?: unknown } } };\n const basePath = built.connect?.app?.basePath;\n if (typeof basePath === \"string\" && basePath) {\n return normalizeBasePath(basePath);\n }\n } catch {\n // no readable dist config\n }\n return undefined;\n}\n\n// `pathname` relative to the deploy base (\"/\" + rest), or itself when outside it.\nexport function stripBase(pathname: string, base: string): string {\n return base !== \"/\" && pathname.startsWith(base)\n ? `/${pathname.slice(base.length)}`\n : pathname;\n}\n\n/** The steps both Connect servers run, in the order they run them. */\nexport type ConnectMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void;\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nconst HASHED_DIRS = [\"/assets/\", \"/fonts/\", \"/__reactor_worker__/assets/\"];\n\n// Content-addressed output (hashed names, or a `v` query on the worker's), as in the nginx image.\nexport function previewCacheControl(\n pathname: string,\n search: string,\n): string | undefined {\n if (HASHED_DIRS.some((dir) => pathname.startsWith(dir))) return IMMUTABLE;\n if (pathname.startsWith(\"/__vendor__/\")) {\n return /\\/(shared-deps|import-map)\\.js(on)?$/.test(pathname)\n ? \"no-cache\"\n : IMMUTABLE;\n }\n if (pathname.startsWith(\"/__react__/\")) return IMMUTABLE;\n if (pathname.startsWith(\"/__reactor_worker__/\")) {\n return new URLSearchParams(search).has(\"v\") ? IMMUTABLE : \"no-cache\";\n }\n return undefined;\n}\n\nexport function cacheHeaders(outDir: string, base: string): ConnectMiddleware {\n return (req, res, next) => {\n const [rawPath, search = \"\"] = (req.url ?? \"/\").split(\"?\");\n const rel = stripBase(rawPath, base);\n let value = previewCacheControl(rel, search);\n // A cached 404 would outlive the next deploy.\n if (value === IMMUTABLE && !existsSync(path.join(outDir, rel))) {\n value = undefined;\n }\n if (value) res.setHeader(\"Cache-Control\", value);\n next();\n };\n}\n\ntype HtmlTransform = (html: string) => string;\n\n/** The dist's shell for the served config: its composition's variant and its app name. */\nexport function shellSwapFor(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n): HtmlTransform | undefined {\n const composition = override.connect?.composition;\n const renamed = override.connect?.branding?.appName !== undefined;\n if (!composition && !renamed) return undefined;\n const file = path.join(outDir, APP_SHELLS_FILE);\n // The manifest the build copied from the Connect it used.\n const variant =\n composition && appShellVariant(composition, readShellPluginsIn(outDir));\n const shell =\n variant && existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as AppShells)[variant]\n : undefined;\n // The name the app will title itself with: the served (baked + override) config's.\n const appName = (\n JSON.parse(mergedConfigBody(outDir, override)) as {\n connect?: { branding?: { appName?: string } };\n }\n ).connect?.branding?.appName;\n return (html) =>\n shell && appShellVariantOf(html) !== variant\n ? swapAppShell(html, shell, base, appName)\n : withShellAppName(html, appName);\n}\n\n/**\n * Whether a request on a proxying server belongs to the switchboard: its\n * paths go to the proxy, untouched, except a browser navigation under `/d/`\n * (Connect's own drive routes), as switchboardProxy splits them.\n */\nexport function isProxiedRequest(urlPath: string, accept: string | undefined) {\n if (!isSwitchboardProxyPath(urlPath)) return false;\n return !(urlPath.startsWith(\"/d/\") && isHtmlNavigation(accept));\n}\n\nexport function serveOverrideStep(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n swapShell?: HtmlTransform,\n proxied = false,\n): ConnectMiddleware {\n return (req, res, next) => {\n const urlPath = stripBase((req.url ?? \"/\").split(\"?\")[0], base);\n if (urlPath === \"/powerhouse.config.json\") {\n res.writeHead(200, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(mergedConfigBody(outDir, override));\n return;\n }\n // The switchboard's paths are the proxy's, which runs after this:\n // served the SPA shell instead, /graphql would never reach it.\n if (proxied && isProxiedRequest(urlPath, req.headers.accept)) {\n next();\n return;\n }\n // index.html and extensionless SPA routes get the CSP patch.\n const isHtml =\n urlPath === \"/\" ||\n urlPath.endsWith(\"/index.html\") ||\n !path.extname(urlPath);\n if ((override.cspRegistrySync || swapShell) && isHtml) {\n const file = path.join(outDir, \"index.html\");\n if (existsSync(file)) {\n let html = readFileSync(file, \"utf8\");\n if (override.cspRegistrySync) {\n const merged = JSON.parse(mergedConfigBody(outDir, override)) as {\n packageRegistryUrl?: string;\n };\n const registry = merged.packageRegistryUrl;\n if (registry) html = patchCspScriptSrc(html, registry);\n }\n if (swapShell) html = swapShell(html);\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(html);\n return;\n }\n }\n next();\n };\n}\n\n/** Extensions whose files have `.gz` siblings. */\nexport const PRECOMPRESS_EXTENSIONS = [\".wasm\", \".data\"] as const;\n\nconst PRECOMPRESSED_TYPES: Record<string, string> = {\n \".wasm\": \"application/wasm\",\n \".data\": \"application/octet-stream\",\n};\n\n// Serves the build's `.gz` siblings of wasm/data, which the main sirv ignores.\nexport function precompressedAssets(\n outDir: string,\n base = \"/\",\n): ConnectMiddleware {\n const serve = sirv(outDir, {\n dev: true,\n etag: true,\n gzip: true,\n extensions: [],\n setHeaders(res, pathname) {\n res.setHeader(\n \"Content-Type\",\n PRECOMPRESSED_TYPES[path.extname(pathname)],\n );\n },\n });\n return (req, res, next) => {\n const url = req.url ?? \"/\";\n const [rawPath, search] = url.split(\"?\");\n const rel = stripBase(rawPath, base);\n // Ranges are byte offsets into the identity body: leave them to the server.\n if (\n !(PRECOMPRESS_EXTENSIONS as readonly string[]).includes(\n path.extname(rel),\n ) ||\n req.headers.range ||\n (base !== \"/\" && rel === rawPath)\n ) {\n next();\n return;\n }\n req.url = search === undefined ? rel : `${rel}?${search}`;\n serve(req, res, () => {\n req.url = url;\n next();\n });\n };\n}\n\n/** Throws, naming the missing file and the build, when `outDirAbs` holds no build. */\nexport function assertConnectBuild(\n outDirArg: string,\n outDirAbs: string,\n dirname: string,\n): void {\n const file = path.join(outDirAbs, \"index.html\");\n if (existsSync(file)) return;\n const relative = path.relative(dirname, file);\n const shown = (\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ? file\n : relative\n )\n .split(path.sep)\n .join(\"/\");\n // A default build, maybe another project's (a monitor copy serves its source's).\n const project = path.resolve(outDirAbs, \"../../..\");\n const build =\n path.resolve(project, DEFAULT_CONNECT_OUTDIR) !== outDirAbs\n ? `\\`ph connect build --outDir ${JSON.stringify(outDirArg)}\\``\n : project === path.resolve(dirname)\n ? \"`ph connect build`\"\n : `\\`ph connect build\\` in ${project.split(path.sep).join(\"/\")}`;\n throw new Error(\n `No Connect build to serve: ${shown} is missing. Build it first with ${build}, or \\`ph run <host> build\\` for a host's Connect.`,\n );\n}\n\n/** The served base: `--base`, else what the dist or the project was built with. */\nexport function connectBaseOf(\n args: Pick<ConnectPreviewArgs, \"connectBasePath\">,\n outDirAbs: string,\n dirname: string,\n): string {\n // Serving a dist needs only its base, not the build's plugin stack.\n const sourceBasePath = getConfig(path.join(dirname, \"powerhouse.config.json\"))\n .connect?.app?.basePath;\n return (\n resolvePreviewBase(args.connectBasePath, outDirAbs) ??\n (sourceBasePath ? normalizeBasePath(sourceBasePath) : \"/\")\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,gBACd,MAA0C,QAAQ,KAChB;CAClC,MAAM,YAAY,IAAI;CACtB,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,aAAa,CAAC,UAAU,OAAO,KAAA;CACpC,MAAM,WAAiC,CAAC;CACxC,IAAI,WACF,SAAS,UAAU,EACjB,QAAQ;EACN,eAAe,UACZ,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,CAAC,CACf,KAAK,SAAS;GAAE;GAAK,MAAM;GAAM,MAAM;EAAK,EAAE;EACjD,kBACE,IAAI,uCAAuC;CAC/C,EACF;CAEF,IAAI,UAAU;EACZ,SAAS,qBAAqB;EAC9B,SAAS,kBAAkB;CAC7B;CACA,OAAO;AACT;AAEA,SAAS,iBACP,QACA,UACQ;CACR,MAAM,OAAO,KAAK,KAAK,QAAQ,wBAAwB;CACvD,MAAM,QAAQ,WAAW,IAAI,IACxB,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC,IACtC,CAAC;CACL,MAAM,UAAU,SAAS,UACrB,UACG,MAAM,WAAW,CAAC,GACnB,SAAS,OACX,IACA,MAAM;CACV,OAAO,KAAK,UAAU;EACpB,GAAG;EACH;EACA,GAAI,SAAS,qBACT,EAAE,oBAAoB,SAAS,mBAAmB,IAClD,CAAC;CACP,CAAC;AACH;;;;;;;AAQA,SAAgB,kBAAkB,MAAc,aAA6B;CAC3E,OAAO,KAAK,QACV,0EACC,QAAQ,MAAc,SAAiB,UAAkB;EACxD,MAAM,SAAS,QAAQ,QAAQ,UAAU,GAAG,CAAC,CAAC,QAAQ,UAAU,GAAG;EACnE,IAAI,OAAO,SAAS,WAAW,GAAG,OAA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GACV,KAAK;EACP,CAAC;CACH;AACF;;AAGA,SAAgB,mBACd,WACA,WACA,SACM;CACN,MAAM,OAAO,KAAK,KAAK,WAAW,YAAY;CAC9C,IAAI,WAAW,IAAI,GAAG;CACtB,MAAM,WAAW,KAAK,SAAS,SAAS,IAAI;CAC5C,MAAM,SACJ,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,IACpB,OACA,SAAA,CAEH,MAAM,KAAK,GAAG,CAAC,CACf,KAAK,GAAG;CAEX,MAAM,UAAU,KAAK,QAAQ,WAAW,UAAU;CAClD,MAAM,QACJ,KAAK,QAAQ,SAAS,sBAAsB,MAAM,YAC9C,+BAA+B,KAAK,UAAU,SAAS,EAAE,MACzD,YAAY,KAAK,QAAQ,OAAO,IAC9B,uBACA,2BAA2B,QAAQ,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;CACnE,MAAM,IAAI,MACR,8BAA8B,MAAM,mCAAmC,MAAM,mDAC/E;AACF;;AAGA,SAAgB,cACd,MACA,WACA,SACQ;CAER,MAAM,iBAAiB,UAAU,KAAK,KAAK,SAAS,wBAAwB,CAAC,CAAC,CAC3E,SAAS,KAAK;CACjB,OACE,mBAAmB,KAAK,iBAAiB,SAAS,MACjD,iBAAiB,kBAAkB,cAAc,IAAI;AAE1D","debug_id":"152aac10-515c-55ef-9f11-64c6a3fbff77"}
|
|
@@ -54,9 +54,11 @@ declare function serveOverrideStep(outDir: string, override: ConnectServeOverrid
|
|
|
54
54
|
/** Extensions whose files have `.gz` siblings. */
|
|
55
55
|
declare const PRECOMPRESS_EXTENSIONS: readonly [".wasm", ".data"];
|
|
56
56
|
declare function precompressedAssets(outDir: string, base?: string): ConnectMiddleware;
|
|
57
|
+
/** Throws, naming the missing file and the build, when `outDirAbs` holds no build. */
|
|
58
|
+
declare function assertConnectBuild(outDirArg: string, outDirAbs: string, dirname: string): void;
|
|
57
59
|
/** The served base: `--base`, else what the dist or the project was built with. */
|
|
58
60
|
declare function connectBaseOf(args: Pick<ConnectPreviewArgs, "connectBasePath">, outDirAbs: string, dirname: string): string;
|
|
59
61
|
//#endregion
|
|
60
|
-
export {
|
|
62
|
+
export { cacheHeaders as a, overrideFromEnv as c, previewCacheControl as d, resolvePreviewBase as f, stripBase as h, assertConnectBuild as i, patchCspScriptSrc as l, shellSwapFor as m, ConnectServeOverride as n, connectBaseOf as o, serveOverrideStep as p, PRECOMPRESS_EXTENSIONS as r, isProxiedRequest as s, ConnectMiddleware as t, precompressedAssets as u };
|
|
61
63
|
export {};
|
|
62
|
-
//# sourceMappingURL=connect-serve-
|
|
64
|
+
//# sourceMappingURL=connect-serve-COWXf_41.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-serve-
|
|
1
|
+
{"version":3,"file":"connect-serve-COWXf_41.d.mts","names":[],"sources":["../src/services/connect-serve.ts"],"mappings":";;;;;;;;;;;;;;UAmCiB;EACf,UAAU;EACV;;EAEA;;;;;;;;;;;iBAYc,gBACd,MAAK,qCACJ;;;;;;;iBAsDa,kBAAkB,cAAc;iBAkBhC,mBACd,6BACA;iBAkBc,UAAU,kBAAkB;;KAOhC,qBACV,KAAK,iBACL,KAAK,gBACL;iBAQc,oBACd,kBACA;iBAec,aAAa,gBAAgB,eAAe;KAcvD,iBAAiB;;iBAGN,aACd,gBACA,UAAU,sBACV,gBACC;;;;;;iBA6Ba,iBAAiB,iBAAiB;iBAKlC,kBACd,gBACA,UAAU,sBACV,eACA,YAAY,eACZ,oBACC;;cA+CU;iBAQG,oBACd,gBACA,gBACC;;iBAqCa,mBACd,mBACA,mBACA;;iBA4Bc,cACd,MAAM,KAAK,wCACX,mBACA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="b275fe92-4897-57b6-a224-4881b6d414db")}catch(e){}}();
|
|
3
3
|
import { assertProtocolConsistency, primaryBackend, protocolEnv, reactorBlockToSwitchboardConfig } from "@powerhousedao/host-core";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
@@ -132,6 +132,12 @@ async function memberSwitchboardConfig(member, env, options) {
|
|
|
132
132
|
storage
|
|
133
133
|
}, options.pluginHost ? { features: { pluginHost: true } } : {});
|
|
134
134
|
}
|
|
135
|
+
/** A Postgres store no url names: the server would use a folder instead. */
|
|
136
|
+
function missingPostgresUrl(reactor, config, hostFileLabel) {
|
|
137
|
+
if (primaryBackend(reactor)?.storage?.kind !== "postgres") return void 0;
|
|
138
|
+
if (config.storage?.reactor?.url) return void 0;
|
|
139
|
+
return `${hostFileLabel}: the reactor's storage is Postgres, but nothing names the database. Set the backend's storage.url, or PH_REACTOR_DATABASE_URL.`;
|
|
140
|
+
}
|
|
135
141
|
/**
|
|
136
142
|
* Fails when the operator's env contradicts the member's protocol block, then
|
|
137
143
|
* creates the block's path-storage dir (the server's own mkdir is not
|
|
@@ -149,7 +155,7 @@ function switchboardDevMode(devVerb, runner) {
|
|
|
149
155
|
return devVerb || runner.dev === true;
|
|
150
156
|
}
|
|
151
157
|
//#endregion
|
|
152
|
-
export {
|
|
158
|
+
export { overlappingKeys as a, readModelAsReactorStore as c, missingPostgresUrl as i, rememberShellNames as l, memberSwitchboardConfig as n, prepareMemberStorage as o, memberSwitchboardConfigSchema as r, reactorBlockConflicts as s, memberEnvOf as t, switchboardDevMode as u };
|
|
153
159
|
|
|
154
|
-
//# sourceMappingURL=member-config-
|
|
155
|
-
//# debugId=
|
|
160
|
+
//# sourceMappingURL=member-config-Bs3yOT6y.mjs.map
|
|
161
|
+
//# debugId=b275fe92-4897-57b6-a224-4881b6d414db
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"member-config-BcEWRVq4.mjs","sources":["../src/runners/member-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n protocolEnv,\n reactorBlockToSwitchboardConfig,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigLayerSchema,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport {\n envNamesBeforeProjectEnv,\n isDotenvDisabled,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport type { ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The operator's env, split by where each value came from. */\nexport interface MemberEnv {\n /** Set by the shell: wins over the host file. */\n shell: Env;\n /** Only in the project `.env`: the host file's keys win over these. */\n dotenv: Env;\n}\n\n// The server's dotenv.config() ignores a file it cannot read.\nfunction readDotenv(cwd: string): Record<string, string> {\n try {\n return dotenv.parse(fs.readFileSync(path.join(cwd, \".env\")));\n } catch {\n return {};\n }\n}\n\nconst shellNamesByEnv = new WeakMap<object, ReadonlySet<string>>();\n\n/** Records which names of `env` the shell set, before a `.env` loads into it. */\nexport function rememberShellNames(env: Env, names: Iterable<string>): void {\n shellNamesByEnv.set(env, new Set(names));\n}\n\n// Taken the first time an env is seen: before the first member's server\n// import loads the .env into it, and reused for every later member.\nfunction shellNamesOf(env: Env): ReadonlySet<string> {\n let names = shellNamesByEnv.get(env);\n if (!names) {\n names =\n (env === process.env ? envNamesBeforeProjectEnv() : undefined) ??\n new Set(Object.keys(env));\n shellNamesByEnv.set(env, names);\n }\n return names;\n}\n\n/**\n * Splits `env` into the shell's values and the `.env` the switchboard server\n * loads from `cwd` (the same file). A name the shell set stays the shell's,\n * whatever the file says.\n */\nexport function memberEnvOf(env: Env, cwd: string = process.cwd()): MemberEnv {\n const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);\n const shellNames = shellNamesOf(env);\n const shell: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (file[name] === undefined || shellNames.has(name)) shell[name] = value;\n }\n const fromFile: Record<string, string> = {};\n for (const [name, value] of Object.entries(file)) {\n if (!shellNames.has(name)) fromFile[name] = value;\n }\n return { shell, dotenv: fromFile };\n}\n\n/** The env vars the block sets, which a `.env` value does not override. */\nfunction blockEnvNames(reactor: ReactorConfig | undefined): string[] {\n const block = reactorBlockToSwitchboardConfig(reactor);\n return [\n ...Object.keys(protocolEnv(reactor?.protocol)),\n ...(block.packages?.dynamic ? [\"DYNAMIC_MODEL_LOADING\"] : []),\n ...(block.features ? [\"PH_WORKFLOWS_ENABLED\"] : []),\n ];\n}\n\n/** `config.switchboard`: a member's own switchboard config. The omitted keys\n * live in the reactor block (storage, protocol, dynamic packages) or the\n * runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */\nexport const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([\n \"logLevel\",\n \"server.port\",\n \"server.dev\",\n \"storage.reactor\",\n \"storage.readModel\",\n \"protocol\",\n \"telemetry\",\n \"packages.dynamic\",\n \"drive\",\n \"remoteDrives\",\n \"features.pluginHost\",\n \"processorConfig\",\n]);\n\nexport interface SwitchboardMember {\n reactor?: ReactorConfig;\n config?: { switchboard?: SwitchboardConfigInput };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** The dotted keys both layers set. */\nexport function overlappingKeys(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n path = \"\",\n): string[] {\n return Object.entries(b).flatMap(([key, value]) => {\n const other = a[key];\n if (value === undefined || other === undefined) return [];\n const at = path ? `${path}.${key}` : key;\n return isPlainObject(value) && isPlainObject(other)\n ? overlappingKeys(other, value, at)\n : [at];\n });\n}\n\n/** Each `config.switchboard` key the reactor block already sets. */\nexport function reactorBlockConflicts(member: SwitchboardMember): string[] {\n const own = member.config?.switchboard;\n if (!own) return [];\n return overlappingKeys(\n reactorBlockToSwitchboardConfig(member.reactor) as Record<string, unknown>,\n own as Record<string, unknown>,\n ).map(\n (key) =>\n `config.switchboard.${key} is also set by the reactor block; set it in one place.`,\n );\n}\n\n/**\n * The deprecation notice for a block whose `readModel.url` still names the\n * reactor store too: nothing else names the store, as it did when\n * readModel.url rode `dbPath`.\n */\nexport function readModelAsReactorStore(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): { url: string; warning: string } | undefined {\n const storage = reactorBlockToSwitchboardConfig(reactor).storage;\n const url = storage?.readModel?.url;\n if (\n !url ||\n storage.reactor ||\n env.PH_REACTOR_DATABASE_URL !== undefined ||\n env.PH_SWITCHBOARD_DATABASE_URL !== undefined\n ) {\n return undefined;\n }\n return {\n url,\n warning:\n `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. ` +\n \"This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).\",\n };\n}\n\n/**\n * The member's switchboard config under the runner's own arguments: its\n * reactor block, then `config.switchboard`, then the env over both, mapped\n * once as the server read it (the shell over the `.env`, whose values for the\n * block's own vars are dropped). The block keeps the precedence it had as\n * set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL\n * overrides its store, and no env var overrides its read model. Writes nothing.\n */\nexport async function memberSwitchboardConfig(\n member: SwitchboardMember,\n env: MemberEnv,\n options: {\n pluginHost: boolean;\n logger?: ILogger;\n /** Under everything else: values no flag or host file set. */\n defaults?: SwitchboardConfigInput;\n },\n): Promise<SwitchboardConfigInput> {\n // Lazy: the env mapping loads reactor-api, which the runner module must not.\n const { switchboardConfigFromEnv } =\n await import(\"@powerhousedao/switchboard/config/env\");\n const block = reactorBlockToSwitchboardConfig(member.reactor);\n const legacy = readModelAsReactorStore(member.reactor, env.shell, \"\");\n if (legacy) {\n block.storage = { ...block.storage, reactor: { url: legacy.url } };\n }\n // One env, as the server read it: the .env under the block's own vars,\n // the shell over both.\n const dotenvValues: Record<string, string | undefined> = { ...env.dotenv };\n for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];\n const fromEnv = switchboardConfigFromEnv(\n { ...dotenvValues, ...env.shell },\n { logger: options.logger },\n );\n const storage = { ...fromEnv.storage };\n if (\n block.storage?.reactor &&\n env.shell.PH_REACTOR_DATABASE_URL === undefined\n ) {\n delete storage.reactor;\n }\n if (block.storage?.readModel) delete storage.readModel;\n return mergeSwitchboardConfig(\n options.defaults ?? {},\n block,\n member.config?.switchboard ?? {},\n { ...fromEnv, storage },\n // A declared composition turns the plugin host on, whatever the env says.\n options.pluginHost ? { features: { pluginHost: true } } : {},\n );\n}\n\n/**\n * Fails when the operator's env contradicts the member's protocol block, then\n * creates the block's path-storage dir (the server's own mkdir is not\n * recursive).\n */\nexport function prepareMemberStorage(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): void {\n assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind !== \"path\" || !storage.dataDir) return;\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n"],"names":[],"mappings":";;;;;;;;;AAgCA,SAAS,WAAW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,QACF,MAAM,UAAU;EAAE,GAAG,MAAM;EAAS,SAAS,EAAE,KAAK,OAAO,IAAI;CAAE;CAInE,MAAM,eAAmD,EAAE,GAAG,IAAI,OAAO;CACzE,KAAK,MAAM,QAAQ,cAAc,OAAO,OAAO,GAAG,OAAO,aAAa;CACtE,MAAM,UAAU,yBACd;EAAE,GAAG;EAAc,GAAG,IAAI;CAAM,GAChC,EAAE,QAAQ,QAAQ,OAAO,CAC3B;CACA,MAAM,UAAU,EAAE,GAAG,QAAQ,QAAQ;CACrC,IACE,MAAM,SAAS,WACf,IAAI,MAAM,4BAA4B,KAAA,GAEtC,OAAO,QAAQ;CAEjB,IAAI,MAAM,SAAS,WAAW,OAAO,QAAQ;CAC7C,OAAO,uBACL,QAAQ,YAAY,CAAC,GACrB,OACA,OAAO,QAAQ,eAAe,CAAC,GAC/B;EAAE,GAAG;EAAS;CAAQ,GAEtB,QAAQ,aAAa,EAAE,UAAU,EAAE,YAAY,KAAK,EAAE,IAAI,CAAC,CAC7D;AACF;;;;;;AAOA,SAAgB,qBACd,SACA,KACA,eACM;CACN,0BAA0B,SAAS,UAAU,EAAE,GAAG,IAAI,GAAG,aAAa;CACtE,MAAM,UAAU,eAAe,OAAO,CAAC,EAAE;CACzC,IAAI,SAAS,SAAS,UAAU,CAAC,QAAQ,SAAS;CAGlD,IAAI,+BAA+B,KAAK,QAAQ,OAAO,GACrD,MAAM,IAAI,MACR,GAAG,cAAc,qBAAqB,QAAQ,QAAQ,8EACxD;CAEF,GAAG,UAAU,QAAQ,SAAS,EAAE,WAAW,KAAK,CAAC;AACnD;;AAGA,SAAgB,mBACd,SACA,QACS;CACT,OAAO,WAAW,OAAO,QAAQ;AACnC","debug_id":"397b5602-ebe3-50b3-89af-8add364d7c0d"}
|
|
1
|
+
{"version":3,"file":"member-config-Bs3yOT6y.mjs","sources":["../src/runners/member-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n protocolEnv,\n reactorBlockToSwitchboardConfig,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigLayerSchema,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport {\n envNamesBeforeProjectEnv,\n isDotenvDisabled,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport type { ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The operator's env, split by where each value came from. */\nexport interface MemberEnv {\n /** Set by the shell: wins over the host file. */\n shell: Env;\n /** Only in the project `.env`: the host file's keys win over these. */\n dotenv: Env;\n}\n\n// The server's dotenv.config() ignores a file it cannot read.\nfunction readDotenv(cwd: string): Record<string, string> {\n try {\n return dotenv.parse(fs.readFileSync(path.join(cwd, \".env\")));\n } catch {\n return {};\n }\n}\n\nconst shellNamesByEnv = new WeakMap<object, ReadonlySet<string>>();\n\n/** Records which names of `env` the shell set, before a `.env` loads into it. */\nexport function rememberShellNames(env: Env, names: Iterable<string>): void {\n shellNamesByEnv.set(env, new Set(names));\n}\n\n// Taken the first time an env is seen: before the first member's server\n// import loads the .env into it, and reused for every later member.\nfunction shellNamesOf(env: Env): ReadonlySet<string> {\n let names = shellNamesByEnv.get(env);\n if (!names) {\n names =\n (env === process.env ? envNamesBeforeProjectEnv() : undefined) ??\n new Set(Object.keys(env));\n shellNamesByEnv.set(env, names);\n }\n return names;\n}\n\n/**\n * Splits `env` into the shell's values and the `.env` the switchboard server\n * loads from `cwd` (the same file). A name the shell set stays the shell's,\n * whatever the file says.\n */\nexport function memberEnvOf(env: Env, cwd: string = process.cwd()): MemberEnv {\n const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);\n const shellNames = shellNamesOf(env);\n const shell: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (file[name] === undefined || shellNames.has(name)) shell[name] = value;\n }\n const fromFile: Record<string, string> = {};\n for (const [name, value] of Object.entries(file)) {\n if (!shellNames.has(name)) fromFile[name] = value;\n }\n return { shell, dotenv: fromFile };\n}\n\n/** The env vars the block sets, which a `.env` value does not override. */\nfunction blockEnvNames(reactor: ReactorConfig | undefined): string[] {\n const block = reactorBlockToSwitchboardConfig(reactor);\n return [\n ...Object.keys(protocolEnv(reactor?.protocol)),\n ...(block.packages?.dynamic ? [\"DYNAMIC_MODEL_LOADING\"] : []),\n ...(block.features ? [\"PH_WORKFLOWS_ENABLED\"] : []),\n ];\n}\n\n/** `config.switchboard`: a member's own switchboard config. The omitted keys\n * live in the reactor block (storage, protocol, dynamic packages) or the\n * runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */\nexport const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([\n \"logLevel\",\n \"server.port\",\n \"server.dev\",\n \"storage.reactor\",\n \"storage.readModel\",\n \"protocol\",\n \"telemetry\",\n \"packages.dynamic\",\n \"drive\",\n \"remoteDrives\",\n \"features.pluginHost\",\n \"processorConfig\",\n]);\n\nexport interface SwitchboardMember {\n reactor?: ReactorConfig;\n config?: { switchboard?: SwitchboardConfigInput };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** The dotted keys both layers set. */\nexport function overlappingKeys(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n path = \"\",\n): string[] {\n return Object.entries(b).flatMap(([key, value]) => {\n const other = a[key];\n if (value === undefined || other === undefined) return [];\n const at = path ? `${path}.${key}` : key;\n return isPlainObject(value) && isPlainObject(other)\n ? overlappingKeys(other, value, at)\n : [at];\n });\n}\n\n/** Each `config.switchboard` key the reactor block already sets. */\nexport function reactorBlockConflicts(member: SwitchboardMember): string[] {\n const own = member.config?.switchboard;\n if (!own) return [];\n return overlappingKeys(\n reactorBlockToSwitchboardConfig(member.reactor) as Record<string, unknown>,\n own as Record<string, unknown>,\n ).map(\n (key) =>\n `config.switchboard.${key} is also set by the reactor block; set it in one place.`,\n );\n}\n\n/**\n * The deprecation notice for a block whose `readModel.url` still names the\n * reactor store too: nothing else names the store, as it did when\n * readModel.url rode `dbPath`.\n */\nexport function readModelAsReactorStore(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): { url: string; warning: string } | undefined {\n const storage = reactorBlockToSwitchboardConfig(reactor).storage;\n const url = storage?.readModel?.url;\n if (\n !url ||\n storage.reactor ||\n env.PH_REACTOR_DATABASE_URL !== undefined ||\n env.PH_SWITCHBOARD_DATABASE_URL !== undefined\n ) {\n return undefined;\n }\n return {\n url,\n warning:\n `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. ` +\n \"This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).\",\n };\n}\n\n/**\n * The member's switchboard config under the runner's own arguments: its\n * reactor block, then `config.switchboard`, then the env over both, mapped\n * once as the server read it (the shell over the `.env`, whose values for the\n * block's own vars are dropped). The block keeps the precedence it had as\n * set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL\n * overrides its store, and no env var overrides its read model. Writes nothing.\n */\nexport async function memberSwitchboardConfig(\n member: SwitchboardMember,\n env: MemberEnv,\n options: {\n pluginHost: boolean;\n logger?: ILogger;\n /** Under everything else: values no flag or host file set. */\n defaults?: SwitchboardConfigInput;\n },\n): Promise<SwitchboardConfigInput> {\n // Lazy: the env mapping loads reactor-api, which the runner module must not.\n const { switchboardConfigFromEnv } =\n await import(\"@powerhousedao/switchboard/config/env\");\n const block = reactorBlockToSwitchboardConfig(member.reactor);\n const legacy = readModelAsReactorStore(member.reactor, env.shell, \"\");\n if (legacy) {\n block.storage = { ...block.storage, reactor: { url: legacy.url } };\n }\n // One env, as the server read it: the .env under the block's own vars,\n // the shell over both.\n const dotenvValues: Record<string, string | undefined> = { ...env.dotenv };\n for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];\n const fromEnv = switchboardConfigFromEnv(\n { ...dotenvValues, ...env.shell },\n { logger: options.logger },\n );\n const storage = { ...fromEnv.storage };\n if (\n block.storage?.reactor &&\n env.shell.PH_REACTOR_DATABASE_URL === undefined\n ) {\n delete storage.reactor;\n }\n if (block.storage?.readModel) delete storage.readModel;\n return mergeSwitchboardConfig(\n options.defaults ?? {},\n block,\n member.config?.switchboard ?? {},\n { ...fromEnv, storage },\n // A declared composition turns the plugin host on, whatever the env says.\n options.pluginHost ? { features: { pluginHost: true } } : {},\n );\n}\n\n/** A Postgres store no url names: the server would use a folder instead. */\nexport function missingPostgresUrl(\n reactor: ReactorConfig | undefined,\n config: SwitchboardConfigInput,\n hostFileLabel: string,\n): string | undefined {\n if (primaryBackend(reactor)?.storage?.kind !== \"postgres\") return undefined;\n if (config.storage?.reactor?.url) return undefined;\n return `${hostFileLabel}: the reactor's storage is Postgres, but nothing names the database. Set the backend's storage.url, or PH_REACTOR_DATABASE_URL.`;\n}\n\n/**\n * Fails when the operator's env contradicts the member's protocol block, then\n * creates the block's path-storage dir (the server's own mkdir is not\n * recursive).\n */\nexport function prepareMemberStorage(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): void {\n assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind !== \"path\" || !storage.dataDir) return;\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: boolean },\n): boolean {\n return devVerb || runner.dev === true;\n}\n"],"names":[],"mappings":";;;;;;;;;A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OAAO,QAAQ;AACnC","debug_id":"b275fe92-4897-57b6-a224-4881b6d414db"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ConnectPreviewArgs } from "../classic-args-Dm0_3O5p.mjs";
|
|
2
|
-
import { n as ConnectServeOverride } from "../connect-serve-
|
|
2
|
+
import { n as ConnectServeOverride } from "../connect-serve-COWXf_41.mjs";
|
|
3
3
|
import { RunnerContext, RunnerHandle } from "@powerhousedao/host-core";
|
|
4
4
|
import { PHConnectRuntimeConfig } from "@powerhousedao/shared/clis";
|
|
5
5
|
import { z } from "zod";
|
|
@@ -945,6 +945,7 @@ export declare function withoutBuiltImages(config: PHConnectRuntimeConfig | unde
|
|
|
945
945
|
reactorWorker: boolean;
|
|
946
946
|
multiReactor?: boolean | undefined;
|
|
947
947
|
reactorClient?: "in-process" | "remote" | "router" | "worker" | undefined;
|
|
948
|
+
storage?: "idb" | "memory" | undefined;
|
|
948
949
|
remoteBackends?: {
|
|
949
950
|
name: string;
|
|
950
951
|
url: string;
|
|
@@ -1158,6 +1159,7 @@ export declare function withoutBuiltImages(config: PHConnectRuntimeConfig | unde
|
|
|
1158
1159
|
reactorWorker: boolean;
|
|
1159
1160
|
multiReactor?: boolean | undefined;
|
|
1160
1161
|
reactorClient?: "in-process" | "remote" | "router" | "worker" | undefined;
|
|
1162
|
+
storage?: "idb" | "memory" | undefined;
|
|
1161
1163
|
remoteBackends?: {
|
|
1162
1164
|
name: string;
|
|
1163
1165
|
url: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.mts","names":[],"sources":["../../src/runners/connect.ts"],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"connect.d.mts","names":[],"sources":["../../src/runners/connect.ts"],"mappings":";;;;;;;;;;;;qBAwCa;qBA0CA,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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W,oBACpB,MAAM,mBACN,KAAK,gBACJ;wBAsBa,mBAAmB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAU/B,sBACV,MAAM,oBACN,WAAW,sBACX,kBACA;EAAY;MACT,QAAQ;;;;;;;wBAQS,UACpB,OAAO,oBACP,MAAM,mBACN,KAAK,gBACJ,QAAQ,aAAa;;;wBAmCF,MACpB,MAAM,mBACN,KAAK,gBACJ,QAAQ,aAAa;;qBAMX,YAAG;qBAEH"}
|
package/dist/runners/connect.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { defineHostSchemas, entryActiveForVerb, findDeadConnectConfig, isStructuralMultiReactor, mergeDefaultDrives, normalizePluginEntries, placeConnectDrives, projectDrivesIntoConnect, projectReactorToConnect, refineConnectReactor, remoteBackendUrls, resolveDriveDeclaration } from "@powerhousedao/host-core";
|
|
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]="94e46473-59a0-58d6-8649-1332bc2a48c0")}catch(e){}}();
|
|
3
|
+
import { defineHostSchemas, entryActiveForVerb, findDeadConnectConfig, isStructuralMultiReactor, mergeDefaultDrives, normalizePluginEntries, placeConnectDrives, projectDrivesIntoConnect, projectReactorToConnect, refineConnectReactor, remoteBackendUrls, resolveDriveDeclaration, unservedConnectStorage } from "@powerhousedao/host-core";
|
|
4
4
|
import { DEFAULT_CONNECT_OUTDIR, DEFAULT_CONNECT_STUDIO_PORT } from "@powerhousedao/shared/clis";
|
|
5
5
|
import { connectConfigSchemaWith } from "@powerhousedao/shared/connect/connect-config-schema";
|
|
6
6
|
import { isPassthroughImageRef } from "@powerhousedao/shared/connect/image-ref";
|
|
@@ -150,6 +150,8 @@ function callerOverrideRaw(host, ctx, verb = "dev") {
|
|
|
150
150
|
namespace: base.instance?.namespace ?? reactorNamespace
|
|
151
151
|
};
|
|
152
152
|
const { connect } = projectReactorToConnect(reactor);
|
|
153
|
+
const unserved = unservedConnectStorage(reactor);
|
|
154
|
+
if (unserved) console.warn(`[connect] hosts/${host.name}/host.js: ${unserved}`);
|
|
153
155
|
const structural = isStructuralMultiReactor(reactor);
|
|
154
156
|
if (!connect.reactor && !connect.instance && !connect.app && !structural) return host.config !== void 0 || composition || declaredDefaults || base.renown !== void 0 || base.instance !== void 0 ? base : void 0;
|
|
155
157
|
const projected = structural ? projectDrivesIntoConnect({
|
|
@@ -268,4 +270,4 @@ const verbs = ["run", "serve"];
|
|
|
268
270
|
export { callerOverride, connectHandle, declaredHostSchema, hostSchema, kind, outputsSchema, run, serve, serveWith, startUnderSupervisor, validateComposition, verbs, withoutBuiltImages };
|
|
269
271
|
|
|
270
272
|
//# sourceMappingURL=connect.mjs.map
|
|
271
|
-
//# debugId=
|
|
273
|
+
//# debugId=94e46473-59a0-58d6-8649-1332bc2a48c0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.mjs","sources":["../../src/runners/connect.ts"],"sourcesContent":["import {\n DEFAULT_CONNECT_OUTDIR,\n DEFAULT_CONNECT_STUDIO_PORT,\n type PHConnectCompositionEntry,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { connectConfigSchemaWith } from \"@powerhousedao/shared/connect/connect-config-schema\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport { withOriginPlaceholders } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport {\n defineHostSchemas,\n entryActiveForVerb,\n findDeadConnectConfig,\n isStructuralMultiReactor,\n mergeDefaultDrives,\n normalizePluginEntries,\n placeConnectDrives,\n resolveDriveDeclaration,\n type DriveDeclaration,\n projectDrivesIntoConnect,\n projectReactorToConnect,\n refineConnectReactor,\n remoteBackendUrls,\n type ReactorConfig,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { z } from \"zod\";\nimport type { ConnectPreviewArgs } from \"../services/classic-args.js\";\nimport type { ConnectServeOverride } from \"../services/connect-serve.js\";\n\n/**\n * BRIDGE runner for Connect hosts (uniform-runners phase 0): maps a\n * hosts/connect/host.js definition onto the SAME service the classic\n * `ph connect studio` (dev/run), `ph connect build` and `ph connect preview`\n * (serve) commands call — no forked behavior.\n */\n\nexport const kind = \"reactor\";\n\n/** The connect host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails), and\n * `config` typed by Connect's own zod schema (the authored `connect` block),\n * whose URL fields that name another host's outputs\n * (`drives.defaultDrives[].url`, `renown.switchboardUrl`) are token-able.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** Open a browser tab once listening (dev/serve). */\n openBrowser: z.boolean().optional(),\n /** Fail instead of moving to the next free port when `port` is taken. */\n strictPort: z.boolean().optional(),\n /** The Connect build output dir (`build` writes it, `serve` serves it). */\n outDir: z.string().min(1).optional(),\n /** Patch the baked CSP for the runtime registry (`serve`); a\n * compound's wiring sets it on its connect member. */\n cspRegistrySync: z.boolean().optional(),\n /** The host's routes folder, project-relative; false for none.\n * Default: hosts/connect/routes. */\n routes: z.union([z.string(), z.literal(false)]).optional(),\n /** The switchboard this Connect is served next to: its server\n * (dev and serve) proxies the switchboard's paths (`/graphql`,\n * `/d/*`, `/attachments`, `/mcp`, `/api/*`) to `target`, and the\n * served config names that switchboard as `${origin}`, resolved by\n * the browser against the page's origin. So one config holds from\n * the developer's `localhost` and from a published site alike, with\n * every call on the page's own origin. Typically a sibling's\n * `origin` output token. */\n proxy: z.strictObject({ target: s.tokenable(z.url()) }).optional(),\n })\n .strict(),\n config: connectConfigSchemaWith(s.tokenable).optional(),\n })\n .superRefine(refineConnectReactor),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a connect host.js author writes. */\nexport type ConnectHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type ConnectHostParsed = z.output<typeof hostSchema>;\n\n/** What a started Connect (`dev`/`run`/`serve`) produces: the origin it\n * actually listens on and the app URL (origin plus base path). */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({ connect: z.url() }),\n});\nexport type ConnectOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/connect\": {\n host: ConnectHost;\n outputs: ConnectOutputs;\n };\n }\n}\n\n/** The slice of a vite dev/preview server a handle needs. */\nexport interface ListeningServer {\n resolvedUrls: { local: string[] } | null;\n close(): Promise<void>;\n}\n\n/** A started Connect as a runner handle. vite has already listened when the\n * service returns, so `ready` is settled; the outputs carry the URL vite\n * resolved (the port it actually bound), falling back to the requested one. */\nexport function connectHandle(\n server: ListeningServer,\n requested: { host: string; port: number },\n): RunnerHandle<ConnectOutputs> {\n const fallback = `http://${requested.host}:${requested.port}/`;\n const app = server.resolvedUrls?.local[0] ?? fallback;\n let closing: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin: new URL(app).origin,\n endpoints: { connect: app },\n }),\n ready: Promise.resolve(),\n shutdown: () => (closing ??= server.close()),\n };\n}\n\n/** host.js reactor.drives -> the served drives.defaultDrives shapes: locals\n * carry id/name/icon and the preferredEditor under its Connect alias `app`;\n * remotes carry their URL. */\nfunction declaredDrivesToDefaults(\n projectRoot: string,\n declarations: readonly DriveDeclaration[],\n): PHConnectDefaultDrive[] {\n return declarations.map((declaration) => {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n if (drive.kind === \"remote\") {\n return {\n url: drive.remoteUrl!,\n name: drive.name,\n icon: drive.icon ?? null,\n };\n }\n return {\n local: true as const,\n // A local drive is skipped on later boots by this id, so it stays fixed.\n id: drive.id ?? drive.slug,\n name: drive.name,\n icon: drive.icon ?? null,\n ...(drive.preferredEditor ? { app: drive.preferredEditor } : {}),\n };\n });\n}\n\n/**\n * The served override. With `runner.proxy`, every URL on the proxied\n * switchboard's origin (drives, backends, plugin configs, however they were\n * written or resolved from output tokens) is served as `${origin}…`: the\n * browser reaches the switchboard through the page's own origin, which this\n * Connect's server proxies, so the config holds wherever the page is loaded\n * from. A host may also write `${origin}/…` itself; that passes through.\n */\nexport function callerOverride(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n const override = callerOverrideRaw(host, ctx, verb);\n const target = host.runner.proxy?.target;\n return override && target\n ? withOriginPlaceholders(override, target)\n : override;\n}\n\nfunction callerOverrideRaw(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n // A copy: the projection below adds served-only keys (composition, …).\n const base: PHConnectRuntimeConfig = { ...host.config };\n const reactor: ReactorConfig | undefined = host.reactor;\n\n // The Renown instance a person chose at start, under the names the\n // switchboard reads, so the two can't disagree.\n const renownUrl = ctx?.env.RENOWN_URL?.trim();\n const renownSwitchboardUrl = ctx?.env.SWITCHBOARD_URL?.trim();\n if (renownUrl || renownSwitchboardUrl) {\n base.renown = {\n ...base.renown,\n ...(renownUrl ? { url: renownUrl } : {}),\n ...(renownSwitchboardUrl ? { switchboardUrl: renownSwitchboardUrl } : {}),\n };\n }\n\n // R3: the composition (verb-filtered, projected as DATA — the browser\n // pipeline resolves and runs the entries), declared drives, and the\n // reactor-core identity/namespace keys.\n const entries = host.runner.plugins;\n const composition: PHConnectCompositionEntry[] | undefined =\n entries === undefined\n ? undefined\n : normalizePluginEntries(entries, `hosts/${host.name}/host.js`)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => ({ module: entry.module, config: entry.config }));\n // Entry configs arrive RESOLVED: output tokens (e.g. the workflows\n // plugin's `drive: switchboard.drives.workflows.url`) were replaced by\n // `ph run` (standalone: the producer's run record; in a compound: the\n // member's live outputs) before validateHost let this verb run.\n if (entries !== undefined) {\n // Change 2: show the composition plan on the `ph run connect` terminal.\n // The pipeline itself runs in the browser (hook execution logs to the\n // browser console); here we report WHAT will be served and for which verb.\n const all = normalizePluginEntries(entries, `hosts/${host.name}/host.js`);\n console.log(\n `[connect] composition plan (verb=${verb}): ${composition?.length ?? 0} active of ${all.length} declared`,\n );\n for (const entry of all) {\n const active = entryActiveForVerb(entry, verb);\n const scope =\n entry.verbs === \"*\" ? \"\" : ` verbs=[${entry.verbs.join(\",\")}]`;\n const cfg = Object.keys(entry.config);\n console.log(\n `[connect] ${active ? \"•\" : \"○\"} ${entry.module}${scope}` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\") +\n (active ? \"\" : \" (inactive for this verb)\"),\n );\n }\n }\n // Config a Connect plugin owns, set on the host while that plugin is not\n // composed for this verb: Connect serves the plugin-absent value instead.\n for (const warning of findDeadConnectConfig(\n host.config,\n entries,\n verb,\n `hosts/${host.name}/host.js`,\n )) {\n console.warn(warning.message);\n }\n const declared = reactor?.drives;\n const declaredDefaults =\n declared && ctx\n ? declaredDrivesToDefaults(ctx.projectRoot, declared)\n : undefined;\n const reactorRenown = reactor?.renown;\n const reactorNamespace = reactor?.namespace;\n base.drives = declaredDefaults\n ? {\n ...base.drives,\n defaultDrives: mergeDefaultDrives(\n declaredDefaults,\n base.drives?.defaultDrives ?? [],\n ),\n preserveStrategy: base.drives?.preserveStrategy ?? \"preserve-all\",\n }\n : base.drives;\n if (composition) base.composition = composition;\n if (reactorRenown) base.renown = { ...reactorRenown, ...base.renown };\n if (reactorNamespace !== undefined)\n base.instance = {\n ...base.instance,\n namespace: base.instance?.namespace ?? reactorNamespace,\n } as typeof base.instance;\n const { connect } = projectReactorToConnect(reactor);\n const structural = isStructuralMultiReactor(reactor);\n if (!connect.reactor && !connect.instance && !connect.app && !structural) {\n // `base` IS host.config when the host has one; a host without a config\n // block still carries its composition, drives, Renown and namespace (set\n // on `base` above). With none of them, there is no override: a classic\n // build.\n return host.config !== undefined ||\n composition ||\n declaredDefaults ||\n base.renown !== undefined ||\n base.instance !== undefined\n ? base\n : undefined;\n }\n const projected = structural\n ? projectDrivesIntoConnect({\n createdDriveUrls: remoteBackendUrls(reactor),\n configuredDefaultDrives: base.drives?.defaultDrives,\n }).drives\n : base.drives;\n const placed = placeConnectDrives(reactor, projected?.defaultDrives ?? []);\n const drives =\n projected?.defaultDrives === undefined\n ? projected\n : { ...projected, defaultDrives: placed.defaultDrives };\n // When the host DECLARES backends, instance facts derive from them and win\n // over config defaults (declaring `kind: \"worker\"` is more explicit intent\n // than a scaffold's `reactorWorker: false`); without backends the P2 rule\n // stands — an explicit connect.* value wins over descriptive projection.\n const declaresBackends = Object.keys(reactor?.backends ?? {}).length > 0;\n const instance = declaresBackends\n ? {\n ...base.instance,\n ...connect.instance,\n ...(placed.collections ? { collections: placed.collections } : {}),\n }\n : { ...connect.instance, ...base.instance };\n return {\n ...base,\n reactor: { ...connect.reactor, ...base.reactor },\n instance: instance as never,\n app: { ...connect.app, ...base.app },\n ...(drives ? { drives: { ...base.drives, ...drives } } : {}),\n };\n}\n\n/**\n * Start a server; under a supervising compound (`ctx.parent`), drop the\n * process-exiting signal listeners it installed (vite's dev and preview\n * servers exit on SIGTERM): the compound owns the exit and stops members in\n * reverse dependency order through their handles.\n */\nexport async function startUnderSupervisor<T>(\n ctx: RunnerContext,\n start: () => Promise<T>,\n): Promise<T> {\n if (!ctx.parent) return start();\n const signals = [\"SIGINT\", \"SIGTERM\"] as const;\n const before = new Map(\n signals.map((signal) => [signal, new Set(process.listeners(signal))]),\n );\n try {\n return await start();\n } finally {\n for (const signal of signals) {\n for (const listener of process.listeners(signal)) {\n if (!before.get(signal)?.has(listener)) {\n process.off(signal, listener);\n }\n }\n }\n }\n}\n\n/** Fail at `ph run`, naming the plugin and key, when a composed Connect\n * plugin's entry config does not match its schema. */\nexport async function validateComposition(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n const { validateConnectPluginConfigs } =\n await import(\"./connect-plugin-configs.js\");\n await validateConnectPluginConfigs(\n ctx.projectRoot,\n host.runner.plugins,\n ctx.verb,\n `hosts/${host.name}/host.js`,\n );\n}\n\n/** A project file the build resolved: the built dist has it (as icon.ico or\n * a data URI); served, its path would mean nothing. */\nfunction isBuiltImage(ref: unknown): boolean {\n const src =\n typeof ref === \"object\" && ref !== null && \"src\" in ref ? ref.src : ref;\n return typeof src === \"string\" && !isPassthroughImageRef(src);\n}\n\n// The served config keeps the build's images: the favicon and any branding\n// image given as a project path were resolved into the dist, and merged over\n// it a path would replace the built data URI with a URL that 404s.\nexport function withoutBuiltImages(config: PHConnectRuntimeConfig | undefined) {\n const branding = config?.branding;\n if (!branding) return config;\n const { favicon: _, ...served } = branding;\n if (isBuiltImage(served.icon)) delete served.icon;\n if (isBuiltImage(served.loader)) delete served.loader;\n return { ...config, branding: served };\n}\n\n/** A server for a built Connect, given what to serve and how. */\nexport type ConnectServerStart = (\n args: ConnectPreviewArgs,\n override?: ConnectServeOverride,\n dirname?: string,\n options?: { proxy?: string },\n) => Promise<ListeningServer>;\n\n/** `serve` on a given server. The host's connect config (including a\n * supervising compound's projected drives and the reactor projection) rides a\n * serve override: the baked powerhouse.config.json merges with it at request\n * time, and `runner.cspRegistrySync` (set by the compound's wiring) patches the\n * baked CSP's script-src for the runtime registry. Together these replace the\n * ph-win-desktop sidecar's hand-rolled static server (desktop shape). */\nexport async function serveWith(\n start: ConnectServerStart,\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const runner = host.runner;\n const port = runner.port ?? DEFAULT_CONNECT_STUDIO_PORT;\n const bind = runner.host ?? \"127.0.0.1\";\n const args: Partial<ConnectPreviewArgs> = {\n port,\n outDir: runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n cors: true,\n printUrls: true,\n bindCLIShortcuts: false,\n // Explicit IPv4 loopback (runner.host overrides): vite's default\n // \"localhost\" can bind ::1 only on Windows, and a supervising shell\n // (ph-win) probes 127.0.0.1 — the sidecar this replaces bound 127.0.0.1.\n host: bind,\n };\n const override = withoutBuiltImages(callerOverride(host, ctx, ctx.verb));\n const server = await startUnderSupervisor<ListeningServer>(ctx, () =>\n start(\n args as ConnectPreviewArgs,\n {\n connect: override,\n cspRegistrySync: runner.cspRegistrySync === true,\n },\n undefined,\n { proxy: runner.proxy?.target },\n ),\n );\n return connectHandle(server, { host: bind, port });\n}\n\n/** Serves a built Connect (run `build` first) with nothing but what a running\n * app has. ph-cli's runner adds the verbs that need build tools. */\nexport async function serve(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n const { runConnectServer } = await import(\"../services/connect-server.js\");\n return serveWith(runConnectServer, host, ctx);\n}\n\n/** With no Studio here, running Connect is serving its build. */\nexport const run = serve;\n\nexport const verbs = [\"run\", \"serve\"];\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAa,OAAO;;;;;;;;;AAUpB,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBACC,OAAO;CACN,QAAQ,EAAE,iBACP,OAAO;;EAEN,aAAa,EAAE,QAAQ,CAAC,CAAC,SAAS;;EAElC,YAAY,EAAE,QAAQ,CAAC,CAAC,SAAS;;EAEjC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;EAGnC,iBAAiB,EAAE,QAAQ,CAAC,CAAC,SAAS;;;EAGtC,QAAQ,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;;;;;;;;;EASzD,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;CACnE,CAAC,CAAC,CACD,OAAO;CACV,QAAQ,wBAAwB,EAAE,SAAS,CAAC,CAAC,SAAS;AACxD,CAAC,CAAC,CACD,YAAY,oBAAoB,CACrC;AACA,MAAa,qBAAqB,QAAQ;AAC1C,MAAa,aAAa,QAAQ;;;AASlC,MAAa,gBAAgB,EAAE,aAAa;CAC1C,QAAQ,EAAE,IAAI;CACd,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAChD,CAAC;;;;AAqBD,SAAgB,cACd,QACA,WAC8B;CAC9B,MAAM,WAAW,UAAU,UAAU,KAAK,GAAG,UAAU,KAAK;CAC5D,MAAM,MAAM,OAAO,cAAc,MAAM,MAAM;CAC7C,IAAI;CACJ,OAAO;EACL,SAAS,cAAc,MAAM;GAC3B,QAAQ,IAAI,IAAI,GAAG,CAAC,CAAC;GACrB,WAA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AE,OAAO,OAAO,OAAO,OAAO,CAChC,CACF,GAC6B;EAAE,MAAM;EAAM;CAAK,CAAC;AACnD;;;AAIA,eAAsB,MACpB,MACA,KACuC;CACvC,MAAM,EAAE,qBAAqB,MAAM,OAAO;CAC1C,OAAO,UAAU,kBAAkB,MAAM,GAAG;AAC9C;;AAGA,MAAa,MAAM;AAEnB,MAAa,QAAQ,CAAC,OAAO,OAAO","debug_id":"1afe3171-4423-5b61-896d-d2141ebf418a"}
|
|
1
|
+
{"version":3,"file":"connect.mjs","sources":["../../src/runners/connect.ts"],"sourcesContent":["import {\n DEFAULT_CONNECT_OUTDIR,\n DEFAULT_CONNECT_STUDIO_PORT,\n type PHConnectCompositionEntry,\n type PHConnectDefaultDrive,\n type PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { connectConfigSchemaWith } from \"@powerhousedao/shared/connect/connect-config-schema\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport { withOriginPlaceholders } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport {\n defineHostSchemas,\n entryActiveForVerb,\n findDeadConnectConfig,\n isStructuralMultiReactor,\n mergeDefaultDrives,\n normalizePluginEntries,\n placeConnectDrives,\n resolveDriveDeclaration,\n type DriveDeclaration,\n projectDrivesIntoConnect,\n projectReactorToConnect,\n unservedConnectStorage,\n refineConnectReactor,\n remoteBackendUrls,\n type ReactorConfig,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport { z } from \"zod\";\nimport type { ConnectPreviewArgs } from \"../services/classic-args.js\";\nimport type { ConnectServeOverride } from \"../services/connect-serve.js\";\n\n/**\n * BRIDGE runner for Connect hosts (uniform-runners phase 0): maps a\n * hosts/connect/host.js definition onto the SAME service the classic\n * `ph connect studio` (dev/run), `ph connect build` and `ph connect preview`\n * (serve) commands call — no forked behavior.\n */\n\nexport const kind = \"reactor\";\n\n/** The connect host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails), and\n * `config` typed by Connect's own zod schema (the authored `connect` block),\n * whose URL fields that name another host's outputs\n * (`drives.defaultDrives[].url`, `renown.switchboardUrl`) are token-able.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** Open a browser tab once listening (dev/serve). */\n openBrowser: z.boolean().optional(),\n /** Fail instead of moving to the next free port when `port` is taken. */\n strictPort: z.boolean().optional(),\n /** The Connect build output dir (`build` writes it, `serve` serves it). */\n outDir: z.string().min(1).optional(),\n /** Patch the baked CSP for the runtime registry (`serve`); a\n * compound's wiring sets it on its connect member. */\n cspRegistrySync: z.boolean().optional(),\n /** The host's routes folder, project-relative; false for none.\n * Default: hosts/connect/routes. */\n routes: z.union([z.string(), z.literal(false)]).optional(),\n /** The switchboard this Connect is served next to: its server\n * (dev and serve) proxies the switchboard's paths (`/graphql`,\n * `/d/*`, `/attachments`, `/mcp`, `/api/*`) to `target`, and the\n * served config names that switchboard as `${origin}`, resolved by\n * the browser against the page's origin. So one config holds from\n * the developer's `localhost` and from a published site alike, with\n * every call on the page's own origin. Typically a sibling's\n * `origin` output token. */\n proxy: z.strictObject({ target: s.tokenable(z.url()) }).optional(),\n })\n .strict(),\n config: connectConfigSchemaWith(s.tokenable).optional(),\n })\n .superRefine(refineConnectReactor),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a connect host.js author writes. */\nexport type ConnectHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type ConnectHostParsed = z.output<typeof hostSchema>;\n\n/** What a started Connect (`dev`/`run`/`serve`) produces: the origin it\n * actually listens on and the app URL (origin plus base path). */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({ connect: z.url() }),\n});\nexport type ConnectOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/connect\": {\n host: ConnectHost;\n outputs: ConnectOutputs;\n };\n }\n}\n\n/** The slice of a vite dev/preview server a handle needs. */\nexport interface ListeningServer {\n resolvedUrls: { local: string[] } | null;\n close(): Promise<void>;\n}\n\n/** A started Connect as a runner handle. vite has already listened when the\n * service returns, so `ready` is settled; the outputs carry the URL vite\n * resolved (the port it actually bound), falling back to the requested one. */\nexport function connectHandle(\n server: ListeningServer,\n requested: { host: string; port: number },\n): RunnerHandle<ConnectOutputs> {\n const fallback = `http://${requested.host}:${requested.port}/`;\n const app = server.resolvedUrls?.local[0] ?? fallback;\n let closing: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin: new URL(app).origin,\n endpoints: { connect: app },\n }),\n ready: Promise.resolve(),\n shutdown: () => (closing ??= server.close()),\n };\n}\n\n/** host.js reactor.drives -> the served drives.defaultDrives shapes: locals\n * carry id/name/icon and the preferredEditor under its Connect alias `app`;\n * remotes carry their URL. */\nfunction declaredDrivesToDefaults(\n projectRoot: string,\n declarations: readonly DriveDeclaration[],\n): PHConnectDefaultDrive[] {\n return declarations.map((declaration) => {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n if (drive.kind === \"remote\") {\n return {\n url: drive.remoteUrl!,\n name: drive.name,\n icon: drive.icon ?? null,\n };\n }\n return {\n local: true as const,\n // A local drive is skipped on later boots by this id, so it stays fixed.\n id: drive.id ?? drive.slug,\n name: drive.name,\n icon: drive.icon ?? null,\n ...(drive.preferredEditor ? { app: drive.preferredEditor } : {}),\n };\n });\n}\n\n/**\n * The served override. With `runner.proxy`, every URL on the proxied\n * switchboard's origin (drives, backends, plugin configs, however they were\n * written or resolved from output tokens) is served as `${origin}…`: the\n * browser reaches the switchboard through the page's own origin, which this\n * Connect's server proxies, so the config holds wherever the page is loaded\n * from. A host may also write `${origin}/…` itself; that passes through.\n */\nexport function callerOverride(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n const override = callerOverrideRaw(host, ctx, verb);\n const target = host.runner.proxy?.target;\n return override && target\n ? withOriginPlaceholders(override, target)\n : override;\n}\n\nfunction callerOverrideRaw(\n host: ConnectHostParsed,\n ctx?: RunnerContext,\n verb = \"dev\",\n): PHConnectRuntimeConfig | undefined {\n // A copy: the projection below adds served-only keys (composition, …).\n const base: PHConnectRuntimeConfig = { ...host.config };\n const reactor: ReactorConfig | undefined = host.reactor;\n\n // The Renown instance a person chose at start, under the names the\n // switchboard reads, so the two can't disagree.\n const renownUrl = ctx?.env.RENOWN_URL?.trim();\n const renownSwitchboardUrl = ctx?.env.SWITCHBOARD_URL?.trim();\n if (renownUrl || renownSwitchboardUrl) {\n base.renown = {\n ...base.renown,\n ...(renownUrl ? { url: renownUrl } : {}),\n ...(renownSwitchboardUrl ? { switchboardUrl: renownSwitchboardUrl } : {}),\n };\n }\n\n // R3: the composition (verb-filtered, projected as DATA — the browser\n // pipeline resolves and runs the entries), declared drives, and the\n // reactor-core identity/namespace keys.\n const entries = host.runner.plugins;\n const composition: PHConnectCompositionEntry[] | undefined =\n entries === undefined\n ? undefined\n : normalizePluginEntries(entries, `hosts/${host.name}/host.js`)\n .filter((entry) => entryActiveForVerb(entry, verb))\n .map((entry) => ({ module: entry.module, config: entry.config }));\n // Entry configs arrive RESOLVED: output tokens (e.g. the workflows\n // plugin's `drive: switchboard.drives.workflows.url`) were replaced by\n // `ph run` (standalone: the producer's run record; in a compound: the\n // member's live outputs) before validateHost let this verb run.\n if (entries !== undefined) {\n // Change 2: show the composition plan on the `ph run connect` terminal.\n // The pipeline itself runs in the browser (hook execution logs to the\n // browser console); here we report WHAT will be served and for which verb.\n const all = normalizePluginEntries(entries, `hosts/${host.name}/host.js`);\n console.log(\n `[connect] composition plan (verb=${verb}): ${composition?.length ?? 0} active of ${all.length} declared`,\n );\n for (const entry of all) {\n const active = entryActiveForVerb(entry, verb);\n const scope =\n entry.verbs === \"*\" ? \"\" : ` verbs=[${entry.verbs.join(\",\")}]`;\n const cfg = Object.keys(entry.config);\n console.log(\n `[connect] ${active ? \"•\" : \"○\"} ${entry.module}${scope}` +\n (cfg.length ? ` config: {${cfg.join(\", \")}}` : \"\") +\n (active ? \"\" : \" (inactive for this verb)\"),\n );\n }\n }\n // Config a Connect plugin owns, set on the host while that plugin is not\n // composed for this verb: Connect serves the plugin-absent value instead.\n for (const warning of findDeadConnectConfig(\n host.config,\n entries,\n verb,\n `hosts/${host.name}/host.js`,\n )) {\n console.warn(warning.message);\n }\n const declared = reactor?.drives;\n const declaredDefaults =\n declared && ctx\n ? declaredDrivesToDefaults(ctx.projectRoot, declared)\n : undefined;\n const reactorRenown = reactor?.renown;\n const reactorNamespace = reactor?.namespace;\n base.drives = declaredDefaults\n ? {\n ...base.drives,\n defaultDrives: mergeDefaultDrives(\n declaredDefaults,\n base.drives?.defaultDrives ?? [],\n ),\n preserveStrategy: base.drives?.preserveStrategy ?? \"preserve-all\",\n }\n : base.drives;\n if (composition) base.composition = composition;\n if (reactorRenown) base.renown = { ...reactorRenown, ...base.renown };\n if (reactorNamespace !== undefined)\n base.instance = {\n ...base.instance,\n namespace: base.instance?.namespace ?? reactorNamespace,\n } as typeof base.instance;\n const { connect } = projectReactorToConnect(reactor);\n const unserved = unservedConnectStorage(reactor);\n if (unserved)\n console.warn(`[connect] hosts/${host.name}/host.js: ${unserved}`);\n const structural = isStructuralMultiReactor(reactor);\n if (!connect.reactor && !connect.instance && !connect.app && !structural) {\n // `base` IS host.config when the host has one; a host without a config\n // block still carries its composition, drives, Renown and namespace (set\n // on `base` above). With none of them, there is no override: a classic\n // build.\n return host.config !== undefined ||\n composition ||\n declaredDefaults ||\n base.renown !== undefined ||\n base.instance !== undefined\n ? base\n : undefined;\n }\n const projected = structural\n ? projectDrivesIntoConnect({\n createdDriveUrls: remoteBackendUrls(reactor),\n configuredDefaultDrives: base.drives?.defaultDrives,\n }).drives\n : base.drives;\n const placed = placeConnectDrives(reactor, projected?.defaultDrives ?? []);\n const drives =\n projected?.defaultDrives === undefined\n ? projected\n : { ...projected, defaultDrives: placed.defaultDrives };\n // When the host DECLARES backends, instance facts derive from them and win\n // over config defaults (declaring `kind: \"worker\"` is more explicit intent\n // than a scaffold's `reactorWorker: false`); without backends the P2 rule\n // stands — an explicit connect.* value wins over descriptive projection.\n const declaresBackends = Object.keys(reactor?.backends ?? {}).length > 0;\n const instance = declaresBackends\n ? {\n ...base.instance,\n ...connect.instance,\n ...(placed.collections ? { collections: placed.collections } : {}),\n }\n : { ...connect.instance, ...base.instance };\n return {\n ...base,\n reactor: { ...connect.reactor, ...base.reactor },\n instance: instance as never,\n app: { ...connect.app, ...base.app },\n ...(drives ? { drives: { ...base.drives, ...drives } } : {}),\n };\n}\n\n/**\n * Start a server; under a supervising compound (`ctx.parent`), drop the\n * process-exiting signal listeners it installed (vite's dev and preview\n * servers exit on SIGTERM): the compound owns the exit and stops members in\n * reverse dependency order through their handles.\n */\nexport async function startUnderSupervisor<T>(\n ctx: RunnerContext,\n start: () => Promise<T>,\n): Promise<T> {\n if (!ctx.parent) return start();\n const signals = [\"SIGINT\", \"SIGTERM\"] as const;\n const before = new Map(\n signals.map((signal) => [signal, new Set(process.listeners(signal))]),\n );\n try {\n return await start();\n } finally {\n for (const signal of signals) {\n for (const listener of process.listeners(signal)) {\n if (!before.get(signal)?.has(listener)) {\n process.off(signal, listener);\n }\n }\n }\n }\n}\n\n/** Fail at `ph run`, naming the plugin and key, when a composed Connect\n * plugin's entry config does not match its schema. */\nexport async function validateComposition(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<void> {\n const { validateConnectPluginConfigs } =\n await import(\"./connect-plugin-configs.js\");\n await validateConnectPluginConfigs(\n ctx.projectRoot,\n host.runner.plugins,\n ctx.verb,\n `hosts/${host.name}/host.js`,\n );\n}\n\n/** A project file the build resolved: the built dist has it (as icon.ico or\n * a data URI); served, its path would mean nothing. */\nfunction isBuiltImage(ref: unknown): boolean {\n const src =\n typeof ref === \"object\" && ref !== null && \"src\" in ref ? ref.src : ref;\n return typeof src === \"string\" && !isPassthroughImageRef(src);\n}\n\n// The served config keeps the build's images: the favicon and any branding\n// image given as a project path were resolved into the dist, and merged over\n// it a path would replace the built data URI with a URL that 404s.\nexport function withoutBuiltImages(config: PHConnectRuntimeConfig | undefined) {\n const branding = config?.branding;\n if (!branding) return config;\n const { favicon: _, ...served } = branding;\n if (isBuiltImage(served.icon)) delete served.icon;\n if (isBuiltImage(served.loader)) delete served.loader;\n return { ...config, branding: served };\n}\n\n/** A server for a built Connect, given what to serve and how. */\nexport type ConnectServerStart = (\n args: ConnectPreviewArgs,\n override?: ConnectServeOverride,\n dirname?: string,\n options?: { proxy?: string },\n) => Promise<ListeningServer>;\n\n/** `serve` on a given server. The host's connect config (including a\n * supervising compound's projected drives and the reactor projection) rides a\n * serve override: the baked powerhouse.config.json merges with it at request\n * time, and `runner.cspRegistrySync` (set by the compound's wiring) patches the\n * baked CSP's script-src for the runtime registry. Together these replace the\n * ph-win-desktop sidecar's hand-rolled static server (desktop shape). */\nexport async function serveWith(\n start: ConnectServerStart,\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n await validateComposition(host, ctx);\n const runner = host.runner;\n const port = runner.port ?? DEFAULT_CONNECT_STUDIO_PORT;\n const bind = runner.host ?? \"127.0.0.1\";\n const args: Partial<ConnectPreviewArgs> = {\n port,\n outDir: runner.outDir ?? DEFAULT_CONNECT_OUTDIR,\n open: runner.openBrowser === true,\n strictPort: runner.strictPort === true,\n cors: true,\n printUrls: true,\n bindCLIShortcuts: false,\n // Explicit IPv4 loopback (runner.host overrides): vite's default\n // \"localhost\" can bind ::1 only on Windows, and a supervising shell\n // (ph-win) probes 127.0.0.1 — the sidecar this replaces bound 127.0.0.1.\n host: bind,\n };\n const override = withoutBuiltImages(callerOverride(host, ctx, ctx.verb));\n const server = await startUnderSupervisor<ListeningServer>(ctx, () =>\n start(\n args as ConnectPreviewArgs,\n {\n connect: override,\n cspRegistrySync: runner.cspRegistrySync === true,\n },\n undefined,\n { proxy: runner.proxy?.target },\n ),\n );\n return connectHandle(server, { host: bind, port });\n}\n\n/** Serves a built Connect (run `build` first) with nothing but what a running\n * app has. ph-cli's runner adds the verbs that need build tools. */\nexport async function serve(\n host: ConnectHostParsed,\n ctx: RunnerContext,\n): Promise<RunnerHandle<ConnectOutputs>> {\n const { runConnectServer } = await import(\"../services/connect-server.js\");\n return serveWith(runConnectServer, host, ctx);\n}\n\n/** With no Studio here, running Connect is serving its build. */\nexport const run = serve;\n\nexport const verbs = [\"run\", \"serve\"];\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAa,OAAO;;;;;;;;;AAUpB,MAAM,UAAU,mBAAmB,MACjC,EAAE,kBACC,OAAO;CACN,QAAQ,EAAE,iBACP,OAAO;;EAEN,aAAa,EAAE,QAAQ,CAAC,CAAC,SAAS;;EAElC,YAAY,EAAE,QAAQ,CAAC,CAAC,SAAS;;EAEjC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;EAGnC,iBAAiB,EAAE,QAAQ,CAAC,CAAC,SAAS;;;EAGtC,QAAQ,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;;;;;;;;;EASzD,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;CACnE,CAAC,CAAC,CACD,OAAO;CACV,QAAQ,wBAAwB,EAAE,SAAS,CAAC,CAAC,SAAS;AACxD,CAAC,CAAC,CACD,YAAY,oBAAoB,CACrC;AACA,MAAa,qBAAqB,QAAQ;AAC1C,MAAa,aAAa,QAAQ;;;AASlC,MAAa,gBAAgB,EAAE,aAAa;CAC1C,QAAQ,EAAE,IAAI;CAC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KAAK;CACpB,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,OAAoC;EACxC;EACA,QAAQ,OAAO,UAAU;EACzB,MAAM,OAAO,gBAAgB;EAC7B,YAAY,OAAO,eAAe;EAClC,MAAM;EACN,WAAW;EACX,kBAAkB;EAIlB,MAAM;CACR;CACA,MAAM,WAAW,mBAAmB,eAAe,MAAM,KAAK,IAAI,IAAI,CAAC;CAYvE,OAAO,cAAc,MAXA,qBAAsC,WACzD,MACE,MACA;EACE,SAAS;EACT,iBAAiB,OAAO,oBAAoB;CAC9C,GACA,KAAA,GACA,EAAE,OAAO,OAAO,OAAO,OAAO,CAChC,CACF,GAC6B;EAAE,MAAM;EAAM;CAAK,CAAC;AACnD;;;AAIA,eAAsB,MACpB,MACA,KACuC;CACvC,MAAM,EAAE,qBAAqB,MAAM,OAAO;CAC1C,OAAO,UAAU,kBAAkB,MAAM,GAAG;AAC9C;;AAGA,MAAa,MAAM;AAEnB,MAAa,QAAQ,CAAC,OAAO,OAAO","debug_id":"94e46473-59a0-58d6-8649-1332bc2a48c0"}
|
|
@@ -775,6 +775,8 @@ export declare function memberSwitchboardConfig(member: SwitchboardMember, env:
|
|
|
775
775
|
/** Under everything else: values no flag or host file set. */
|
|
776
776
|
defaults?: SwitchboardConfigInput;
|
|
777
777
|
}): Promise<SwitchboardConfigInput>;
|
|
778
|
+
/** A Postgres store no url names: the server would use a folder instead. */
|
|
779
|
+
export declare function missingPostgresUrl(reactor: ReactorConfig | undefined, config: SwitchboardConfigInput, hostFileLabel: string): string | undefined;
|
|
778
780
|
/**
|
|
779
781
|
* Fails when the operator's env contradicts the member's protocol block, then
|
|
780
782
|
* creates the block's path-storage dir (the server's own mkdir is not
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"member-config.d.mts","names":[],"sources":["../../src/runners/member-config.ts"],"mappings":";;;;KAqBK,MAAM,SAAS;;iBAGH;;EAEf,OAAO;;EAE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L;EACG;EAAa;;;;;;;;;;wBA2BI,wBACpB,QAAQ,mBACR,KAAK,WACL;EACE;EACA,SAAS;;EAET,WAAW;IAEZ,QAAQ;;wBAoCK,mBACd,SAAS,2BACT,QAAQ,wBACR;;;;;;wBAYc,qBACd,SAAS,2BACT,KAAK,KACL;;wBAgBc,mBACd,kBACA;EAAU"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { memberEnvOf, memberSwitchboardConfig, memberSwitchboardConfigSchema, overlappingKeys, prepareMemberStorage, reactorBlockConflicts, readModelAsReactorStore, rememberShellNames, switchboardDevMode };
|
|
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]="
|
|
4
|
-
//# debugId=
|
|
1
|
+
import { a as overlappingKeys, c as readModelAsReactorStore, i as missingPostgresUrl, l as rememberShellNames, n as memberSwitchboardConfig, o as prepareMemberStorage, r as memberSwitchboardConfigSchema, s as reactorBlockConflicts, t as memberEnvOf, u as switchboardDevMode } from "../member-config-Bs3yOT6y.mjs";
|
|
2
|
+
export { memberEnvOf, memberSwitchboardConfig, memberSwitchboardConfigSchema, missingPostgresUrl, overlappingKeys, prepareMemberStorage, reactorBlockConflicts, readModelAsReactorStore, rememberShellNames, switchboardDevMode };
|
|
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]="b755c6e4-2275-5fd0-b880-f614e8ab8f66")}catch(e){}}();
|
|
4
|
+
//# debugId=b755c6e4-2275-5fd0-b880-f614e8ab8f66
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.d.mts","names":[],"sources":["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AAK;EACvC;;;;;;;;;;;;;;wBAqGoB,aACpB,aACA,mBACA,eAAe,kBACf,mBAAkB,QACjB;;YAqBS,oBAAoB,aAAa;wBAmTvB,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;qBAEL;wBAES,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;;wBAKW,UACpB,MAAM,uBACN,KAAK,mBACJ,QAAQ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import {
|
|
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]="22235455-173a-50c8-ac05-c56d3ed43f16")}catch(e){}}();
|
|
3
|
+
import { c as readModelAsReactorStore, i as missingPostgresUrl, n as memberSwitchboardConfig, o as prepareMemberStorage, r as memberSwitchboardConfigSchema, s as reactorBlockConflicts, t as memberEnvOf, u as switchboardDevMode } from "../member-config-Bs3yOT6y.mjs";
|
|
4
4
|
import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
|
|
5
5
|
import { defineHostSchemas, drivesSchema, mergeDrivePlan, protocolConflicts, resolveDriveDeclaration, resolveHostPlugins, seedDrives } from "@powerhousedao/host-core";
|
|
6
6
|
import { z } from "zod";
|
|
@@ -558,6 +558,8 @@ async function start(host, ctx, devMode) {
|
|
|
558
558
|
pluginHost: entriesDeclared,
|
|
559
559
|
defaults: https === void 0 ? {} : { server: { https } }
|
|
560
560
|
});
|
|
561
|
+
const noDatabase = missingPostgresUrl(host.reactor, memberConfig, hostFile);
|
|
562
|
+
if (noDatabase) throw new Error(noDatabase);
|
|
561
563
|
let pluginComposition;
|
|
562
564
|
if (entries !== void 0) pluginComposition = await resolveHostPlugins(ctx.projectRoot, "switchboard", ctx.verb, entries, `hosts/${host.name}/host.js`);
|
|
563
565
|
const hostDrives = (host.reactor?.drives ?? []).map((declaration) => ({
|
|
@@ -690,6 +692,11 @@ async function checkBoot(host, ctx) {
|
|
|
690
692
|
});
|
|
691
693
|
return issues;
|
|
692
694
|
}
|
|
695
|
+
const noDatabase = missingPostgresUrl(host.reactor, config, ctx.file);
|
|
696
|
+
if (noDatabase) issues.push({
|
|
697
|
+
path: "reactor.backends",
|
|
698
|
+
message: noDatabase
|
|
699
|
+
});
|
|
693
700
|
const facts = await switchboardBootFactsOf(config, {
|
|
694
701
|
dev: switchboardDevMode(ctx.verb === "dev", host.runner),
|
|
695
702
|
configuredRenown: getConfig(path.join(ctx.projectRoot, "powerhouse.config.json")).auth?.renown
|
|
@@ -704,4 +711,4 @@ async function checkBoot(host, ctx) {
|
|
|
704
711
|
export { checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema, verbs, waitForDrive };
|
|
705
712
|
|
|
706
713
|
//# sourceMappingURL=switchboard.mjs.map
|
|
707
|
-
//# debugId=
|
|
714
|
+
//# debugId=22235455-173a-50c8-ac05-c56d3ed43f16
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.mjs","sources":["../../src/services/run/memory-line.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import type {\n GaugeGrowth,\n MemorySample,\n MemoryTelemetryReport,\n} from \"@powerhousedao/reactor\";\n\nconst MB = 1024 * 1024;\n\nfunction size(bytes: number): string {\n return bytes >= 1024 * MB\n ? `${(bytes / (1024 * MB)).toFixed(2)} GB`\n : `${Math.round(bytes / MB)} MB`;\n}\n\nfunction rate(mbPerMin: number | null): string {\n if (mbPerMin === null) return \"\";\n const rounded = Math.round(mbPerMin);\n return ` (${rounded >= 0 ? \"+\" : \"\"}${rounded} MB/min)`;\n}\n\nfunction growth(gauge: GaugeGrowth): string {\n const perMin = Math.round(gauge.perMin);\n const text =\n Math.abs(perMin) >= 1000 ? `${(perMin / 1000).toFixed(1)}k` : `${perMin}`;\n return `${gauge.gauge} ${perMin >= 0 ? \"+\" : \"\"}${text}/min`;\n}\n\nfunction pglite(sample: MemorySample): number {\n let total = 0;\n for (const worker of Object.values(sample.workers)) total += worker.wasm ?? 0;\n return total;\n}\n\n/** The newest sample on one line; undefined before there is one. */\nexport function renderMemoryLine(\n report: MemoryTelemetryReport,\n): string | undefined {\n const sample = report.samples.at(-1);\n if (!sample) return undefined;\n const { summary } = report;\n const heap =\n sample.postGcHeap === null\n ? `heap ${size(sample.heapUsed)}`\n : `heap ${size(sample.heapUsed)}, post-GC ${size(sample.postGcHeap)}${rate(summary?.postGcMbPerMin ?? null)}`;\n const seconds = Math.round(sample.delta.s);\n const perOps =\n summary?.mbPer1kOps === null || summary?.mbPer1kOps === undefined\n ? \"\"\n : `, ${Math.round(summary.mbPer1kOps)} MB/1k ops`;\n const parts = [\n `memory: rss ${size(sample.rss)}${rate(summary?.rssMbPerMin ?? null)}`,\n heap,\n ];\n const wasm = pglite(sample);\n if (wasm > 0) parts.push(`pglite ${size(wasm)}`);\n parts.push(`${sample.delta.opsWritten} ops/${seconds}s${perOps}`);\n const top = summary?.topGauges[0];\n if (top) parts.push(`top: ${growth(top)}`);\n return parts.join(\" · \");\n}\n\n/** True when the reactor is running telemetry with the console output on. */\nexport function wantsMemoryLine(report: MemoryTelemetryReport): boolean {\n return report.enabled && report.outputs.includes(\"console\");\n}\n","import {\n computeProgress,\n formatCount,\n formatDuration,\n rankSlowest,\n renderDoneSummary,\n renderSlowLine,\n type CatchUpPriorityState,\n type IInspector,\n type InspectorProcessorTimingReport,\n type MemoryTelemetryReport,\n type ReactorProgress,\n type SlowProcessor,\n} from \"@powerhousedao/reactor\";\n\nimport { renderMemoryLine, wantsMemoryLine } from \"./memory-line.js\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n /** Undefined when the reactor has no timing, an older one. */\n readonly timing?: InspectorProcessorTimingReport;\n /** The latest sample; undefined when the reactor has no memory telemetry. */\n readonly memory?: MemoryTelemetryReport;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n // Its summary reads every sample of the window, too much for each poll.\n let memoryReadAt = 0;\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n let timing: InspectorProcessorTimingReport | undefined;\n try {\n timing = await inspector.getProcessorTiming();\n } catch {\n timing = undefined;\n }\n let memory: MemoryTelemetryReport | undefined;\n if (Date.now() - memoryReadAt >= MEMORY_READ_MS) {\n memoryReadAt = Date.now();\n try {\n memory = await inspector.getMemoryTelemetry(1);\n } catch {\n memory = undefined;\n }\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n timing,\n memory,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n /** How many of the slowest processors to show; 0 hides them. */\n readonly top?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst DEFAULT_TOP = 5;\nconst MEMORY_READ_MS = 5_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\n// label, space, bar, space, 7 for \"errored\" / \"100%\"\nconst BAR_FIXED = 9;\n\nfunction barLabelWidth(rows: readonly ProgressRow[], columns: number): number {\n const width = Math.max(columns - 1, 1);\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n return Math.max(1, Math.min(MAX_LABEL, longest, width - BAR_FIXED - MIN_BAR));\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n const labelWidth = barLabelWidth(rows, columns);\n const barWidth = Math.max(MIN_BAR, width - labelWidth - BAR_FIXED);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** The columns of the slowest block, dropped from the first on a narrow console. */\nconst SLOW_COLUMNS: readonly {\n title: string;\n width: number;\n cell: (row: SlowProcessor) => string;\n}[] = [\n {\n title: \"eta\",\n width: 7,\n cell: (row) => (row.etaMs === null ? \"\" : formatDuration(row.etaMs)),\n },\n {\n title: \"behind\",\n width: 8,\n cell: (row) => formatCount(row.ordinalsBehind),\n },\n { title: \"fill\", width: 7, cell: (row) => formatDuration(row.fillMs) },\n { title: \"read\", width: 7, cell: (row) => formatDuration(row.readMs) },\n { title: \"op/s\", width: 6, cell: (row) => formatCount(row.opsPerSecond) },\n {\n title: \"handler\",\n width: 8,\n cell: (row) => formatDuration(row.handlerMs),\n },\n];\n\nconst BUSY_WIDTH = 7;\nconst SLOW_ORDER = [\"handler\", \"read\", \"fill\", \"op/s\", \"behind\", \"eta\"];\n\n/**\n * The slowest processors as a table, for under the bars. The label column\n * is at least as wide as the bars' and every line stays short of the last\n * column; a narrow console loses `eta`, `behind`, `fill`, `read`, `op/s`,\n * `handler`, in that order, and `busy` always stays.\n */\nexport function renderSlowest(\n rows: readonly SlowProcessor[],\n columns: number,\n labelWidth: number,\n windowMs: number,\n): string[] {\n if (rows.length === 0) return [];\n const width = Math.max(columns - 1, 1);\n const title = `slowest, last ${Math.round(windowMs / 1000)} s`;\n const longest = Math.max(\n title.length,\n ...rows.map((row) => row.label.length),\n );\n const label = Math.max(\n 1,\n Math.min(\n Math.max(labelWidth, Math.min(longest, MAX_LABEL)),\n width - BUSY_WIDTH - 1,\n ),\n );\n let room = width - label - BUSY_WIDTH;\n const kept = new Set<string>();\n for (const column of [...SLOW_COLUMNS].reverse()) {\n if (room < column.width) break;\n room -= column.width;\n kept.add(column.title);\n }\n const shown = SLOW_ORDER.flatMap((name) => {\n const column = SLOW_COLUMNS.find((c) => c.title === name);\n return column && kept.has(name) ? [column] : [];\n });\n const line = (first: string, busy: string, cells: string[]) =>\n `${fit(first, label)}${busy.padStart(BUSY_WIDTH)}${cells.join(\"\")}`.slice(\n 0,\n width,\n );\n return [\n line(\n title,\n \"busy\",\n shown.map((column) => column.title.padStart(column.width)),\n ),\n ...rows.map((row) =>\n line(\n row.label,\n formatDuration(row.busyMs),\n shown.map((column) => column.cell(row).padStart(column.width)),\n ),\n ),\n ];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n const top = options.top ?? DEFAULT_TOP;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let timing: InspectorProcessorTimingReport | undefined;\n let memory: MemoryTelemetryReport | undefined;\n let lastMemoryLine = Date.now();\n let busySince: number | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const slowest = () =>\n timing && timing.level !== \"off\" && top > 0\n ? rankSlowest(timing, top, \"window\")\n : [];\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const columns = widthOf(stdout);\n const lines = [\n ...renderBars(rows, columns, priority),\n ...renderSlowest(\n slowest(),\n columns,\n barLabelWidth(rows, columns),\n timing?.windowMs ?? 0,\n ),\n ];\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority, timing, memory } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n const now = Date.now();\n // Through stderr, so a terminal's bars lift above it like any other output.\n if (\n memory &&\n wantsMemoryLine(memory) &&\n now - lastMemoryLine >= memory.consoleIntervalMs\n ) {\n const line = renderMemoryLine(memory);\n if (line) {\n stderr.write(`${line}\\n`);\n lastMemoryLine = now;\n }\n }\n if (busy(rows)) {\n busySince ??= now;\n } else if (busySince !== undefined) {\n const wallMs = now - busySince;\n busySince = undefined;\n if (timing && timing.level !== \"off\" && top > 0) {\n erase();\n originalOut(\n `${renderDoneSummary(rankSlowest(timing, top, \"total\"), wallMs)}\\n`,\n );\n }\n }\n if (tty) {\n erase();\n draw();\n return;\n }\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n const slow = slowest();\n if (slow.length > 0) {\n originalOut(`${renderSlowLine(slow, timing?.windowMs ?? 0)}\\n`);\n }\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import type * as SwitchboardUtils from \"@powerhousedao/switchboard/utils\";\nimport {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { SwitchboardArgs } from \"../services/classic-args.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails).\n * `config.switchboard` is this member's own switchboard config (auth,\n * inspection, workers, ...); a key the reactor block also sets is refused.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z\n .strictObject({ switchboard: memberSwitchboardConfigSchema.optional() })\n .optional(),\n })\n .superRefine((host, ctx) => {\n for (const message of reactorBlockConflicts(host)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"switchboard\"],\n message,\n });\n }\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract).\n *\n * The probe is anonymous, and a host with authentication on hides a drive\n * from a caller it refuses (`/d/:drive` answers 404 to anyone who may not\n * read it, 401 under the authenticated-caller floor). Those answers prove\n * the server is listening but not whether the drive exists, so `served`,\n * the reactor's own view of the drive, decides then; without it an\n * ADMIN_ONLY host never passes this gate and the compound tears down after\n * the timeout. */\nexport async function waitForDrive(\n url: string,\n timeoutMs: number,\n served?: () => Promise<boolean>,\n fetchImpl: typeof fetch = fetch,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n const HIDDEN = new Set([401, 403, 404]);\n for (;;) {\n try {\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) return;\n if (HIDDEN.has(res.status) && served && (await served())) return;\n } catch {\n // not listening yet\n }\n if (Date.now() > deadline) {\n throw new Error(\n `Switchboard drive ${url} did not answer within ${timeoutMs}ms.`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 400));\n }\n}\n\n/** What a started switchboard returns. */\nexport type SwitchboardHandle = RunnerHandle<SwitchboardOutputs>;\n\n/** The slice of the switchboard's reactor client (IReactorClient) the seeder\n * reads: id-or-slug resolution against the read model (live documents). */\ninterface SlugLookupClient {\n resolveIdOrSlug(identifier: string): Promise<string | undefined>;\n}\n\n/**\n * Adapter from the switchboard's reactor client onto the host-core seeder.\n * Seeding is SLUG-keyed: a live drive that already serves the slug — under\n * whatever id (a store from a run that hashed the project path differently,\n * or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive\n * alone only knows ids: with a different id it would try to create a second\n * drive for the slug, and against a deleted document with that id the create\n * fails on every boot.\n */\nfunction seederClient(\n reactor: unknown,\n port: number,\n seededIds: Map<string, string>,\n): DriveSeederClient {\n return {\n findDriveBySlug: async (slug: string) => {\n try {\n const id = await (reactor as SlugLookupClient).resolveIdOrSlug(slug);\n if (id) seededIds.set(slug, id);\n return id || undefined;\n } catch {\n // not found (or ambiguous): seed as declared\n return undefined;\n }\n },\n createDrive: async (drive: ResolvedDrive) => {\n const { ensureDrive } = await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(ensureDrive, reactor, drive, port);\n } catch (error) {\n console.error(\n `The drive \"${drive.slug}\" was not created: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n // Its id: the declared one, or the one the reactor generated\n let id: string | undefined;\n try {\n id = await (reactor as SlugLookupClient).resolveIdOrSlug(drive.slug);\n } catch {\n id = undefined;\n }\n seededIds.set(drive.slug, id || drive.id || drive.slug);\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\n/** A declared local drive, through the switchboard's own default-drive path. */\nasync function createDeclaredDrive(\n ensureDrive: typeof SwitchboardUtils.ensureDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await ensureDrive(\n reactor as Parameters<typeof ensureDrive>[0],\n {\n ...(drive.id ? { id: drive.id } : {}),\n ...(drive.documentType ? { documentType: drive.documentType } : {}),\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof ensureDrive>[1],\n port,\n );\n}\n\nfunction catchUpTopFromEnv(raw: string | undefined): number | undefined {\n const top = Number(raw?.trim() || Number.NaN);\n return Number.isInteger(top) && top >= 0 ? top : undefined;\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const hostFile = `hosts/${host.name}/host.js`;\n // Split before the server import loads the project .env into the env.\n const env = memberEnvOf(ctx.env);\n prepareMemberStorage(host.reactor, env.shell, hostFile);\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n hostFile,\n );\n if (legacyStore) console.warn(legacyStore.warning);\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);\n // powerhouse.config.json `reactor.https` is a default, not a flag: it goes\n // under the member's own config instead of over it.\n const { https } = classic;\n const args = { ...classic, https: undefined };\n // This member's own config, under the args: nothing is written to the\n // process env, so compound members do not see each other's settings.\n const memberConfig = await memberSwitchboardConfig(host, env, {\n pluginHost: entriesDeclared,\n defaults: https === undefined ? {} : { server: { https } },\n });\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and\n // `features.pluginHost` drives server-side activation. No plugins key =\n // classic path.\n let pluginComposition;\n if (entries !== undefined) {\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n // `/ready` waits until the drives seeded below exist.\n let seeded!: { resolve: () => void; reject: (error: unknown) => void };\n const readyAfter = new Promise<void>((resolve, reject) => {\n seeded = { resolve, reject };\n });\n const seeding = async <T>(work: Promise<T>): Promise<T> => {\n try {\n return await work;\n } catch (error) {\n seeded.reject(error);\n throw error;\n }\n };\n const switchboard = await startSwitchboard(\n { ...serverArgs, readyAfter },\n undefined,\n memberConfig,\n );\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was. PH_CATCH_UP_TOP\n // sets how many of the slowest processors they list; 0 hides them.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n top: catchUpTopFromEnv(process.env.PH_CATCH_UP_TOP),\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seeding(\n seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n ),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id ?? drive.slug,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { projectDriveId, seedWorkflowsDrive } =\n await import(\"../services/switchboard.js\");\n const url = await seeding(\n seedWorkflowsDrive(switchboard.reactor, port, ctx.projectRoot),\n );\n if (url) {\n drives.workflows = {\n id: projectDriveId(\"workflows\", ctx.projectRoot),\n url,\n };\n }\n }\n seeded.resolve();\n\n // Under an authenticating host the anonymous probe cannot see the drive;\n // the reactor's slug lookup (the seeder's) answers for it.\n const served = async () => {\n try {\n const id = await (\n switchboard.reactor as SlugLookupClient\n ).resolveIdOrSlug(slug);\n return Boolean(id);\n } catch {\n return false;\n }\n };\n const ready = waitForDrive(driveUrl, 180_000, served);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport const verbs = [\"run\", \"serve\", \"dev\"];\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n // As `start` splits it: the project .env sits under the host file.\n const env = memberEnvOf(ctx.env, ctx.projectRoot);\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n env.shell,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n ctx.file,\n );\n if (legacyStore) {\n issues.push({ path: \"reactor.backends\", message: legacyStore.warning });\n }\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsOf, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n let config;\n try {\n // As `start` builds it; an env parse error becomes the issue.\n config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n } catch (error) {\n issues.push({\n path: \"\",\n message: error instanceof Error ? error.message : String(error),\n });\n return issues;\n }\n const facts = await switchboardBootFactsOf(config, {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n });\n for (const message of switchboardBootIssues(facts)) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n"],"names":[],"mappings":";;;;;;;;;AAMA,MAAM,KAAK;AAEX,SAAS,KAAK,OAAuB;CACnC,OAAO,SAAS,OAAO,KACnB,IAAI,SAAS,OAAO,IAAA,CAAK,QAAQ,CAAC,EAAE,OACpC,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE;AAChC;AAEA,SAAS,KAAK,UAAiC;CAC7C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,KAAK,MAAM,QAAQ;CACnC,OAAO,KAAK,WAAW,IAAI,MAAM,KAAK,QAAQ;AAChD;AAEA,SAAS,OAAO,OAA4B;CAC1C,MAAM,SAAS,KAAK,MAAM,MAAM,MAAM;CACtC,MAAM,OACJ,KAAK,IAAI,MAAM,KAAK,MAAO,IAAI,SAAS,IAAA,CAAM,QAAQ,CAAC,EAAE,KAAK,GAAG;CACnE,OAAO,GAAG,MAAM,MAAM,GAAG,UAAU,IAAI,MAAM,KAAK,KAAK;AACzD;AAEA,SAAS,OAAO,QAA8B;CAC5C,IAAI,QAAQ;CACZ,KAAK,MAAM,UAAU,OAAO,OAAO,OAAO,OAAO,GAAG,SAAS,OAAO,QAAQ;CAC5E,OAAO;AACT;;AAGA,SAAgB,iBACd,QACoB;CACpB,MAAM,SAAS,OA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src/services/run/memory-line.ts","../../src/services/run/catch-up-progress.ts","../../src/runners/switchboard.ts"],"sourcesContent":["import type {\n GaugeGrowth,\n MemorySample,\n MemoryTelemetryReport,\n} from \"@powerhousedao/reactor\";\n\nconst MB = 1024 * 1024;\n\nfunction size(bytes: number): string {\n return bytes >= 1024 * MB\n ? `${(bytes / (1024 * MB)).toFixed(2)} GB`\n : `${Math.round(bytes / MB)} MB`;\n}\n\nfunction rate(mbPerMin: number | null): string {\n if (mbPerMin === null) return \"\";\n const rounded = Math.round(mbPerMin);\n return ` (${rounded >= 0 ? \"+\" : \"\"}${rounded} MB/min)`;\n}\n\nfunction growth(gauge: GaugeGrowth): string {\n const perMin = Math.round(gauge.perMin);\n const text =\n Math.abs(perMin) >= 1000 ? `${(perMin / 1000).toFixed(1)}k` : `${perMin}`;\n return `${gauge.gauge} ${perMin >= 0 ? \"+\" : \"\"}${text}/min`;\n}\n\nfunction pglite(sample: MemorySample): number {\n let total = 0;\n for (const worker of Object.values(sample.workers)) total += worker.wasm ?? 0;\n return total;\n}\n\n/** The newest sample on one line; undefined before there is one. */\nexport function renderMemoryLine(\n report: MemoryTelemetryReport,\n): string | undefined {\n const sample = report.samples.at(-1);\n if (!sample) return undefined;\n const { summary } = report;\n const heap =\n sample.postGcHeap === null\n ? `heap ${size(sample.heapUsed)}`\n : `heap ${size(sample.heapUsed)}, post-GC ${size(sample.postGcHeap)}${rate(summary?.postGcMbPerMin ?? null)}`;\n const seconds = Math.round(sample.delta.s);\n const perOps =\n summary?.mbPer1kOps === null || summary?.mbPer1kOps === undefined\n ? \"\"\n : `, ${Math.round(summary.mbPer1kOps)} MB/1k ops`;\n const parts = [\n `memory: rss ${size(sample.rss)}${rate(summary?.rssMbPerMin ?? null)}`,\n heap,\n ];\n const wasm = pglite(sample);\n if (wasm > 0) parts.push(`pglite ${size(wasm)}`);\n parts.push(`${sample.delta.opsWritten} ops/${seconds}s${perOps}`);\n const top = summary?.topGauges[0];\n if (top) parts.push(`top: ${growth(top)}`);\n return parts.join(\" · \");\n}\n\n/** True when the reactor is running telemetry with the console output on. */\nexport function wantsMemoryLine(report: MemoryTelemetryReport): boolean {\n return report.enabled && report.outputs.includes(\"console\");\n}\n","import {\n computeProgress,\n formatCount,\n formatDuration,\n rankSlowest,\n renderDoneSummary,\n renderSlowLine,\n type CatchUpPriorityState,\n type IInspector,\n type InspectorProcessorTimingReport,\n type MemoryTelemetryReport,\n type ReactorProgress,\n type SlowProcessor,\n} from \"@powerhousedao/reactor\";\n\nimport { renderMemoryLine, wantsMemoryLine } from \"./memory-line.js\";\n\n/** One bar: a processor factory or a read model, and how far its catch-up has got. */\nexport type ProgressRow = {\n readonly label: string;\n /** 0..1 of the current run. */\n readonly fraction: number;\n readonly state: \"catching-up\" | \"done\" | \"errored\";\n};\n\n/** The catch-up priority as the progress display states it. */\nexport type ProgressPriority = {\n readonly mode: CatchUpPriorityState[\"mode\"];\n readonly level: number;\n readonly reason: string;\n};\n\n/** What one read of the source shows: the bars, and the priority when known. */\nexport type ProgressSnapshot = {\n readonly rows: readonly ProgressRow[];\n readonly priority: ProgressPriority | undefined;\n /** Undefined when the reactor has no timing, an older one. */\n readonly timing?: InspectorProcessorTimingReport;\n /** The latest sample; undefined when the reactor has no memory telemetry. */\n readonly memory?: MemoryTelemetryReport;\n};\n\n/** Reads the current rows; rejects while the reactor cannot answer. */\nexport type ProgressSource = () => Promise<ProgressSnapshot>;\n\nfunction withDrives(label: string, driveCount: number): string {\n return `${label} (${driveCount} ${driveCount === 1 ? \"drive\" : \"drives\"})`;\n}\n\n/** One row per processor factory, then one per reactor read model. */\nexport function progressRows(progress: ReactorProgress): ProgressRow[] {\n const factories = progress.factories.map((factory): ProgressRow => ({\n label: withDrives(factory.label, factory.driveCount),\n fraction: factory.fraction,\n state:\n factory.phase === \"errored\"\n ? \"errored\"\n : factory.phase === \"catching-up\"\n ? \"catching-up\"\n : \"done\",\n }));\n const readModels = progress.readModels.map((model): ProgressRow => ({\n label: model.consumerId,\n fraction: model.fraction,\n state: model.blocked ? \"errored\" : model.complete ? \"done\" : \"catching-up\",\n }));\n return [...factories, ...readModels];\n}\n\n/** Rows from a reactor's inspector: its processors, catch-up status and priority. */\nexport function inspectorProgressSource(inspector: IInspector): ProgressSource {\n // Its summary reads every sample of the window, too much for each poll.\n let memoryReadAt = 0;\n return async () => {\n const processors = await inspector.getProcessors();\n let catchUp:\n | Awaited<ReturnType<IInspector[\"getCatchUpStatus\"]>>\n | undefined;\n try {\n catchUp = await inspector.getCatchUpStatus();\n } catch {\n catchUp = undefined;\n }\n let priority: ProgressPriority | undefined;\n try {\n const state = await inspector.getCatchUpPriority();\n priority = { mode: state.mode, level: state.level, reason: state.reason };\n } catch {\n priority = undefined;\n }\n let timing: InspectorProcessorTimingReport | undefined;\n try {\n timing = await inspector.getProcessorTiming();\n } catch {\n timing = undefined;\n }\n let memory: MemoryTelemetryReport | undefined;\n if (Date.now() - memoryReadAt >= MEMORY_READ_MS) {\n memoryReadAt = Date.now();\n try {\n memory = await inspector.getMemoryTelemetry(1);\n } catch {\n memory = undefined;\n }\n }\n return {\n rows: progressRows(computeProgress(processors, catchUp)),\n priority,\n timing,\n memory,\n };\n };\n}\n\n/** `catch-up priority 6 (dynamic, idle 14 s)`, or `catch-up priority 3 (fixed)`. */\nexport function renderPriority(priority: ProgressPriority): string {\n const why =\n priority.mode === \"dynamic\" ? `dynamic, ${priority.reason}` : \"fixed\";\n return `catch-up priority ${priority.level} (${why})`;\n}\n\n/** The slice of a TTY stream the display writes to and intercepts. */\nexport type ProgressStream = {\n write: NodeJS.WriteStream[\"write\"];\n readonly isTTY?: boolean;\n readonly columns?: number;\n /** A TTY stream emits \"resize\" when the terminal's size changes. */\n on?(event: \"resize\", listener: () => void): unknown;\n off?(event: \"resize\", listener: () => void): unknown;\n};\n\n/** The console width the bars are sized for: a reported width, else 80. */\nfunction widthOf(stream: ProgressStream): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : 80;\n}\n\nexport type ProgressDisplayOptions = {\n readonly stdout: ProgressStream;\n readonly stderr: ProgressStream;\n /** How often the source is read. */\n readonly pollMs?: number;\n /** Without a TTY: how often a progress line is printed while catching up. */\n readonly lineMs?: number;\n /** How many of the slowest processors to show; 0 hides them. */\n readonly top?: number;\n};\n\nexport type ProgressDisplay = {\n /** Stops polling, removes the bars and restores the streams. */\n stop(): void;\n};\n\nconst DEFAULT_POLL_MS = 1_000;\nconst DEFAULT_LINE_MS = 10_000;\nconst DEFAULT_TOP = 5;\nconst MEMORY_READ_MS = 5_000;\nconst MIN_BAR = 10;\nconst MAX_LABEL = 32;\n\nfunction percent(row: ProgressRow): string {\n if (row.state === \"errored\") return \"errored\";\n if (row.state === \"done\") return \"done\";\n return `${Math.floor(Math.min(Math.max(row.fraction, 0), 1) * 100)}%`;\n}\n\n// label, space, bar, space, 7 for \"errored\" / \"100%\"\nconst BAR_FIXED = 9;\n\nfunction barLabelWidth(rows: readonly ProgressRow[], columns: number): number {\n const width = Math.max(columns - 1, 1);\n const longest = Math.max(...rows.map((row) => row.label.length), 0);\n return Math.max(1, Math.min(MAX_LABEL, longest, width - BAR_FIXED - MIN_BAR));\n}\n\nfunction fit(label: string, width: number): string {\n return label.length <= width\n ? label.padEnd(width)\n : `…${label.slice(label.length - width + 1)}`;\n}\n\n/**\n * The bar block, one line per row, under the priority when known. Every line\n * stays short of the terminal's last column: a line that fills it wraps on\n * xterm-based terminals (VS Code, Windows Terminal), and the erase would then\n * lift fewer lines than are on screen, leaving old bars behind. On a narrow\n * terminal the label gives way before the bar.\n */\nexport function renderBars(\n rows: readonly ProgressRow[],\n columns: number,\n priority?: ProgressPriority,\n): string[] {\n const width = Math.max(columns - 1, 1);\n const labelWidth = barLabelWidth(rows, columns);\n const barWidth = Math.max(MIN_BAR, width - labelWidth - BAR_FIXED);\n const bars = rows.map((row) => {\n const fraction = row.state === \"done\" ? 1 : row.fraction;\n const filled = Math.round(Math.min(Math.max(fraction, 0), 1) * barWidth);\n const bar = \"█\".repeat(filled) + \"░\".repeat(barWidth - filled);\n return `${fit(row.label, labelWidth)} ${bar} ${percent(row).padStart(7)}`.slice(\n 0,\n width,\n );\n });\n if (!priority) return bars;\n return [renderPriority(priority).slice(0, width), ...bars];\n}\n\n/** The columns of the slowest block, dropped from the first on a narrow console. */\nconst SLOW_COLUMNS: readonly {\n title: string;\n width: number;\n cell: (row: SlowProcessor) => string;\n}[] = [\n {\n title: \"eta\",\n width: 7,\n cell: (row) => (row.etaMs === null ? \"\" : formatDuration(row.etaMs)),\n },\n {\n title: \"behind\",\n width: 8,\n cell: (row) => formatCount(row.ordinalsBehind),\n },\n { title: \"fill\", width: 7, cell: (row) => formatDuration(row.fillMs) },\n { title: \"read\", width: 7, cell: (row) => formatDuration(row.readMs) },\n { title: \"op/s\", width: 6, cell: (row) => formatCount(row.opsPerSecond) },\n {\n title: \"handler\",\n width: 8,\n cell: (row) => formatDuration(row.handlerMs),\n },\n];\n\nconst BUSY_WIDTH = 7;\nconst SLOW_ORDER = [\"handler\", \"read\", \"fill\", \"op/s\", \"behind\", \"eta\"];\n\n/**\n * The slowest processors as a table, for under the bars. The label column\n * is at least as wide as the bars' and every line stays short of the last\n * column; a narrow console loses `eta`, `behind`, `fill`, `read`, `op/s`,\n * `handler`, in that order, and `busy` always stays.\n */\nexport function renderSlowest(\n rows: readonly SlowProcessor[],\n columns: number,\n labelWidth: number,\n windowMs: number,\n): string[] {\n if (rows.length === 0) return [];\n const width = Math.max(columns - 1, 1);\n const title = `slowest, last ${Math.round(windowMs / 1000)} s`;\n const longest = Math.max(\n title.length,\n ...rows.map((row) => row.label.length),\n );\n const label = Math.max(\n 1,\n Math.min(\n Math.max(labelWidth, Math.min(longest, MAX_LABEL)),\n width - BUSY_WIDTH - 1,\n ),\n );\n let room = width - label - BUSY_WIDTH;\n const kept = new Set<string>();\n for (const column of [...SLOW_COLUMNS].reverse()) {\n if (room < column.width) break;\n room -= column.width;\n kept.add(column.title);\n }\n const shown = SLOW_ORDER.flatMap((name) => {\n const column = SLOW_COLUMNS.find((c) => c.title === name);\n return column && kept.has(name) ? [column] : [];\n });\n const line = (first: string, busy: string, cells: string[]) =>\n `${fit(first, label)}${busy.padStart(BUSY_WIDTH)}${cells.join(\"\")}`.slice(\n 0,\n width,\n );\n return [\n line(\n title,\n \"busy\",\n shown.map((column) => column.title.padStart(column.width)),\n ),\n ...rows.map((row) =>\n line(\n row.label,\n formatDuration(row.busyMs),\n shown.map((column) => column.cell(row).padStart(column.width)),\n ),\n ),\n ];\n}\n\n/** One line for a log without a TTY, listing only what is still catching up. */\nexport function renderLine(\n rows: readonly ProgressRow[],\n priority?: ProgressPriority,\n): string {\n const busy = rows.filter((row) => row.state !== \"done\");\n const line = `catch-up: ${busy.map((row) => `${row.label} ${percent(row)}`).join(\" · \")}`;\n return priority\n ? `${line} · priority ${priority.level} ${priority.mode}`\n : line;\n}\n\nfunction busy(rows: readonly ProgressRow[]): boolean {\n return rows.some((row) => row.state !== \"done\");\n}\n\n/**\n * Shows catch-up progress while any row is not done. In a terminal the bars\n * sit below the output and every other write is printed above them; without\n * one, a progress line is printed every `lineMs`.\n */\nexport function startProgressDisplay(\n source: ProgressSource,\n options: ProgressDisplayOptions,\n): ProgressDisplay {\n const { stdout, stderr } = options;\n const tty = stdout.isTTY === true;\n const top = options.top ?? DEFAULT_TOP;\n let rows: readonly ProgressRow[] = [];\n let priority: ProgressPriority | undefined;\n let timing: InspectorProcessorTimingReport | undefined;\n let memory: MemoryTelemetryReport | undefined;\n let lastMemoryLine = Date.now();\n let busySince: number | undefined;\n let drawn = 0;\n let atLineStart = true;\n let lastLine = 0;\n let stopped = false;\n let reading = false;\n\n const restoreOut = stdout.write;\n const restoreErr = stderr.write;\n const originalOut = restoreOut.bind(stdout);\n const originalErr = restoreErr.bind(stderr);\n\n const erase = () => {\n if (drawn > 0) originalOut(`\\x1b[${drawn}A\\r\\x1b[0J`);\n drawn = 0;\n };\n const slowest = () =>\n timing && timing.level !== \"off\" && top > 0\n ? rankSlowest(timing, top, \"window\")\n : [];\n const draw = () => {\n if (!tty || stopped || !atLineStart || !busy(rows)) return;\n const columns = widthOf(stdout);\n const lines = [\n ...renderBars(rows, columns, priority),\n ...renderSlowest(\n slowest(),\n columns,\n barLabelWidth(rows, columns),\n timing?.windowMs ?? 0,\n ),\n ];\n originalOut(`${lines.join(\"\\n\")}\\n`);\n drawn = lines.length;\n };\n\n // Every other write goes above the bars: lift them, write, put them back.\n const above =\n (write: (chunk: string | Uint8Array, ...rest: never[]) => boolean) =>\n (chunk: string | Uint8Array, ...rest: never[]): boolean => {\n erase();\n const result = write(chunk, ...rest);\n const text =\n typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n if (text.length > 0) atLineStart = text.endsWith(\"\\n\");\n draw();\n return result;\n };\n // A resized terminal has already reflowed the drawn lines; redraw for the\n // new width right away rather than at the next poll.\n const onResize = () => {\n if (stopped) return;\n erase();\n draw();\n };\n if (tty) {\n stdout.write = above(originalOut as never) as NodeJS.WriteStream[\"write\"];\n stderr.write = above(originalErr as never) as NodeJS.WriteStream[\"write\"];\n stdout.on?.(\"resize\", onResize);\n }\n\n const tick = async () => {\n if (reading || stopped) return;\n reading = true;\n try {\n ({ rows, priority, timing, memory } = await source());\n } catch {\n // The reactor did not answer; keep the last rows until it does.\n } finally {\n reading = false;\n }\n if (stopped) return;\n const now = Date.now();\n // Through stderr, so a terminal's bars lift above it like any other output.\n if (\n memory &&\n wantsMemoryLine(memory) &&\n now - lastMemoryLine >= memory.consoleIntervalMs\n ) {\n const line = renderMemoryLine(memory);\n if (line) {\n stderr.write(`${line}\\n`);\n lastMemoryLine = now;\n }\n }\n if (busy(rows)) {\n busySince ??= now;\n } else if (busySince !== undefined) {\n const wallMs = now - busySince;\n busySince = undefined;\n if (timing && timing.level !== \"off\" && top > 0) {\n erase();\n originalOut(\n `${renderDoneSummary(rankSlowest(timing, top, \"total\"), wallMs)}\\n`,\n );\n }\n }\n if (tty) {\n erase();\n draw();\n return;\n }\n if (busy(rows) && now - lastLine >= (options.lineMs ?? DEFAULT_LINE_MS)) {\n originalOut(`${renderLine(rows, priority)}\\n`);\n const slow = slowest();\n if (slow.length > 0) {\n originalOut(`${renderSlowLine(slow, timing?.windowMs ?? 0)}\\n`);\n }\n lastLine = now;\n }\n };\n\n const timer = setInterval(\n () => void tick(),\n options.pollMs ?? DEFAULT_POLL_MS,\n );\n (timer as { unref?: () => void }).unref?.();\n void tick();\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n erase();\n if (tty) {\n stdout.off?.(\"resize\", onResize);\n stdout.write = restoreOut;\n stderr.write = restoreErr;\n }\n },\n };\n}\n","import type * as SwitchboardUtils from \"@powerhousedao/switchboard/utils\";\nimport {\n defineHostSchemas,\n drivesSchema,\n mergeDrivePlan,\n protocolConflicts,\n resolveDriveDeclaration,\n resolveHostPlugins,\n seedDrives,\n type BootCheckContext,\n type BootIssue,\n type DriveSeederClient,\n type ResolvedDrive,\n type ResolvedPlugin,\n type RunnerContext,\n type RunnerHandle,\n} from \"@powerhousedao/host-core\";\nimport path from \"node:path\";\nimport {\n memberEnvOf,\n memberSwitchboardConfig,\n memberSwitchboardConfigSchema,\n missingPostgresUrl,\n prepareMemberStorage,\n reactorBlockConflicts,\n readModelAsReactorStore,\n switchboardDevMode,\n} from \"./member-config.js\";\nimport { z } from \"zod\";\nimport { classicSwitchboardArgs } from \"../services/classic-args.js\";\nimport {\n inspectorProgressSource,\n startProgressDisplay,\n} from \"../services/run/catch-up-progress.js\";\nimport type { SwitchboardArgs } from \"../services/classic-args.js\";\n\n/**\n * BRIDGE runner for Switchboard hosts (uniform-runners phase 0): maps a\n * hosts/switchboard/host.js definition onto the SAME `startSwitchboard`\n * service the classic command calls. `run` = production loaders, `dev` =\n * Vite package loader (worker pools refused by the server, as always).\n */\n\nexport const kind = \"reactor\";\n\n/** The switchboard host: the host-core reactor host with every runner option\n * this module reads declared (strict: an unknown runner key fails).\n * `config.switchboard` is this member's own switchboard config (auth,\n * inspection, workers, ...); a key the reactor block also sets is refused.\n * One definition, two schemas: `declaredHostSchema` (token-able fields take\n * output tokens; types host files) and `hostSchema` (resolved; checked\n * right before the verb). */\nconst schemas = defineHostSchemas((s) =>\n s.reactorHostSchema\n .extend({\n runner: s.runnerBaseSchema\n .extend({\n /** 0 binds a port the OS picks; `origin` reports it. */\n port: z.number().int().min(0).max(65535).optional(),\n /** Dev mode without the `dev` verb (the Vite package loader). */\n dev: z.boolean().optional(),\n /** The project package output dir `build` writes (default \"dist\"). */\n outDir: z.string().min(1).optional(),\n })\n .strict(),\n config: z\n .strictObject({ switchboard: memberSwitchboardConfigSchema.optional() })\n .optional(),\n })\n .superRefine((host, ctx) => {\n for (const message of reactorBlockConflicts(host)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"config\", \"switchboard\"],\n message,\n });\n }\n }),\n);\nexport const declaredHostSchema = schemas.declaredHostSchema;\nexport const hostSchema = schemas.hostSchema;\n\n/** What a switchboard host.js author writes. */\nexport type SwitchboardHost = z.input<typeof declaredHostSchema>;\n/** What a verb receives (defaults applied). */\nexport type SwitchboardHostParsed = z.output<typeof hostSchema>;\n\n/** One drive the switchboard serves: its document id and its URL. */\nexport const switchboardDriveOutputSchema = z.strictObject({\n id: z.string().min(1),\n url: z.url(),\n});\n\n/** What a started switchboard produces. `origin` carries the port the server\n * actually bound. `drives` is keyed by the DECLARED slug (a `projectHash:\n * true` drive is reachable as `vetra`, its URL uses the hashed slug it is\n * served under) and includes plugin-created drives (e.g. `workflows`) and\n * the server's implicit default drive. `endpoints.mcp` is present when MCP\n * is mounted. */\nexport const outputsSchema = z.strictObject({\n origin: z.url(),\n endpoints: z.strictObject({\n graphql: z.url(),\n mcp: z.url().optional(),\n }),\n drives: z.record(z.string(), switchboardDriveOutputSchema),\n});\nexport type SwitchboardOutputs = z.infer<typeof outputsSchema>;\n\ndeclare global {\n interface PHHostRunners {\n \"@powerhousedao/ph-cli/runners/switchboard\": {\n host: SwitchboardHost;\n outputs: SwitchboardOutputs;\n };\n }\n}\n\n/** The classic arg shape with the one switch a composition may leave unset. */\nexport type SwitchboardRunnerArgs = Omit<SwitchboardArgs, \"mcp\"> & {\n mcp: boolean | undefined;\n};\n\n/**\n * Start from the classic `ph switchboard` args (parsed by the classic\n * definitions, no flags) and overlay ONLY the keys the host file owns. Every\n * other key — including the ones the classic command carries as `undefined`,\n * such as `dbPath` — reaches the service exactly as on the classic path. No\n * cast: a key the classic shape has and this object lacks is a type error.\n */\nasync function toSwitchboardArgs(\n host: SwitchboardHostParsed,\n devMode: boolean,\n composed: boolean,\n): Promise<SwitchboardRunnerArgs> {\n const classic = await classicSwitchboardArgs();\n const runner = host.runner;\n return {\n ...classic,\n port: runner.port ?? classic.port,\n dev: switchboardDevMode(devMode, runner) ? true : classic.dev,\n // A declared composition owns the carved switches (R2): the mcp plugin's\n // presence sets it, its absence must deactivate. Classic path: classic.\n mcp: composed ? undefined : classic.mcp,\n };\n}\n\n/** The drive the switchboard service creates by default\n * (services/switchboard.ts `defaultSwitchboardOptions.drive`). */\nconst DEFAULT_DRIVE_SLUG = \"powerhouse\";\n\n/** The `<slug>` of the server-reported `…/d/<slug>` default drive URL. */\nfunction defaultDriveSlug(url: string | undefined): string {\n const match = url ? /\\/d\\/([^/?#]+)\\/?$/.exec(url) : null;\n return match ? decodeURIComponent(match[1]) : DEFAULT_DRIVE_SLUG;\n}\n\n/** A drive in the plan with the slug its declaration used (a `projectHash:\n * true` drive is served under its hashed slug; outputs key it by this one). */\ninterface PlannedDrive {\n declaredSlug: string;\n drive: ResolvedDrive;\n}\n\n/**\n * The drives the composition's plugins contribute, resolved and in plan\n * order, minus the slugs the host declares itself (mergeDrivePlan: the host\n * file wins). A contribution that is not a valid drive declaration fails the\n * boot naming the plugin.\n */\nfunction pluginDrives(\n projectRoot: string,\n hostDrives: readonly PlannedDrive[],\n composition: readonly ResolvedPlugin[] | undefined,\n where: string,\n): PlannedDrive[] {\n if (!composition) return [];\n const contributed = composition.flatMap((resolved) => {\n const drives = resolved.plugin.contributions?.drives ?? [];\n if (drives.length === 0) return [];\n const parsed = drivesSchema.safeParse(drives);\n if (!parsed.success) {\n throw new Error(\n `${where}: plugin \"${resolved.plugin.name}\" contributes an invalid drive declaration:\\n${z.prettifyError(parsed.error)}`,\n );\n }\n return parsed.data.map((declaration) => ({\n declaration,\n source: resolved.plugin.name,\n }));\n });\n if (contributed.length === 0) return [];\n // served slug -> declared slug, for the outputs' keys\n const declaredSlugs = new Map(\n contributed.map(({ declaration }) => [\n resolveDriveDeclaration(projectRoot, declaration).slug,\n declaration.slug,\n ]),\n );\n const hostSlugs = new Set(hostDrives.map((d) => d.drive.slug));\n return mergeDrivePlan(projectRoot, [], contributed)\n .map((entry) => entry.drive)\n .filter((drive) => !hostSlugs.has(drive.slug))\n .map((drive) => ({\n declaredSlug: declaredSlugs.get(drive.slug) ?? drive.slug,\n drive,\n }));\n}\n\n/** Poll the default drive endpoint until the server answers — the compound's\n * readiness gate: Connect auto-connects the drive on first load, so the drive\n * must answer before the connect member serves (the sidecar's\n * waitForSwitchboard, moved behind the handle contract).\n *\n * The probe is anonymous, and a host with authentication on hides a drive\n * from a caller it refuses (`/d/:drive` answers 404 to anyone who may not\n * read it, 401 under the authenticated-caller floor). Those answers prove\n * the server is listening but not whether the drive exists, so `served`,\n * the reactor's own view of the drive, decides then; without it an\n * ADMIN_ONLY host never passes this gate and the compound tears down after\n * the timeout. */\nexport async function waitForDrive(\n url: string,\n timeoutMs: number,\n served?: () => Promise<boolean>,\n fetchImpl: typeof fetch = fetch,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n const HIDDEN = new Set([401, 403, 404]);\n for (;;) {\n try {\n const res = await fetchImpl(url, { signal: AbortSignal.timeout(3000) });\n if (res.ok) return;\n if (HIDDEN.has(res.status) && served && (await served())) return;\n } catch {\n // not listening yet\n }\n if (Date.now() > deadline) {\n throw new Error(\n `Switchboard drive ${url} did not answer within ${timeoutMs}ms.`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 400));\n }\n}\n\n/** What a started switchboard returns. */\nexport type SwitchboardHandle = RunnerHandle<SwitchboardOutputs>;\n\n/** The slice of the switchboard's reactor client (IReactorClient) the seeder\n * reads: id-or-slug resolution against the read model (live documents). */\ninterface SlugLookupClient {\n resolveIdOrSlug(identifier: string): Promise<string | undefined>;\n}\n\n/**\n * Adapter from the switchboard's reactor client onto the host-core seeder.\n * Seeding is SLUG-keyed: a live drive that already serves the slug — under\n * whatever id (a store from a run that hashed the project path differently,\n * or a hand-made drive) — is the drive, and nothing is created. addDefaultDrive\n * alone only knows ids: with a different id it would try to create a second\n * drive for the slug, and against a deleted document with that id the create\n * fails on every boot.\n */\nfunction seederClient(\n reactor: unknown,\n port: number,\n seededIds: Map<string, string>,\n): DriveSeederClient {\n return {\n findDriveBySlug: async (slug: string) => {\n try {\n const id = await (reactor as SlugLookupClient).resolveIdOrSlug(slug);\n if (id) seededIds.set(slug, id);\n return id || undefined;\n } catch {\n // not found (or ambiguous): seed as declared\n return undefined;\n }\n },\n createDrive: async (drive: ResolvedDrive) => {\n const { ensureDrive } = await import(\"@powerhousedao/switchboard/utils\");\n // One drive that cannot be made must not keep the server from starting\n try {\n await createDeclaredDrive(ensureDrive, reactor, drive, port);\n } catch (error) {\n console.error(\n `The drive \"${drive.slug}\" was not created: ${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n // Its id: the declared one, or the one the reactor generated\n let id: string | undefined;\n try {\n id = await (reactor as SlugLookupClient).resolveIdOrSlug(drive.slug);\n } catch {\n id = undefined;\n }\n seededIds.set(drive.slug, id || drive.id || drive.slug);\n },\n attachRemoteDrive: () => Promise.resolve(), // remotes ride options.remoteDrives\n };\n}\n\n/** A declared local drive, through the switchboard's own default-drive path. */\nasync function createDeclaredDrive(\n ensureDrive: typeof SwitchboardUtils.ensureDrive,\n reactor: unknown,\n drive: ResolvedDrive,\n port: number,\n): Promise<void> {\n await ensureDrive(\n reactor as Parameters<typeof ensureDrive>[0],\n {\n ...(drive.id ? { id: drive.id } : {}),\n ...(drive.documentType ? { documentType: drive.documentType } : {}),\n slug: drive.slug,\n global: { name: drive.name, icon: drive.icon },\n ...(drive.preferredEditor\n ? { preferredEditor: drive.preferredEditor }\n : {}),\n local: {\n availableOffline: drive.availableOffline,\n listeners: [],\n sharingType: drive.sharingType,\n triggers: [],\n },\n } as Parameters<typeof ensureDrive>[1],\n port,\n );\n}\n\nfunction catchUpTopFromEnv(raw: string | undefined): number | undefined {\n const top = Number(raw?.trim() || Number.NaN);\n return Number.isInteger(top) && top >= 0 ? top : undefined;\n}\n\nasync function start(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n devMode: boolean,\n): Promise<SwitchboardHandle> {\n const hostFile = `hosts/${host.name}/host.js`;\n // Split before the server import loads the project .env into the env.\n const env = memberEnvOf(ctx.env);\n prepareMemberStorage(host.reactor, env.shell, hostFile);\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n hostFile,\n );\n if (legacyStore) console.warn(legacyStore.warning);\n const { startSwitchboard } = await import(\"../services/switchboard.js\");\n const entries = host.runner.plugins;\n const entriesDeclared = entries !== undefined;\n const classic = await toSwitchboardArgs(host, devMode, entriesDeclared);\n // powerhouse.config.json `reactor.https` is a default, not a flag: it goes\n // under the member's own config instead of over it.\n const { https } = classic;\n const args = { ...classic, https: undefined };\n // This member's own config, under the args: nothing is written to the\n // process env, so compound members do not see each other's settings.\n const memberConfig = await memberSwitchboardConfig(host, env, {\n pluginHost: entriesDeclared,\n defaults: https === undefined ? {} : { server: { https } },\n });\n const noDatabase = missingPostgresUrl(host.reactor, memberConfig, hostFile);\n if (noDatabase) throw new Error(noDatabase);\n\n // R2 step 2: a declared composition activates the plugin pipeline — the\n // runner resolves the entries against the PROJECT dependency tree and\n // `features.pluginHost` drives server-side activation. No plugins key =\n // classic path.\n let pluginComposition;\n if (entries !== undefined) {\n pluginComposition = await resolveHostPlugins(\n ctx.projectRoot,\n \"switchboard\",\n ctx.verb,\n entries,\n `hosts/${host.name}/host.js`,\n );\n }\n\n // Core drive declarations (reactor.drives): locals seed after boot via the\n // host-core seeder; remotes ride the existing remoteDrives option; the\n // implicit default powerhouse drive is replaced by the declared set.\n const hostDrives: PlannedDrive[] = (host.reactor?.drives ?? []).map(\n (declaration) => ({\n declaredSlug: declaration.slug,\n drive: resolveDriveDeclaration(ctx.projectRoot, declaration),\n }),\n );\n // Plugin-contributed drives (e.g. the workflows plugin's Workflows drive)\n // join the plan after the host's own: a host declaration with the same slug\n // wins, and the host's drives stay first (the first local one is the\n // readiness gate and the compound's primary drive).\n const contributedDrives = pluginDrives(\n ctx.projectRoot,\n hostDrives,\n pluginComposition,\n `hosts/${host.name}/host.js`,\n );\n const planned = [...hostDrives, ...contributedDrives];\n const resolvedDrives = planned.map((p) => p.drive);\n const remoteDrives = resolvedDrives.flatMap((d) =>\n d.kind === \"remote\" && d.remoteUrl ? [d.remoteUrl] : [],\n );\n const serverArgs = {\n ...args,\n ...(pluginComposition ? { pluginComposition } : {}),\n // Only the HOST's declarations replace the implicit default drive; a\n // contribution adds to whatever the host serves.\n ...(hostDrives.length > 0 ? { drive: undefined } : {}),\n ...(remoteDrives.length > 0 ? { remoteDrives } : {}),\n // A compound member: the compound owns SIGINT/SIGTERM and the exit, and\n // stops this reactor through the handle's shutdown().\n ...(ctx.parent ? { signalHandlers: false } : {}),\n };\n\n // `/ready` waits until the drives seeded below exist.\n let seeded!: { resolve: () => void; reject: (error: unknown) => void };\n const readyAfter = new Promise<void>((resolve, reject) => {\n seeded = { resolve, reject };\n });\n const seeding = async <T>(work: Promise<T>): Promise<T> => {\n try {\n return await work;\n } catch (error) {\n seeded.reject(error);\n throw error;\n }\n };\n const switchboard = await startSwitchboard(\n { ...serverArgs, readyAfter },\n undefined,\n memberConfig,\n );\n // Bars for processor and read-model catch-up, below the server's output;\n // PH_CATCH_UP_PROGRESS=false leaves the output as it was. PH_CATCH_UP_TOP\n // sets how many of the slowest processors they list; 0 hides them.\n const progress =\n switchboard.inspector && process.env.PH_CATCH_UP_PROGRESS !== \"false\"\n ? startProgressDisplay(inspectorProgressSource(switchboard.inspector), {\n stdout: process.stdout,\n stderr: process.stderr,\n top: catchUpTopFromEnv(process.env.PH_CATCH_UP_TOP),\n })\n : undefined;\n // The port the server actually bound (it may move off a taken one).\n const port = switchboard.port;\n const origin = `http://localhost:${port}`;\n const driveUrlOf = (slug: string) => `${origin}/d/${slug}`;\n\n const seededIds = new Map<string, string>();\n const localPlanned = planned.filter((p) => p.drive.kind === \"local\");\n if (localPlanned.length > 0) {\n await seeding(\n seedDrives(\n seederClient(switchboard.reactor, port, seededIds),\n localPlanned.map((p) => p.drive),\n ),\n );\n }\n\n const drives: SwitchboardOutputs[\"drives\"] = {};\n // The server creates its implicit default drive only when nothing replaces\n // it: no host declaration and no remote drive (services/switchboard.ts).\n const localHostDrives = hostDrives.filter((d) => d.drive.kind === \"local\");\n const defaultSlug = defaultDriveSlug(switchboard.defaultDriveUrl);\n if (hostDrives.length === 0 && remoteDrives.length === 0) {\n drives[defaultSlug] = { id: defaultSlug, url: driveUrlOf(defaultSlug) };\n }\n for (const { declaredSlug, drive } of localPlanned) {\n drives[declaredSlug] = {\n id: seededIds.get(drive.slug) ?? drive.id ?? drive.slug,\n url: driveUrlOf(drive.slug),\n };\n }\n\n const slug =\n localHostDrives.length > 0 ? localHostDrives[0].drive.slug : defaultSlug;\n const driveUrl = driveUrlOf(slug);\n\n // No composition declared (the deprecated `reactor.workflows` switch): the\n // workflows flag still seeds the SAME project-hashed drive the classic\n // vetra path seeds. With a composition the workflows PLUGIN declares that\n // drive (contributions.drives above), so nothing implicit happens here.\n if (entries === undefined && switchboard.workflowsEnabled) {\n const { projectDriveId, seedWorkflowsDrive } =\n await import(\"../services/switchboard.js\");\n const url = await seeding(\n seedWorkflowsDrive(switchboard.reactor, port, ctx.projectRoot),\n );\n if (url) {\n drives.workflows = {\n id: projectDriveId(\"workflows\", ctx.projectRoot),\n url,\n };\n }\n }\n seeded.resolve();\n\n // Under an authenticating host the anonymous probe cannot see the drive;\n // the reactor's slug lookup (the seeder's) answers for it.\n const served = async () => {\n try {\n const id = await (\n switchboard.reactor as SlugLookupClient\n ).resolveIdOrSlug(slug);\n return Boolean(id);\n } catch {\n return false;\n }\n };\n const ready = waitForDrive(driveUrl, 180_000, served);\n // A supervisor awaits `ready` and sees the rejection; an unsupervised caller\n // (or a test with the service mocked) must not die of an unhandled one.\n ready.catch(() => undefined);\n const graphql = `${origin}/graphql`;\n // Stops the reactor the server owns, then drains the HTTP server (freeing\n // the port), GraphQL, MCP, attachments, the plugins' onShutdown and the\n // read-model db, then closes the reactor database. SwitchboardReactor\n // memoizes it; standalone, SIGINT/SIGTERM run the same teardown, so a\n // shutdown() during or after a signal joins it instead of draining twice.\n let stopping: Promise<void> | undefined;\n return {\n outputs: outputsSchema.parse({\n origin,\n endpoints: {\n graphql,\n ...(switchboard.mcpEnabled ? { mcp: `${origin}/mcp` } : {}),\n },\n drives,\n }),\n ready,\n shutdown: () => {\n progress?.stop();\n return (stopping ??= switchboard.shutdown());\n },\n };\n}\n\n// The four verbs are orthogonal: each does ONE job.\n// - `run`/`serve`: START the server in production mode (serves the built\n// project package). `serve` is run's alias — a server IS its served stack,\n// and it lets the compound forward one `serve` verb to every member.\n// - `dev`: START the server in dev mode (watch / the Vite package loader).\n// - `build`: PRODUCE the project package this switchboard serves, and start\n// NOTHING. The analog of `ph connect build` on the server side: legacy\n// `ph switchboard build` never existed, but the project still has a build.\n// `build` is what lets a compound forward a single `build` verb to all members\n// (desktop/cli) without the switchboard member failing on an unknown verb.\n\nexport async function run(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, false);\n}\n\nexport const serve = run;\n\nexport const verbs = [\"run\", \"serve\", \"dev\"];\n\nexport async function dev(\n host: SwitchboardHostParsed,\n ctx: RunnerContext,\n): Promise<SwitchboardHandle> {\n return start(host, ctx, true);\n}\n\n/** What the server would refuse at boot for this host, `ctx.verb` and `ctx.env` (`ph host check`). */\nexport async function checkBoot(\n host: SwitchboardHostParsed,\n ctx: BootCheckContext,\n): Promise<BootIssue[]> {\n // As `start` splits it: the project .env sits under the host file.\n const env = memberEnvOf(ctx.env, ctx.projectRoot);\n const issues: BootIssue[] = protocolConflicts(\n host.reactor?.protocol,\n env.shell,\n ctx.file,\n ).map((message) => ({ path: \"reactor.protocol\", message }));\n const legacyStore = readModelAsReactorStore(\n host.reactor,\n env.shell,\n ctx.file,\n );\n if (legacyStore) {\n issues.push({ path: \"reactor.backends\", message: legacyStore.warning });\n }\n const { getConfig } = await import(\"@powerhousedao/config/node\");\n const { switchboardBootFactsOf, switchboardBootIssues } =\n await import(\"@powerhousedao/switchboard/boot\");\n let config;\n try {\n // As `start` builds it; an env parse error becomes the issue.\n config = await memberSwitchboardConfig(host, env, {\n pluginHost: host.runner.plugins !== undefined,\n });\n } catch (error) {\n issues.push({\n path: \"\",\n message: error instanceof Error ? error.message : String(error),\n });\n return issues;\n }\n const noDatabase = missingPostgresUrl(host.reactor, config, ctx.file);\n if (noDatabase) {\n issues.push({ path: \"reactor.backends\", message: noDatabase });\n }\n const facts = await switchboardBootFactsOf(config, {\n // As the `dev` verb starts it.\n dev: switchboardDevMode(ctx.verb === \"dev\", host.runner),\n configuredRenown: getConfig(\n path.join(ctx.projectRoot, \"powerhouse.config.json\"),\n ).auth?.renown,\n });\n for (const message of switchboardBootIssues(facts)) {\n issues.push({ path: \"\", message });\n }\n return issues;\n}\n"],"names":[],"mappings":";;;;;;;;;AAMA,MAAM,KAAK;AAEX,SAAS,KAAK,OAAuB;CACnC,OAAO,SAAS,OAAO,KACnB,IAAI,SAAS,OAAO,IAAA,CAAK,QAAQ,CAAC,EAAE,OACpC,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE;AAChC;AAEA,SAAS,KAAK,UAAiC;CAC7C,IAAI,aAAa,MAAM,OAAO;CAC9B,MAAM,UAAU,KAA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IAAI;CACJ,IAAI;EAEF,SAAS,MAAM,wBAAwB,MAAM,KAAK,EAChD,YAAY,KAAK,OAAO,YAAY,KAAA,EACtC,CAAC;CACH,SAAS,OAAO;EACd,OAAO,KAAK;GACV,MAAM;GACN,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC;EACD,OAAO;CACT;CACA,MAAM,aAAa,mBAAmB,KAAK,SAAS,QAAQ,IAAI,IAAI;CACpE,IAAI,YACF,OAAO,KAAK;EAAE,MAAM;EAAoB,SAAS;CAAW,CAAC;CAE/D,MAAM,QAAQ,MAAM,uBAAuB,QAAQ;EAEjD,KAAK,mBAAmB,IAAI,SAAS,OAAO,KAAK,MAAM;EACvD,kBAAkB,UAChB,KAAK,KAAK,IAAI,aAAa,wBAAwB,CACrD,CAAC,CAAC,MAAM;CACV,CAAC;CACD,KAAK,MAAM,WAAW,sBAAsB,KAAK,GAC/C,OAAO,KAAK;EAAE,MAAM;EAAI;CAAQ,CAAC;CAEnC,OAAO;AACT","debug_id":"22235455-173a-50c8-ac05-c56d3ed43f16"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { ConnectMiddleware, ConnectServeOverride, PRECOMPRESS_EXTENSIONS, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
|
|
1
|
+
import { a as cacheHeaders, c as overrideFromEnv, d as previewCacheControl, f as resolvePreviewBase, h as stripBase, i as assertConnectBuild, l as patchCspScriptSrc, m as shellSwapFor, n as ConnectServeOverride, o as connectBaseOf, p as serveOverrideStep, r as PRECOMPRESS_EXTENSIONS, s as isProxiedRequest, t as ConnectMiddleware, u as precompressedAssets } from "../connect-serve-COWXf_41.mjs";
|
|
2
|
+
export { ConnectMiddleware, ConnectServeOverride, PRECOMPRESS_EXTENSIONS, assertConnectBuild, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
|
|
3
3
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { PRECOMPRESS_EXTENSIONS, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
|
|
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]="
|
|
4
|
-
//# debugId=
|
|
1
|
+
import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, l as previewCacheControl, n as assertConnectBuild, o as overrideFromEnv, p as stripBase, r as cacheHeaders, s as patchCspScriptSrc, t as PRECOMPRESS_EXTENSIONS, u as resolvePreviewBase } from "../connect-serve-1WAi0KJL.mjs";
|
|
2
|
+
export { PRECOMPRESS_EXTENSIONS, assertConnectBuild, cacheHeaders, connectBaseOf, isProxiedRequest, overrideFromEnv, patchCspScriptSrc, precompressedAssets, previewCacheControl, resolvePreviewBase, serveOverrideStep, shellSwapFor, stripBase };
|
|
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]="c740d281-162b-5921-8086-fae159dcfaa6")}catch(e){}}();
|
|
4
|
+
//# debugId=c740d281-162b-5921-8086-fae159dcfaa6
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ConnectPreviewArgs } from "../classic-args-Dm0_3O5p.mjs";
|
|
2
|
-
import { n as ConnectServeOverride } from "../connect-serve-
|
|
2
|
+
import { n as ConnectServeOverride } from "../connect-serve-COWXf_41.mjs";
|
|
3
3
|
//#region src/services/connect-server.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Serves a built Connect with what a running app has anyway. The other way to
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-server.d.mts","names":[],"sources":["../../src/services/connect-server.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"connect-server.d.mts","names":[],"sources":["../../src/services/connect-server.ts"],"mappings":";;;;;;;;;;iBAqCiB;EACf;IAAgB;IAAiB;;EACjC,SAAS;;;wBAIK,cAAc;wBAsMR,iBACpB,MAAM,oBACN,gBAAgB,sBAChB,oBAEE;;EAGA;IAED,QAAQ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { a as
|
|
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]="5e8d8724-35d4-59a8-b0be-fd13032d99f5")}catch(e){}}();
|
|
3
|
+
import { a as isProxiedRequest, c as precompressedAssets, d as serveOverrideStep, f as shellSwapFor, i as connectBaseOf, n as assertConnectBuild, o as overrideFromEnv, r as cacheHeaders } from "../connect-serve-1WAi0KJL.mjs";
|
|
4
4
|
import { isHtmlNavigation } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
@@ -178,6 +178,7 @@ function listen(server, port, host, strictPort) {
|
|
|
178
178
|
async function runConnectServer(args, serveOverride, dirname = process.cwd(), { proxy } = {}) {
|
|
179
179
|
serveOverride ??= overrideFromEnv();
|
|
180
180
|
const outDir = path.resolve(dirname, args.outDir);
|
|
181
|
+
assertConnectBuild(args.outDir, outDir, dirname);
|
|
181
182
|
const base = connectBaseOf(args, outDir, dirname);
|
|
182
183
|
const target = proxy ? new URL(new URL(proxy).origin) : void 0;
|
|
183
184
|
const server = createServer(inOrder([
|
|
@@ -215,4 +216,4 @@ async function runConnectServer(args, serveOverride, dirname = process.cwd(), {
|
|
|
215
216
|
export { isAllowedHost, runConnectServer };
|
|
216
217
|
|
|
217
218
|
//# sourceMappingURL=connect-server.mjs.map
|
|
218
|
-
//# debugId=
|
|
219
|
+
//# debugId=5e8d8724-35d4-59a8-b0be-fd13032d99f5
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-server.mjs","sources":["../../src/services/connect-server.ts"],"sourcesContent":["import { isHtmlNavigation } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { existsSync } from \"node:fs\";\nimport {\n createServer,\n request as httpRequest,\n type IncomingMessage,\n type Server,\n type ServerResponse,\n} from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport net, { type Socket } from \"node:net\";\nimport path from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport tls from \"node:tls\";\nimport sirv from \"sirv\";\nimport type { ConnectPreviewArgs } from \"./classic-args.js\";\nimport {\n cacheHeaders,\n connectBaseOf,\n isProxiedRequest,\n overrideFromEnv,\n precompressedAssets,\n serveOverrideStep,\n shellSwapFor,\n type ConnectMiddleware,\n type ConnectServeOverride,\n} from \"./connect-serve.js\";\n\n/**\n * Serves a built Connect with what a running app has anyway. The other way to\n * serve it is `vite preview`, which brings a bundler, Tailwind and Babel to a\n * job that reads files from a folder. This does what that does for a build,\n * step for step, apart from compressing responses: this server's traffic stays\n * on the computer, where compressing is only slower.\n */\n\nexport interface ConnectServer {\n resolvedUrls: { local: string[]; network: string[] };\n close(): Promise<void>;\n}\n\n/** The hosts a browser may reach this by: a rebinding attack needs a name. */\nexport function isAllowedHost(hostHeader: string | undefined): boolean {\n if (!hostHeader) return false;\n const name = hostHeader.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\");\n return (\n name === \"localhost\" || name.endsWith(\".localhost\") || net.isIP(name) !== 0\n );\n}\n\nconst hostCheck: ConnectMiddleware = (req, res, next) => {\n if (isAllowedHost(req.headers.host)) {\n next();\n return;\n }\n res.writeHead(403, { \"content-type\": \"text/plain\" });\n res.end(`This host (${req.headers.host}) is not allowed.`);\n};\n\nconst openCors: ConnectMiddleware = (req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (req.method !== \"OPTIONS\") {\n next();\n return;\n }\n res.setHeader(\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,PUT,PATCH,POST,DELETE\",\n );\n const asked = req.headers[\"access-control-request-headers\"];\n if (asked) {\n res.setHeader(\"Access-Control-Allow-Headers\", asked);\n res.setHeader(\"Vary\", \"Access-Control-Request-Headers\");\n }\n res.writeHead(204, { \"Content-Length\": \"0\" });\n res.end();\n};\n\n/** Requests outside the base: the root goes to it, anything else is a 404. */\nfunction baseStep(base: string): ConnectMiddleware {\n return (req, res, next) => {\n if (base === \"/\") {\n next();\n return;\n }\n const url = req.url ?? \"/\";\n const pathname = url.split(\"?\")[0];\n if (pathname.startsWith(base)) {\n req.url = `/${url.slice(base.length)}`;\n next();\n return;\n }\n if (pathname === \"/\" || pathname === \"/index.html\") {\n res.writeHead(302, { Location: base + url.slice(pathname.length) });\n res.end();\n return;\n }\n res.writeHead(404, { \"content-type\": \"text/plain\" });\n res.end(`This server's base is ${base}.`);\n };\n}\n\n/** Sends the switchboard's paths to it, leaving the Host header as the browser\n * sent it: the switchboard builds the URLs it hands out from that. */\nfunction proxyStep(target: URL): ConnectMiddleware {\n const request = target.protocol === \"https:\" ? httpsRequest : httpRequest;\n return (req, res, next) => {\n const url = req.url ?? \"/\";\n if (!isProxiedRequest(url.split(\"?\")[0], req.headers.accept)) {\n next();\n return;\n }\n const upstream = request(\n {\n hostname: target.hostname,\n port: target.port,\n method: req.method,\n path: url,\n headers: req.headers,\n },\n (answer) => {\n res.writeHead(answer.statusCode ?? 502, answer.headers);\n answer.pipe(res);\n },\n );\n upstream.on(\"error\", () => {\n if (!res.headersSent) res.writeHead(502);\n res.end();\n });\n // A subscription stream ends when its reader leaves.\n res.on(\"close\", () => upstream.destroy());\n req.pipe(upstream);\n };\n}\n\nfunction upgradeRequestOf(req: IncomingMessage): string {\n const headers: string[] = [];\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n headers.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);\n }\n return `${req.method} ${req.url} HTTP/${req.httpVersion}\\r\\n${headers.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n}\n\n/** GraphQL's subscriptions. Its one websocket path, as a socket joined to the\n * same socket at the switchboard: everything past the handshake is theirs. */\nfunction proxyUpgrade(\n target: URL,\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n) {\n const pathname = (req.url ?? \"/\").split(\"?\")[0];\n const isGraphql = pathname === \"/graphql\" || pathname.startsWith(\"/graphql/\");\n if (!isGraphql || !isAllowedHost(req.headers.host)) {\n socket.destroy();\n return;\n }\n const secure = target.protocol === \"https:\";\n const port = Number(target.port || (secure ? 443 : 80));\n const upstream: Socket = secure\n ? tls.connect(port, target.hostname, { servername: target.hostname })\n : net.connect(port, target.hostname);\n const drop = () => {\n upstream.destroy();\n socket.destroy();\n };\n upstream.once(secure ? \"secureConnect\" : \"connect\", () => {\n upstream.write(upgradeRequestOf(req));\n if (head.length > 0) upstream.write(head);\n upstream.pipe(socket);\n socket.pipe(upstream);\n });\n upstream.on(\"error\", drop);\n upstream.on(\"close\", drop);\n socket.on(\"error\", drop);\n socket.on(\"close\", drop);\n}\n\n/** The file for a request: as it is, or for a page, the app that routes it. */\nfunction assetsStep(outDir: string): ConnectMiddleware {\n const serve = sirv(outDir, { dev: true, etag: true, extensions: [] });\n return (req, res, next) => {\n serve(req, res, () => {\n const accept = req.headers.accept;\n const wantsPage =\n (req.method === \"GET\" || req.method === \"HEAD\") &&\n (!accept || isHtmlNavigation(accept) || accept.includes(\"*/*\"));\n if (!wantsPage || !existsSync(path.join(outDir, \"index.html\"))) {\n next();\n return;\n }\n req.url = \"/index.html\";\n serve(req, res, next);\n });\n };\n}\n\nfunction inOrder(steps: readonly ConnectMiddleware[]) {\n return (req: IncomingMessage, res: ServerResponse) => {\n const run = (index: number) => {\n const step = steps.at(index);\n if (index >= steps.length || !step) {\n res.writeHead(404);\n res.end();\n return;\n }\n step(req, res, () => run(index + 1));\n };\n run(0);\n };\n}\n\n/** Binds `port`, or under no `strictPort` the next one free. */\nfunction listen(\n server: Server,\n port: number,\n host: string | undefined,\n strictPort: boolean | undefined,\n): Promise<number> {\n return new Promise((resolve, reject) => {\n const attempt = (candidate: number) => {\n const onError = (error: NodeJS.ErrnoException) => {\n server.off(\"listening\", onListening);\n if (error.code !== \"EADDRINUSE\") reject(error);\n else if (strictPort) {\n reject(new Error(`Port ${candidate} is already in use`));\n } else attempt(candidate + 1);\n };\n const onListening = () => {\n server.off(\"error\", onError);\n resolve(candidate);\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(candidate, host);\n };\n attempt(port);\n });\n}\n\nexport async function runConnectServer(\n args: ConnectPreviewArgs,\n serveOverride?: ConnectServeOverride,\n dirname = process.cwd(),\n {\n proxy,\n }: {\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n } = {},\n): Promise<ConnectServer> {\n serveOverride ??= overrideFromEnv();\n const outDir = path.resolve(dirname, args.outDir);\n const base = connectBaseOf(args, outDir, dirname);\n const target = proxy ? new URL(new URL(proxy).origin) : undefined;\n\n const server = createServer(\n inOrder([\n cacheHeaders(outDir, base),\n precompressedAssets(outDir, base),\n ...(serveOverride\n ? [\n serveOverrideStep(\n outDir,\n serveOverride,\n base,\n shellSwapFor(outDir, serveOverride, base),\n target !== undefined,\n ),\n ]\n : []),\n openCors,\n hostCheck,\n ...(target ? [proxyStep(target)] : []),\n baseStep(base),\n assetsStep(outDir),\n ]),\n );\n\n // Past an upgrade Node stops tracking the socket, so this has to.\n const upgraded = new Set<Duplex>();\n if (target) {\n server.on(\"upgrade\", (req, socket, head) => {\n upgraded.add(socket);\n socket.once(\"close\", () => upgraded.delete(socket));\n proxyUpgrade(target, req, socket, head);\n });\n }\n\n const port = await listen(server, args.port, args.host, args.strictPort);\n const shown = args.host?.includes(\":\") ? `[${args.host}]` : args.host;\n const url = `http://${shown ?? \"localhost\"}:${port}${base}`;\n if (args.printUrls) console.log(` ➜ Local: ${url}`);\n return {\n resolvedUrls: { local: [url], network: [] },\n close: () =>\n new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n server.closeAllConnections();\n for (const socket of upgraded) socket.destroy();\n }),\n };\n}\n"],"names":["request","httpsRequest","httpRequest"],"mappings":";;;;;;;;;;;;;AA0CA,SAAgB,cAAc,YAAyC;CACrE,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,OAAO,WAAW,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE;CACnE,OACE,SAAS,eAAe,KAAK,SAAS,YAAY,KAAK,IAAI,KAAK,IAAI,MAAM;AAE9E;AAEA,MAAM,aAAgC,KAAK,KAAK,SAAS;CACvD,IAAI,cAAc,IAAI,QAAQ,IAAI,GAAG;EACnC,KAAK;EACL;CACF;CACA,IAAI,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;CACnD,IAAI,IAAI,cAAc,IAAI,QAAQ,KAAK,kBAAkB;AAC3D;AAEA,MAAM,YAA+B,KAAK,KAAK,SAAS;CACtD,IAAI,UAAU,+BAA+B,GAAG;CAChD,IAAI,IAAI,WAAW,WAAW;EAC5B,KAAK;EACL;CACF;CACA,IAAI,UACF,gCACA,gCACF;CACA,MAAM,QAAQ,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U,OAAO,QAAQ;EAChD,CAAC;CACL;AACF","debug_id":"3bcc7706-d7f7-5593-89cb-c35f95023e08"}
|
|
1
|
+
{"version":3,"file":"connect-server.mjs","sources":["../../src/services/connect-server.ts"],"sourcesContent":["import { isHtmlNavigation } from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { existsSync } from \"node:fs\";\nimport {\n createServer,\n request as httpRequest,\n type IncomingMessage,\n type Server,\n type ServerResponse,\n} from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport net, { type Socket } from \"node:net\";\nimport path from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport tls from \"node:tls\";\nimport sirv from \"sirv\";\nimport type { ConnectPreviewArgs } from \"./classic-args.js\";\nimport {\n assertConnectBuild,\n cacheHeaders,\n connectBaseOf,\n isProxiedRequest,\n overrideFromEnv,\n precompressedAssets,\n serveOverrideStep,\n shellSwapFor,\n type ConnectMiddleware,\n type ConnectServeOverride,\n} from \"./connect-serve.js\";\n\n/**\n * Serves a built Connect with what a running app has anyway. The other way to\n * serve it is `vite preview`, which brings a bundler, Tailwind and Babel to a\n * job that reads files from a folder. This does what that does for a build,\n * step for step, apart from compressing responses: this server's traffic stays\n * on the computer, where compressing is only slower.\n */\n\nexport interface ConnectServer {\n resolvedUrls: { local: string[]; network: string[] };\n close(): Promise<void>;\n}\n\n/** The hosts a browser may reach this by: a rebinding attack needs a name. */\nexport function isAllowedHost(hostHeader: string | undefined): boolean {\n if (!hostHeader) return false;\n const name = hostHeader.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\");\n return (\n name === \"localhost\" || name.endsWith(\".localhost\") || net.isIP(name) !== 0\n );\n}\n\nconst hostCheck: ConnectMiddleware = (req, res, next) => {\n if (isAllowedHost(req.headers.host)) {\n next();\n return;\n }\n res.writeHead(403, { \"content-type\": \"text/plain\" });\n res.end(`This host (${req.headers.host}) is not allowed.`);\n};\n\nconst openCors: ConnectMiddleware = (req, res, next) => {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (req.method !== \"OPTIONS\") {\n next();\n return;\n }\n res.setHeader(\n \"Access-Control-Allow-Methods\",\n \"GET,HEAD,PUT,PATCH,POST,DELETE\",\n );\n const asked = req.headers[\"access-control-request-headers\"];\n if (asked) {\n res.setHeader(\"Access-Control-Allow-Headers\", asked);\n res.setHeader(\"Vary\", \"Access-Control-Request-Headers\");\n }\n res.writeHead(204, { \"Content-Length\": \"0\" });\n res.end();\n};\n\n/** Requests outside the base: the root goes to it, anything else is a 404. */\nfunction baseStep(base: string): ConnectMiddleware {\n return (req, res, next) => {\n if (base === \"/\") {\n next();\n return;\n }\n const url = req.url ?? \"/\";\n const pathname = url.split(\"?\")[0];\n if (pathname.startsWith(base)) {\n req.url = `/${url.slice(base.length)}`;\n next();\n return;\n }\n if (pathname === \"/\" || pathname === \"/index.html\") {\n res.writeHead(302, { Location: base + url.slice(pathname.length) });\n res.end();\n return;\n }\n res.writeHead(404, { \"content-type\": \"text/plain\" });\n res.end(`This server's base is ${base}.`);\n };\n}\n\n/** Sends the switchboard's paths to it, leaving the Host header as the browser\n * sent it: the switchboard builds the URLs it hands out from that. */\nfunction proxyStep(target: URL): ConnectMiddleware {\n const request = target.protocol === \"https:\" ? httpsRequest : httpRequest;\n return (req, res, next) => {\n const url = req.url ?? \"/\";\n if (!isProxiedRequest(url.split(\"?\")[0], req.headers.accept)) {\n next();\n return;\n }\n const upstream = request(\n {\n hostname: target.hostname,\n port: target.port,\n method: req.method,\n path: url,\n headers: req.headers,\n },\n (answer) => {\n res.writeHead(answer.statusCode ?? 502, answer.headers);\n answer.pipe(res);\n },\n );\n upstream.on(\"error\", () => {\n if (!res.headersSent) res.writeHead(502);\n res.end();\n });\n // A subscription stream ends when its reader leaves.\n res.on(\"close\", () => upstream.destroy());\n req.pipe(upstream);\n };\n}\n\nfunction upgradeRequestOf(req: IncomingMessage): string {\n const headers: string[] = [];\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n headers.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);\n }\n return `${req.method} ${req.url} HTTP/${req.httpVersion}\\r\\n${headers.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n}\n\n/** GraphQL's subscriptions. Its one websocket path, as a socket joined to the\n * same socket at the switchboard: everything past the handshake is theirs. */\nfunction proxyUpgrade(\n target: URL,\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n) {\n const pathname = (req.url ?? \"/\").split(\"?\")[0];\n const isGraphql = pathname === \"/graphql\" || pathname.startsWith(\"/graphql/\");\n if (!isGraphql || !isAllowedHost(req.headers.host)) {\n socket.destroy();\n return;\n }\n const secure = target.protocol === \"https:\";\n const port = Number(target.port || (secure ? 443 : 80));\n const upstream: Socket = secure\n ? tls.connect(port, target.hostname, { servername: target.hostname })\n : net.connect(port, target.hostname);\n const drop = () => {\n upstream.destroy();\n socket.destroy();\n };\n upstream.once(secure ? \"secureConnect\" : \"connect\", () => {\n upstream.write(upgradeRequestOf(req));\n if (head.length > 0) upstream.write(head);\n upstream.pipe(socket);\n socket.pipe(upstream);\n });\n upstream.on(\"error\", drop);\n upstream.on(\"close\", drop);\n socket.on(\"error\", drop);\n socket.on(\"close\", drop);\n}\n\n/** The file for a request: as it is, or for a page, the app that routes it. */\nfunction assetsStep(outDir: string): ConnectMiddleware {\n const serve = sirv(outDir, { dev: true, etag: true, extensions: [] });\n return (req, res, next) => {\n serve(req, res, () => {\n const accept = req.headers.accept;\n const wantsPage =\n (req.method === \"GET\" || req.method === \"HEAD\") &&\n (!accept || isHtmlNavigation(accept) || accept.includes(\"*/*\"));\n if (!wantsPage || !existsSync(path.join(outDir, \"index.html\"))) {\n next();\n return;\n }\n req.url = \"/index.html\";\n serve(req, res, next);\n });\n };\n}\n\nfunction inOrder(steps: readonly ConnectMiddleware[]) {\n return (req: IncomingMessage, res: ServerResponse) => {\n const run = (index: number) => {\n const step = steps.at(index);\n if (index >= steps.length || !step) {\n res.writeHead(404);\n res.end();\n return;\n }\n step(req, res, () => run(index + 1));\n };\n run(0);\n };\n}\n\n/** Binds `port`, or under no `strictPort` the next one free. */\nfunction listen(\n server: Server,\n port: number,\n host: string | undefined,\n strictPort: boolean | undefined,\n): Promise<number> {\n return new Promise((resolve, reject) => {\n const attempt = (candidate: number) => {\n const onError = (error: NodeJS.ErrnoException) => {\n server.off(\"listening\", onListening);\n if (error.code !== \"EADDRINUSE\") reject(error);\n else if (strictPort) {\n reject(new Error(`Port ${candidate} is already in use`));\n } else attempt(candidate + 1);\n };\n const onListening = () => {\n server.off(\"error\", onError);\n resolve(candidate);\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(candidate, host);\n };\n attempt(port);\n });\n}\n\nexport async function runConnectServer(\n args: ConnectPreviewArgs,\n serveOverride?: ConnectServeOverride,\n dirname = process.cwd(),\n {\n proxy,\n }: {\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n } = {},\n): Promise<ConnectServer> {\n serveOverride ??= overrideFromEnv();\n const outDir = path.resolve(dirname, args.outDir);\n assertConnectBuild(args.outDir, outDir, dirname);\n const base = connectBaseOf(args, outDir, dirname);\n const target = proxy ? new URL(new URL(proxy).origin) : undefined;\n\n const server = createServer(\n inOrder([\n cacheHeaders(outDir, base),\n precompressedAssets(outDir, base),\n ...(serveOverride\n ? [\n serveOverrideStep(\n outDir,\n serveOverride,\n base,\n shellSwapFor(outDir, serveOverride, base),\n target !== undefined,\n ),\n ]\n : []),\n openCors,\n hostCheck,\n ...(target ? [proxyStep(target)] : []),\n baseStep(base),\n assetsStep(outDir),\n ]),\n );\n\n // Past an upgrade Node stops tracking the socket, so this has to.\n const upgraded = new Set<Duplex>();\n if (target) {\n server.on(\"upgrade\", (req, socket, head) => {\n upgraded.add(socket);\n socket.once(\"close\", () => upgraded.delete(socket));\n proxyUpgrade(target, req, socket, head);\n });\n }\n\n const port = await listen(server, args.port, args.host, args.strictPort);\n const shown = args.host?.includes(\":\") ? `[${args.host}]` : args.host;\n const url = `http://${shown ?? \"localhost\"}:${port}${base}`;\n if (args.printUrls) console.log(` ➜ Local: ${url}`);\n return {\n resolvedUrls: { local: [url], network: [] },\n close: () =>\n new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n server.closeAllConnections();\n for (const socket of upgraded) socket.destroy();\n }),\n };\n}\n"],"names":["request","httpsRequest","httpRequest"],"mappings":";;;;;;;;;;;;;AA2CA,SAAgB,cAAc,YAAyC;CACrE,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,OAAO,WAAW,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE;CACnE,OACE,SAAS,eAAe,KAAK,SAAS,YAAY,KAAK,IAAI,KAAK,IAAI,MAAM;AAE9E;AAEA,MAAM,aAAgC,KAAK,KAAK,SAAS;CACvD,IAAI,cAAc,IAAI,QAAQ,IAAI,GAAG;EACnC,KAAK;EACL;CACF;CACA,IAAI,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;CACnD,IAAI,IAAI,cAAc,IAAI,QAAQ,KAAK,kBAAkB;AAC3D;AAEA,MAAM,YAA+B,KAAK,KAAK,SAAS;CACtD,IAAI,UAAU,+BAA+B,GAAG;CAChD,IAAI,IAAI,WAAW,WAAW;EAC5B,KAAK;EACL;CACF;CACA,IAAI,UACF,gCACA,gCACF;CACA,MAAM,QAAQ,IAAI,QAAQ;CAC1B,IAAI,OAAO;EACT,IAAI,UAAU,gCAAgC,KAAK;EACnD,IAAI,UAAU,QAAQ,gCAAgC;CACxD;CACA,IAAI,UAAU,KAAK,EAAE,kBAAkB,IAAI,CAAC;CAC5C,IAAI,IAAI;AACV;;AAGA,SAAS,SAAS,MAAiC;CACjD,QAAQ,KAAK,KAAK,SAAS;EACzB,IAAI,SAAS,KAAK;GAChB,KAAK;GACL;EACF;EACA,MAAM,MAAM,IAAI,OAAO;EACvB,MAAM,WAAW,IAAI,MAAM,GAAG,CAAC,CAAC;EAChC,IAAI,SAAS,WAAW,IA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AAI;EAChC,GAAI,gBACA,CACE,kBACE,QACA,eACA,MACA,aAAa,QAAQ,eAAe,IAAI,GACxC,WAAW,KAAA,CACb,CACF,IACA,CAAC;EACL;EACA;EACA,GAAI,SAAS,CAAC,UAAU,MAAM,CAAC,IAAI,CAAC;EACpC,SAAS,IAAI;EACb,WAAW,MAAM;CACnB,CAAC,CACH;CAGA,MAAM,2BAAW,IAAI,IAAY;CACjC,IAAI,QACF,OAAO,GAAG,YAAY,KAAK,QAAQ,SAAS;EAC1C,SAAS,IAAI,MAAM;EACnB,OAAO,KAAK,eAAe,SAAS,OAAO,MAAM,CAAC;EAClD,aAAa,QAAQ,KAAK,QAAQ,IAAI;CACxC,CAAC;CAGH,MAAM,OAAO,MAAM,OAAO,QAAQ,KAAK,MAAM,KAAK,MAAM,KAAK,UAAU;CAEvE,MAAM,MAAM,WADE,KAAK,MAAM,SAAS,GAAG,IAAI,IAAI,KAAK,KAAK,KAAK,KAAK,SAClC,YAAY,GAAG,OAAO;CACrD,IAAI,KAAK,WAAW,QAAQ,IAAI,iBAAiB,KAAK;CACtD,OAAO;EACL,cAAc;GAAE,OAAO,CAAC,GAAG;GAAG,SAAS,CAAC;EAAE;EAC1C,aACE,IAAI,SAAS,SAAS,WAAW;GAC/B,OAAO,OAAO,UAAW,QAAQ,OAAO,KAAK,IAAI,QAAQ,CAAE;GAC3D,OAAO,oBAAoB;GAC3B,KAAK,MAAM,UAAU,UAAU,OAAO,QAAQ;EAChD,CAAC;CACL;AACF","debug_id":"5e8d8724-35d4-59a8-b0be-fd13032d99f5"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/ph-run",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.95",
|
|
4
4
|
"description": "Runs a project's hosts, with none of the tools that build one",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -72,13 +72,13 @@
|
|
|
72
72
|
"dist"
|
|
73
73
|
],
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@powerhousedao/config": "6.2.3-dev.
|
|
76
|
-
"@powerhousedao/host-core": "6.2.3-dev.
|
|
77
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
78
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
79
|
-
"@powerhousedao/switchboard": "6.2.3-dev.
|
|
75
|
+
"@powerhousedao/config": "6.2.3-dev.95",
|
|
76
|
+
"@powerhousedao/host-core": "6.2.3-dev.95",
|
|
77
|
+
"@powerhousedao/reactor": "6.2.3-dev.95",
|
|
78
|
+
"@powerhousedao/shared": "6.2.3-dev.95",
|
|
79
|
+
"@powerhousedao/switchboard": "6.2.3-dev.95",
|
|
80
80
|
"cmd-ts": "0.15.0",
|
|
81
|
-
"document-model": "6.2.3-dev.
|
|
81
|
+
"document-model": "6.2.3-dev.95",
|
|
82
82
|
"dotenv": "16.4.7",
|
|
83
83
|
"sirv": "^3.0.2",
|
|
84
84
|
"zod": "^4.5.4"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect-serve-0fIQ7xCs.mjs","sources":["../src/services/connect-serve.ts"],"sourcesContent":["import { getConfig } from \"@powerhousedao/config/node\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { deepMerge, normalizeBasePath } from \"@powerhousedao/shared/connect\";\nimport {\n APP_SHELLS_FILE,\n appShellVariant,\n appShellVariantOf,\n readShellPluginsIn,\n swapAppShell,\n withShellAppName,\n type AppShells,\n} from \"@powerhousedao/shared/connect/app-shell\";\nimport {\n isHtmlNavigation,\n isSwitchboardProxyPath,\n} from \"@powerhousedao/shared/connect/origin-placeholder\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport path from \"node:path\";\nimport sirv from \"sirv\";\nimport type { ConnectPreviewArgs } from \"./classic-args.js\";\n\n/**\n * Runtime shaping for a served (built) Connect, desktop shape: the compound\n * projects the live switchboard's drive into the connect member's config, and\n * this override makes the STATIC dist serve it — the built\n * powerhouse.config.json is baked, so without this the drive injection never\n * reaches the SPA. `cspRegistrySync` additionally patches the baked CSP's\n * script-src with the runtime registry (the build bakes the CSP for the\n * registry it was built against; setting the registry at run time breaks that\n * coupling and every package import gets blocked otherwise).\n */\nexport interface ConnectServeOverride {\n connect?: PHConnectRuntimeConfig;\n cspRegistrySync?: boolean;\n /** Overrides the baked top-level packageRegistryUrl in the served config. */\n packageRegistryUrl?: string;\n}\n\n/**\n * The env contract a supervisor can drive the preview with — the same\n * variables the Docker entrypoint and clint's service manager already speak:\n * PH_CONNECT_DEFAULT_DRIVES_URL (comma-separated drive urls, injected into\n * drives.defaultDrives), PH_CONNECT_DRIVES_PRESERVE_STRATEGY, and\n * PH_CONNECT_PACKAGES_REGISTRY (runtime registry: served config + baked-CSP\n * patch). Lets `ph connect preview` replace hand-rolled static servers\n * (clint's connect-server, the ph-win sidecar) without losing injection.\n */\nexport function overrideFromEnv(\n env: Record<string, string | undefined> = process.env,\n): ConnectServeOverride | undefined {\n const drivesUrl = env.PH_CONNECT_DEFAULT_DRIVES_URL;\n const registry = env.PH_CONNECT_PACKAGES_REGISTRY;\n if (!drivesUrl && !registry) return undefined;\n const override: ConnectServeOverride = {};\n if (drivesUrl) {\n override.connect = {\n drives: {\n defaultDrives: drivesUrl\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null })),\n preserveStrategy:\n env.PH_CONNECT_DRIVES_PRESERVE_STRATEGY ?? \"preserve-all\",\n },\n } as PHConnectRuntimeConfig;\n }\n if (registry) {\n override.packageRegistryUrl = registry;\n override.cspRegistrySync = true;\n }\n return override;\n}\n\nfunction mergedConfigBody(\n outDir: string,\n override: ConnectServeOverride,\n): string {\n const file = path.join(outDir, \"powerhouse.config.json\");\n const baked = existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>)\n : {};\n const connect = override.connect\n ? deepMerge(\n (baked.connect ?? {}) as PHConnectRuntimeConfig,\n override.connect,\n )\n : baked.connect;\n return JSON.stringify({\n ...baked,\n connect,\n ...(override.packageRegistryUrl\n ? { packageRegistryUrl: override.packageRegistryUrl }\n : {}),\n });\n}\n\n/**\n * Append the registry origin to the baked CSP's script-src. The attribute\n * value is HTML-escaped (every CSP keyword is `'`-quoted, which contains a\n * semicolon), so decode before touching directives and re-escape after —\n * ported from the ph-win-desktop sidecar, which this path replaces.\n */\nexport function patchCspScriptSrc(html: string, registryUrl: string): string {\n return html.replace(\n /(<meta\\s+http-equiv=\"Content-Security-Policy\"\\s+content=\")([^\"]*)(\")/i,\n (_match, open: string, escaped: string, close: string) => {\n const policy = escaped.replace(/&/g, \"&\").replace(/'/g, \"'\");\n if (policy.includes(registryUrl)) return open + escaped + close;\n const patched = policy.replace(\n /script-src\\s+([^;]*)/i,\n (_directive, sources: string) =>\n `script-src ${sources.trim()} ${registryUrl}`,\n );\n const reEscaped = patched.replace(/&/g, \"&\").replace(/'/g, \"'\");\n return open + reEscaped + close;\n },\n );\n}\n\n// The serve base: an explicit `--base`, else the basePath the dist was built with.\nexport function resolvePreviewBase(\n argBase: string | undefined,\n outDirAbs: string,\n): string | undefined {\n if (argBase && argBase !== \"/\") return normalizeBasePath(argBase);\n try {\n const built = JSON.parse(\n readFileSync(path.join(outDirAbs, \"powerhouse.config.json\"), \"utf8\"),\n ) as { connect?: { app?: { basePath?: unknown } } };\n const basePath = built.connect?.app?.basePath;\n if (typeof basePath === \"string\" && basePath) {\n return normalizeBasePath(basePath);\n }\n } catch {\n // no readable dist config\n }\n return undefined;\n}\n\n// `pathname` relative to the deploy base (\"/\" + rest), or itself when outside it.\nexport function stripBase(pathname: string, base: string): string {\n return base !== \"/\" && pathname.startsWith(base)\n ? `/${pathname.slice(base.length)}`\n : pathname;\n}\n\n/** The steps both Connect servers run, in the order they run them. */\nexport type ConnectMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void;\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nconst HASHED_DIRS = [\"/assets/\", \"/fonts/\", \"/__reactor_worker__/assets/\"];\n\n// Content-addressed output (hashed names, or a `v` query on the worker's), as in the nginx image.\nexport function previewCacheControl(\n pathname: string,\n search: string,\n): string | undefined {\n if (HASHED_DIRS.some((dir) => pathname.startsWith(dir))) return IMMUTABLE;\n if (pathname.startsWith(\"/__vendor__/\")) {\n return /\\/(shared-deps|import-map)\\.js(on)?$/.test(pathname)\n ? \"no-cache\"\n : IMMUTABLE;\n }\n if (pathname.startsWith(\"/__react__/\")) return IMMUTABLE;\n if (pathname.startsWith(\"/__reactor_worker__/\")) {\n return new URLSearchParams(search).has(\"v\") ? IMMUTABLE : \"no-cache\";\n }\n return undefined;\n}\n\nexport function cacheHeaders(outDir: string, base: string): ConnectMiddleware {\n return (req, res, next) => {\n const [rawPath, search = \"\"] = (req.url ?? \"/\").split(\"?\");\n const rel = stripBase(rawPath, base);\n let value = previewCacheControl(rel, search);\n // A cached 404 would outlive the next deploy.\n if (value === IMMUTABLE && !existsSync(path.join(outDir, rel))) {\n value = undefined;\n }\n if (value) res.setHeader(\"Cache-Control\", value);\n next();\n };\n}\n\ntype HtmlTransform = (html: string) => string;\n\n/** The dist's shell for the served config: its composition's variant and its app name. */\nexport function shellSwapFor(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n): HtmlTransform | undefined {\n const composition = override.connect?.composition;\n const renamed = override.connect?.branding?.appName !== undefined;\n if (!composition && !renamed) return undefined;\n const file = path.join(outDir, APP_SHELLS_FILE);\n // The manifest the build copied from the Connect it used.\n const variant =\n composition && appShellVariant(composition, readShellPluginsIn(outDir));\n const shell =\n variant && existsSync(file)\n ? (JSON.parse(readFileSync(file, \"utf8\")) as AppShells)[variant]\n : undefined;\n // The name the app will title itself with: the served (baked + override) config's.\n const appName = (\n JSON.parse(mergedConfigBody(outDir, override)) as {\n connect?: { branding?: { appName?: string } };\n }\n ).connect?.branding?.appName;\n return (html) =>\n shell && appShellVariantOf(html) !== variant\n ? swapAppShell(html, shell, base, appName)\n : withShellAppName(html, appName);\n}\n\n/**\n * Whether a request on a proxying server belongs to the switchboard: its\n * paths go to the proxy, untouched, except a browser navigation under `/d/`\n * (Connect's own drive routes), as switchboardProxy splits them.\n */\nexport function isProxiedRequest(urlPath: string, accept: string | undefined) {\n if (!isSwitchboardProxyPath(urlPath)) return false;\n return !(urlPath.startsWith(\"/d/\") && isHtmlNavigation(accept));\n}\n\nexport function serveOverrideStep(\n outDir: string,\n override: ConnectServeOverride,\n base = \"/\",\n swapShell?: HtmlTransform,\n proxied = false,\n): ConnectMiddleware {\n return (req, res, next) => {\n const urlPath = stripBase((req.url ?? \"/\").split(\"?\")[0], base);\n if (urlPath === \"/powerhouse.config.json\") {\n res.writeHead(200, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(mergedConfigBody(outDir, override));\n return;\n }\n // The switchboard's paths are the proxy's, which runs after this:\n // served the SPA shell instead, /graphql would never reach it.\n if (proxied && isProxiedRequest(urlPath, req.headers.accept)) {\n next();\n return;\n }\n // index.html and extensionless SPA routes get the CSP patch.\n const isHtml =\n urlPath === \"/\" ||\n urlPath.endsWith(\"/index.html\") ||\n !path.extname(urlPath);\n if ((override.cspRegistrySync || swapShell) && isHtml) {\n const file = path.join(outDir, \"index.html\");\n if (existsSync(file)) {\n let html = readFileSync(file, \"utf8\");\n if (override.cspRegistrySync) {\n const merged = JSON.parse(mergedConfigBody(outDir, override)) as {\n packageRegistryUrl?: string;\n };\n const registry = merged.packageRegistryUrl;\n if (registry) html = patchCspScriptSrc(html, registry);\n }\n if (swapShell) html = swapShell(html);\n res.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n res.end(html);\n return;\n }\n }\n next();\n };\n}\n\n/** Extensions whose files have `.gz` siblings. */\nexport const PRECOMPRESS_EXTENSIONS = [\".wasm\", \".data\"] as const;\n\nconst PRECOMPRESSED_TYPES: Record<string, string> = {\n \".wasm\": \"application/wasm\",\n \".data\": \"application/octet-stream\",\n};\n\n// Serves the build's `.gz` siblings of wasm/data, which the main sirv ignores.\nexport function precompressedAssets(\n outDir: string,\n base = \"/\",\n): ConnectMiddleware {\n const serve = sirv(outDir, {\n dev: true,\n etag: true,\n gzip: true,\n extensions: [],\n setHeaders(res, pathname) {\n res.setHeader(\n \"Content-Type\",\n PRECOMPRESSED_TYPES[path.extname(pathname)],\n );\n },\n });\n return (req, res, next) => {\n const url = req.url ?? \"/\";\n const [rawPath, search] = url.split(\"?\");\n const rel = stripBase(rawPath, base);\n // Ranges are byte offsets into the identity body: leave them to the server.\n if (\n !(PRECOMPRESS_EXTENSIONS as readonly string[]).includes(\n path.extname(rel),\n ) ||\n req.headers.range ||\n (base !== \"/\" && rel === rawPath)\n ) {\n next();\n return;\n }\n req.url = search === undefined ? rel : `${rel}?${search}`;\n serve(req, res, () => {\n req.url = url;\n next();\n });\n };\n}\n\n/** The served base: `--base`, else what the dist or the project was built with. */\nexport function connectBaseOf(\n args: Pick<ConnectPreviewArgs, \"connectBasePath\">,\n outDirAbs: string,\n dirname: string,\n): string {\n // Serving a dist needs only its base, not the build's plugin stack.\n const sourceBasePath = getConfig(path.join(dirname, \"powerhouse.config.json\"))\n .connect?.app?.basePath;\n return (\n resolvePreviewBase(args.connectBasePath, outDirAbs) ??\n (sourceBasePath ? normalizeBasePath(sourceBasePath) : \"/\")\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,gBACd,MAA0C,QAAQ,KAChB;CAClC,MAAM,YAAY,IAAI;CACtB,MAAM,WAAW,IAAI;CACrB,IAAI,CAAC,aAAa,CAAC,UAAU,OAAO,KAAA;CACpC,MAAM,WAAiC,CAAC;CACxC,IAAI,WACF,SAAS,UAAU,EACjB,QAAQ;EACN,eAAe,UACZ,MAAM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