@powerhousedao/ph-run 6.2.3-dev.89 → 6.2.3-dev.90
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/classic-args-BYccyIIC.mjs +4 -1
- package/dist/classic-args-BYccyIIC.mjs.map +1 -1
- package/dist/cli.mjs +4 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/connect-plugin-configs-CPRA8hQJ.mjs +4 -1
- package/dist/connect-plugin-configs-CPRA8hQJ.mjs.map +1 -1
- package/dist/connect-serve-0fIQ7xCs.mjs +4 -1
- package/dist/connect-serve-0fIQ7xCs.mjs.map +1 -1
- package/dist/member-config-BcEWRVq4.mjs +4 -1
- package/dist/member-config-BcEWRVq4.mjs.map +1 -1
- package/dist/runners/connect.mjs +4 -1
- package/dist/runners/connect.mjs.map +1 -1
- package/dist/runners/member-config.mjs +2 -0
- package/dist/runners/switchboard.mjs +4 -1
- package/dist/runners/switchboard.mjs.map +1 -1
- package/dist/services/classic-args.mjs +2 -0
- package/dist/services/connect-serve.mjs +2 -0
- package/dist/services/connect-server.mjs +4 -1
- package/dist/services/connect-server.mjs.map +1 -1
- package/dist/services/run/start-run.mjs +2 -0
- package/dist/services/switchboard.mjs +4 -1
- package/dist/services/switchboard.mjs.map +1 -1
- package/dist/start-run-DWn2cVyi.mjs +4 -1
- package/dist/start-run-DWn2cVyi.mjs.map +1 -1
- package/dist/superseded-config-CpHrCuNq.mjs +4 -1
- package/dist/superseded-config-CpHrCuNq.mjs.map +1 -1
- package/package.json +7 -7
|
@@ -1,3 +1,5 @@
|
|
|
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]="25f4ecc9-e49b-546f-9baa-cec84d0ddc4d")}catch(e){}}();
|
|
1
3
|
import { connectPreviewArgs, switchboardArgs } from "@powerhousedao/shared/clis/args";
|
|
2
4
|
import { command, runSafely } from "cmd-ts";
|
|
3
5
|
//#region src/services/classic-args.ts
|
|
@@ -30,4 +32,5 @@ async function classicSwitchboardArgs(argv = []) {
|
|
|
30
32
|
//#endregion
|
|
31
33
|
export { classicSwitchboardArgs as t };
|
|
32
34
|
|
|
33
|
-
//# sourceMappingURL=classic-args-BYccyIIC.mjs.map
|
|
35
|
+
//# sourceMappingURL=classic-args-BYccyIIC.mjs.map
|
|
36
|
+
//# debugId=25f4ecc9-e49b-546f-9baa-cec84d0ddc4d
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"classic-args-BYccyIIC.mjs","
|
|
1
|
+
{"version":3,"file":"classic-args-BYccyIIC.mjs","sources":["../src/services/classic-args.ts"],"sourcesContent":["import type { ParsedCmdResult } from \"@powerhousedao/shared/clis\";\nimport {\n connectPreviewArgs,\n switchboardArgs,\n} from \"@powerhousedao/shared/clis/args\";\nimport { command, runSafely } from \"cmd-ts\";\n\n/**\n * The classic `ph switchboard` argument shape, produced by the SAME cmd-ts\n * definitions the classic command parses — not re-derived by hand. A runner\n * starts from this object and overlays only the keys its host file owns, so\n * every key the classic command carries (including the ones it carries as\n * `undefined`, e.g. `dbPath`) reaches the service exactly as it does on the\n * classic path. The uniform-runners switchboard runner once hand-built a\n * partial object that omitted `dbPath`; the service's then-default\n * `.ph/read-model.db` became both the reactor and the read-model PGlite dir —\n * two instances on one PGDATA (see uniform-runners-plan/legacy-parity-rectification.md).\n */\nconst classicSwitchboard = command({\n name: \"switchboard\",\n args: switchboardArgs,\n handler: (args) => args,\n});\n\nconst classicConnectPreview = command({\n name: \"preview\",\n args: connectPreviewArgs,\n handler: (args) => args,\n});\n\nexport type SwitchboardArgs = ParsedCmdResult<typeof classicSwitchboard>;\nexport type ConnectPreviewArgs = ParsedCmdResult<typeof classicConnectPreview>;\n\nexport async function classicSwitchboardArgs(\n argv: string[] = [],\n): Promise<SwitchboardArgs> {\n const result = await runSafely(classicSwitchboard, argv);\n if (result._tag === \"error\") {\n throw new Error(\n `classic switchboard args did not parse: ${result.error.config.message}`,\n );\n }\n return result.value;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,qBAAqB,QAAQ;CACjC,MAAM;CACN,MAAM;CACN,UAAU,SAAS;AACrB,CAAC;AAE6B,QAAQ;CACpC,MAAM;CACN,MAAM;CACN,UAAU,SAAS;AACrB,CAAC;AAKD,eAAsB,uBACpB,OAAiB,CAAC,GACQ;CAC1B,MAAM,SAAS,MAAM,UAAU,oBAAoB,IAAI;CACvD,IAAI,OAAO,SAAS,SAClB,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,OAAO,SACjE;CAEF,OAAO,OAAO;AAChB","debug_id":"25f4ecc9-e49b-546f-9baa-cec84d0ddc4d"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
|
|
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]="3109cda4-a037-595b-8c8a-1725272205e1")}catch(e){}}();
|
|
2
4
|
import { t as startRun } from "./start-run-DWn2cVyi.mjs";
|
|
3
5
|
import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
|
|
4
6
|
//#region src/cli.ts
|
|
@@ -26,4 +28,5 @@ await main(process.argv.slice(2)).catch((error) => {
|
|
|
26
28
|
//#endregion
|
|
27
29
|
export {};
|
|
28
30
|
|
|
29
|
-
//# sourceMappingURL=cli.mjs.map
|
|
31
|
+
//# sourceMappingURL=cli.mjs.map
|
|
32
|
+
//# debugId=3109cda4-a037-595b-8c8a-1725272205e1
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","
|
|
1
|
+
{"version":3,"file":"cli.mjs","sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { assertNodeVersion } from \"@powerhousedao/shared/clis/utils\";\nimport { startRun } from \"./services/run/start-run.js\";\n\n/**\n * `ph-run run <host> [verb]`: what `ph run` does and nothing else `ph` does, so\n * a packaged app can run a host with none of the tools that build one. It takes\n * `run` as its first word so a supervisor can start either of the two the same\n * way.\n */\nasync function main(args: string[]) {\n assertNodeVersion();\n const debug = args.includes(\"--debug\");\n const [command, host, verb] = args.filter((arg) => arg !== \"--debug\");\n if (command !== \"run\" || !host) {\n throw new Error(\"Usage: ph-run run <host> [verb] [--debug]\");\n }\n await startRun({ host, verb, debug });\n}\n\nawait main(process.argv.slice(2)).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exit(1);\n});\n"],"names":[],"mappings":";;;;;;;;;;;;AAUA,eAAe,KAAK,MAAgB;CAClC,kBAAkB;CAClB,MAAM,QAAQ,KAAK,SAAS,SAAS;CACrC,MAAM,CAAC,SAAS,MAAM,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,SAAS;CACpE,IAAI,YAAY,SAAS,CAAC,MACxB,MAAM,IAAI,MAAM,2CAA2C;CAE7D,MAAM,SAAS;EAAE;EAAM;EAAM;CAAM,CAAC;AACtC;AAEA,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,UAAmB;CAC1D,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;CAC5D,QAAQ,KAAK,CAAC;AAChB,CAAC","debug_id":"3109cda4-a037-595b-8c8a-1725272205e1"}
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="343788e5-4606-5080-b02b-274217034899")}catch(e){}}();
|
|
1
3
|
import { createRequire } from "node:module";
|
|
2
4
|
import { PluginError, entryActiveForVerb, isSchemaLike, normalizePluginEntries } from "@powerhousedao/host-core";
|
|
3
5
|
import path from "node:path";
|
|
@@ -44,4 +46,5 @@ async function loadPluginConfigSchemas(projectRoot) {
|
|
|
44
46
|
//#endregion
|
|
45
47
|
export { validateConnectPluginConfigs };
|
|
46
48
|
|
|
47
|
-
//# sourceMappingURL=connect-plugin-configs-CPRA8hQJ.mjs.map
|
|
49
|
+
//# sourceMappingURL=connect-plugin-configs-CPRA8hQJ.mjs.map
|
|
50
|
+
//# debugId=343788e5-4606-5080-b02b-274217034899
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-plugin-configs-CPRA8hQJ.mjs","
|
|
1
|
+
{"version":3,"file":"connect-plugin-configs-CPRA8hQJ.mjs","sources":["../src/runners/connect-plugin-configs.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n entryActiveForVerb,\n isSchemaLike,\n normalizePluginEntries,\n PluginError,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\n\n/** The zod-only entry Connect publishes with every built-in plugin's entry\n * config schema, keyed by plugin specifier. */\nconst PLUGIN_CONFIGS_ENTRY = \"@powerhousedao/connect/plugin-configs\";\n\n/**\n * Validate the entry configs of the Connect plugins composed for `verb`\n * before Connect boots, so a typo fails at `ph run` naming the plugin and the\n * key instead of at browser boot. The schemas come from the project's own\n * `@powerhousedao/connect/plugin-configs` (resolved from the project tree,\n * like runner and plugin modules); without it, or for a specifier it has no\n * schema for, the browser's own validation stays the only check.\n */\nexport async function validateConnectPluginConfigs(\n projectRoot: string,\n entries: readonly PluginEntryData[] | undefined,\n verb: string,\n where: string,\n): Promise<void> {\n if (entries === undefined || entries.length === 0) return;\n const schemas = await loadPluginConfigSchemas(projectRoot);\n if (!schemas) return;\n for (const entry of normalizePluginEntries(entries, where)) {\n if (!entryActiveForVerb(entry, verb)) continue;\n const schema = schemas[entry.module];\n if (!isSchemaLike(schema)) continue;\n const parsed = schema.safeParse(entry.config);\n if (parsed.success) continue;\n const issues = parsed.error.issues.map((issue) => {\n const key = [\"config\", ...issue.path.map(String)].join(\".\");\n return ` - ${key}: ${issue.message}`;\n });\n throw new PluginError(\n `${where}: config for plugin \"${entry.module}\" is invalid:\\n${issues.join(\"\\n\")}`,\n );\n }\n}\n\nasync function loadPluginConfigSchemas(\n projectRoot: string,\n): Promise<Record<string, unknown> | undefined> {\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let file: string;\n try {\n file = projectRequire.resolve(PLUGIN_CONFIGS_ENTRY);\n } catch {\n return undefined;\n }\n const module = (await import(pathToFileURL(file).href)) as {\n connectPluginConfigSchemas?: unknown;\n };\n const schemas = module.connectPluginConfigSchemas;\n return typeof schemas === \"object\" && schemas !== null\n ? (schemas as Record<string, unknown>)\n : undefined;\n}\n"],"names":[],"mappings":";;;;;;;;;AAaA,MAAM,uBAAuB;;;;;;;;;AAU7B,eAAsB,6BACpB,aACA,SACA,MACA,OACe;CACf,IAAI,YAAY,KAAA,KAAa,QAAQ,WAAW,GAAG;CACnD,MAAM,UAAU,MAAM,wBAAwB,WAAW;CACzD,IAAI,CAAC,SAAS;CACd,KAAK,MAAM,SAAS,uBAAuB,SAAS,KAAK,GAAG;EAC1D,IAAI,CAAC,mBAAmB,OAAO,IAAI,GAAG;EACtC,MAAM,SAAS,QAAQ,MAAM;EAC7B,IAAI,CAAC,aAAa,MAAM,GAAG;EAC3B,MAAM,SAAS,OAAO,UAAU,MAAM,MAAM;EAC5C,IAAI,OAAO,SAAS;EACpB,MAAM,SAAS,OAAO,MAAM,OAAO,KAAK,UAAU;GAEhD,OAAO,OADK,CAAC,UAAU,GAAG,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GACvC,EAAE,IAAI,MAAM;EAC9B,CAAC;EACD,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,MAAM,OAAO,iBAAiB,OAAO,KAAK,IAAI,GAChF;CACF;AACF;AAEA,eAAe,wBACb,aAC8C;CAC9C,MAAM,iBAAiB,cACrB,cAAc,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CAAC,IACxD;CACA,IAAI;CACJ,IAAI;EACF,OAAO,eAAe,QAAQ,oBAAoB;CACpD,QAAQ;EACN;CACF;CAIA,MAAM,WAAU,MAHM,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CAG1B;CACvB,OAAO,OAAO,YAAY,YAAY,YAAY,OAC7C,UACD,KAAA;AACN","debug_id":"343788e5-4606-5080-b02b-274217034899"}
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="ef5981b8-2ad0-5e02-946f-95d7ad4685ac")}catch(e){}}();
|
|
1
3
|
import { isHtmlNavigation, isSwitchboardProxyPath } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
2
4
|
import path from "node:path";
|
|
3
5
|
import { existsSync, readFileSync } from "node:fs";
|
|
@@ -184,4 +186,5 @@ function connectBaseOf(args, outDirAbs, dirname) {
|
|
|
184
186
|
//#endregion
|
|
185
187
|
export { overrideFromEnv as a, previewCacheControl as c, shellSwapFor as d, stripBase as f, isProxiedRequest as i, resolvePreviewBase as l, cacheHeaders as n, patchCspScriptSrc as o, connectBaseOf as r, precompressedAssets as s, PRECOMPRESS_EXTENSIONS as t, serveOverrideStep as u };
|
|
186
188
|
|
|
187
|
-
//# sourceMappingURL=connect-serve-0fIQ7xCs.mjs.map
|
|
189
|
+
//# sourceMappingURL=connect-serve-0fIQ7xCs.mjs.map
|
|
190
|
+
//# debugId=ef5981b8-2ad0-5e02-946f-95d7ad4685ac
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-serve-0fIQ7xCs.mjs","names":[],"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"],"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,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,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SAC7C,KAAK,QAAQ,GAAG,CAClB,KACA,IAAI,QAAQ,SACX,SAAS,OAAO,QAAQ,SACzB;GACA,KAAK;GACL;EACF;EACA,IAAI,MAAM,WAAW,KAAA,IAAY,MAAM,GAAG,IAAI,GAAG;EACjD,MAAM,KAAK,WAAW;GACpB,IAAI,MAAM;GACV,KAAK;EACP,CAAC;CACH;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"}
|
|
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,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,O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SAAgB,oBACd,QACA,OAAO,KACY;CACnB,MAAM,QAAQ,KAAK,QAAQ;EACzB,KAAK;EACL,MAAM;EACN,MAAM;EACN,YAAY,CAAC;EACb,WAAW,KAAK,UAAU;GACxB,IAAI,UACF,gBACA,oBAAoB,KAAK,QAAQ,QAAQ,EAC3C;EACF;CACF,CAAC;CACD,QAAQ,KAAK,KAAK,SAAS;EACzB,MAAM,MAAM,IAAI,OAAO;EACvB,MAAM,CAAC,SAAS,UAAU,IAAI,MAAM,GAAG;EACvC,MAAM,MAAM,UAAU,SAAS,IAAI;EAEnC,IACE,CAAE,uBAA6C,SAC7C,KAAK,QAAQ,GAAG,CAClB,KACA,IAAI,QAAQ,SACX,SAAS,OAAO,QAAQ,SACzB;GACA,KAAK;GACL;EACF;EACA,IAAI,MAAM,WAAW,KAAA,IAAY,MAAM,GAAG,IAAI,GAAG;EACjD,MAAM,KAAK,WAAW;GACpB,IAAI,MAAM;GACV,KAAK;EACP,CAAC;CACH;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":"ef5981b8-2ad0-5e02-946f-95d7ad4685ac"}
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="397b5602-ebe3-50b3-89af-8add364d7c0d")}catch(e){}}();
|
|
1
3
|
import { assertProtocolConsistency, primaryBackend, protocolEnv, reactorBlockToSwitchboardConfig } from "@powerhousedao/host-core";
|
|
2
4
|
import path from "node:path";
|
|
3
5
|
import fs from "node:fs";
|
|
@@ -149,4 +151,5 @@ function switchboardDevMode(devVerb, runner) {
|
|
|
149
151
|
//#endregion
|
|
150
152
|
export { prepareMemberStorage as a, rememberShellNames as c, overlappingKeys as i, switchboardDevMode as l, memberSwitchboardConfig as n, reactorBlockConflicts as o, memberSwitchboardConfigSchema as r, readModelAsReactorStore as s, memberEnvOf as t };
|
|
151
153
|
|
|
152
|
-
//# sourceMappingURL=member-config-BcEWRVq4.mjs.map
|
|
154
|
+
//# sourceMappingURL=member-config-BcEWRVq4.mjs.map
|
|
155
|
+
//# debugId=397b5602-ebe3-50b3-89af-8add364d7c0d
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"member-config-BcEWRVq4.mjs","names":[],"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"],"mappings":";;;;;;;AAgCA,SAAS,WAAW,KAAqC;CACvD,IAAI;EACF,OAAO,OAAO,MAAM,GAAG,aAAa,KAAK,KAAK,KAAK,MAAM,CAAC,CAAC;CAC7D,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAM,kCAAkB,IAAI,QAAqC;;AAGjE,SAAgB,mBAAmB,KAAU,OAA+B;CAC1E,gBAAgB,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC;AACzC;AAIA,SAAS,aAAa,KAA+B;CACnD,IAAI,QAAQ,gBAAgB,IAAI,GAAG;CACnC,IAAI,CAAC,OAAO;EACV,SACG,QAAQ,QAAQ,MAAM,yBAAyB,IAAI,KAAA,MACpD,IAAI,IAAI,OAAO,KAAK,GAAG,CAAC;EAC1B,gBAAgB,IAAI,KAAK,KAAK;CAChC;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,KAAU,MAAc,QAAQ,IAAI,GAAc;CAC5E,MAAM,OAAO,iBAAiB,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,WAAW,GAAG;CAC/D,MAAM,aAAa,aAAa,GAAG;CACnC,MAAM,QAA4C,CAAC;CACnD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,GAAG,GAC5C,IAAI,KAAK,UAAU,KAAA,KAAa,WAAW,IAAI,IAAI,GAAG,MAAM,QAAQ;CAEtE,MAAM,WAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,IAAI,GAC7C,IAAI,CAAC,WAAW,IAAI,IAAI,GAAG,SA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AAS,EAAE,WAAW,KAAK,CAAC;AACnD;;AAGA,SAAgB,mBACd,SACA,QACS;CACT,OAAO,WAAW,OAAO,QAAQ;AACnC"}
|
|
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,KAAqC;CACvD,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AU;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"}
|
package/dist/runners/connect.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
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]="64674726-f10e-55e9-b178-dd7eb54b6e63")}catch(e){}}();
|
|
1
3
|
import { defineHostSchemas, entryActiveForVerb, findDeadConnectConfig, isStructuralMultiReactor, mergeDefaultDrives, normalizePluginEntries, placeConnectDrives, projectDrivesIntoConnect, projectReactorToConnect, refineConnectReactor, remoteBackendUrls, resolveDriveDeclaration } from "@powerhousedao/host-core";
|
|
2
4
|
import { DEFAULT_CONNECT_OUTDIR, DEFAULT_CONNECT_STUDIO_PORT } from "@powerhousedao/shared/clis";
|
|
3
5
|
import { connectConfigSchemaWith } from "@powerhousedao/shared/connect/connect-config-schema";
|
|
@@ -265,4 +267,5 @@ const verbs = ["run", "serve"];
|
|
|
265
267
|
//#endregion
|
|
266
268
|
export { callerOverride, connectHandle, declaredHostSchema, hostSchema, kind, outputsSchema, run, serve, serveWith, startUnderSupervisor, validateComposition, verbs, withoutBuiltImages };
|
|
267
269
|
|
|
268
|
-
//# sourceMappingURL=connect.mjs.map
|
|
270
|
+
//# sourceMappingURL=connect.mjs.map
|
|
271
|
+
//# debugId=64674726-f10e-55e9-b178-dd7eb54b6e63
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.mjs","names":[],"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 and drives (set on `base` above).\n // With none of the three, there is no override: a classic build.\n return host.config !== undefined || composition || declaredDefaults\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"],"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;;;;;;;;;E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;CAC7C,IAAI,aAAa,OAAO,MAAM,GAAG,OAAO,OAAO;CAC/C,OAAO;EAAE,GAAG;EAAQ,UAAU;CAAO;AACvC;;;;;;;AAgBA,eAAsB,UACpB,OACA,MACA,KACuC;CACvC,MAAM,oBAAoB,MAAM,GAAG;CACnC,MAAM,SAAS,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"}
|
|
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 and drives (set on `base` above).\n // With none of the three, there is no override: a classic build.\n return host.config !== undefined || composition || declaredDefaults\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,CA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AAM,EAAE,SAAS,GAAG,GAAG,WAAW;CAClC,IAAI,aAAa,OAAO,IAAI,GAAG,OAAO,OAAO;CAC7C,IAAI,aAAa,OAAO,MAAM,GAAG,OAAO,OAAO;CAC/C,OAAO;EAAE,GAAG;EAAQ,UAAU;CAAO;AACvC;;;;;;;AAgBA,eAAsB,UACpB,OACA,MACA,KACuC;CACvC,MAAM,oBAAoB,MAAM,GAAG;CACnC,MAAM,SAAS,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":"64674726-f10e-55e9-b178-dd7eb54b6e63"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { a as prepareMemberStorage, c as rememberShellNames, i as overlappingKeys, l as switchboardDevMode, n as memberSwitchboardConfig, o as reactorBlockConflicts, r as memberSwitchboardConfigSchema, s as readModelAsReactorStore, t as memberEnvOf } from "../member-config-BcEWRVq4.mjs";
|
|
2
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]="27ff0f7e-1306-5044-9670-e780f06322fc")}catch(e){}}();
|
|
4
|
+
//# debugId=27ff0f7e-1306-5044-9670-e780f06322fc
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="cb68fd63-4333-5361-8c49-9133995b7824")}catch(e){}}();
|
|
1
3
|
import { a as prepareMemberStorage, l as switchboardDevMode, n as memberSwitchboardConfig, o as reactorBlockConflicts, r as memberSwitchboardConfigSchema, s as readModelAsReactorStore, t as memberEnvOf } from "../member-config-BcEWRVq4.mjs";
|
|
2
4
|
import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
|
|
3
5
|
import { defineHostSchemas, drivesSchema, mergeDrivePlan, protocolConflicts, resolveDriveDeclaration, resolveHostPlugins, seedDrives } from "@powerhousedao/host-core";
|
|
@@ -701,4 +703,5 @@ async function checkBoot(host, ctx) {
|
|
|
701
703
|
//#endregion
|
|
702
704
|
export { checkBoot, declaredHostSchema, dev, hostSchema, kind, outputsSchema, run, serve, switchboardDriveOutputSchema, verbs, waitForDrive };
|
|
703
705
|
|
|
704
|
-
//# sourceMappingURL=switchboard.mjs.map
|
|
706
|
+
//# sourceMappingURL=switchboard.mjs.map
|
|
707
|
+
//# debugId=cb68fd63-4333-5361-8c49-9133995b7824
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.mjs","names":[],"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"],"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,MA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;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"}
|
|
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,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AC9B,MAAM,OAAO;CACf,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,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":"cb68fd63-4333-5361-8c49-9133995b7824"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { t as classicSwitchboardArgs } from "../classic-args-BYccyIIC.mjs";
|
|
2
2
|
export { classicSwitchboardArgs };
|
|
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]="1a9483b2-e70b-583b-b445-a26ef3d57a1c")}catch(e){}}();
|
|
4
|
+
//# debugId=1a9483b2-e70b-583b-b445-a26ef3d57a1c
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { a as overrideFromEnv, c as previewCacheControl, d as shellSwapFor, f as stripBase, i as isProxiedRequest, l as resolvePreviewBase, n as cacheHeaders, o as patchCspScriptSrc, r as connectBaseOf, s as precompressedAssets, t as PRECOMPRESS_EXTENSIONS, u as serveOverrideStep } from "../connect-serve-0fIQ7xCs.mjs";
|
|
2
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]="c8aa6bf7-65da-5c76-a5f4-67cf846b9483")}catch(e){}}();
|
|
4
|
+
//# debugId=c8aa6bf7-65da-5c76-a5f4-67cf846b9483
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="3bcc7706-d7f7-5593-89cb-c35f95023e08")}catch(e){}}();
|
|
1
3
|
import { a as overrideFromEnv, d as shellSwapFor, i as isProxiedRequest, n as cacheHeaders, r as connectBaseOf, s as precompressedAssets, u as serveOverrideStep } from "../connect-serve-0fIQ7xCs.mjs";
|
|
2
4
|
import { isHtmlNavigation } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
3
5
|
import path from "node:path";
|
|
@@ -212,4 +214,5 @@ async function runConnectServer(args, serveOverride, dirname = process.cwd(), {
|
|
|
212
214
|
//#endregion
|
|
213
215
|
export { isAllowedHost, runConnectServer };
|
|
214
216
|
|
|
215
|
-
//# sourceMappingURL=connect-server.mjs.map
|
|
217
|
+
//# sourceMappingURL=connect-server.mjs.map
|
|
218
|
+
//# debugId=3bcc7706-d7f7-5593-89cb-c35f95023e08
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-server.mjs","names":["request","httpsRequest","httpRequest"],"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"],"mappings":";;;;;;;;;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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"}
|
|
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,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AAS,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":"3bcc7706-d7f7-5593-89cb-c35f95023e08"}
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import { t as startRun } from "../../start-run-DWn2cVyi.mjs";
|
|
2
2
|
export { startRun };
|
|
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]="4d9babd5-02e7-5e34-b46e-b34d1e0350b5")}catch(e){}}();
|
|
4
|
+
//# debugId=4d9babd5-02e7-5e34-b46e-b34d1e0350b5
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="0abe8f97-362c-5b02-b409-0f8e81033ab0")}catch(e){}}();
|
|
1
3
|
import { DEFAULT_DRIVE_ICON } from "@powerhousedao/shared/clis";
|
|
2
4
|
import { callerOverEnv } from "@powerhousedao/switchboard/config";
|
|
3
5
|
import { switchboardConfigFromEnv } from "@powerhousedao/switchboard/config/env";
|
|
@@ -185,4 +187,5 @@ async function seedWorkflowsDrive(reactor, port, projectRoot) {
|
|
|
185
187
|
//#endregion
|
|
186
188
|
export { POWERHOUSE_DRIVE_ICON, allowLocalhostEgress, defaultSwitchboardOptions, projectDriveId, seedWorkflowsDrive, startSwitchboard, switchboardConfigOf };
|
|
187
189
|
|
|
188
|
-
//# sourceMappingURL=switchboard.mjs.map
|
|
190
|
+
//# sourceMappingURL=switchboard.mjs.map
|
|
191
|
+
//# debugId=0abe8f97-362c-5b02-b409-0f8e81033ab0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.mjs","names":["startSwitchboardServer"],"sources":["../../src/utils/drive-icons.ts","../../src/services/switchboard.ts"],"sourcesContent":["/**\n * Icon for the drives ph-cli creates, inlined as a data URI.\n *\n * This used to be an IPFS URL on a private gateway, which now answers 403 -\n * and a drive stores its icon as a plain URL in document state, so the moment\n * that URL rots every client renders a broken image, for as long as the drive\n * exists. A public gateway would only move the problem: IPFS gateways are\n * frequently overloaded, and a drive icon must not depend on the network at\n * all.\n *\n * A data URI keeps the asset inside this package and inside the drive: no\n * fetch, no gateway, no deploy-base or cross-origin question, and nothing to\n * 404. A few hundred bytes - the size of the string below is the entire cost,\n * paid once in the drive's state.\n *\n * Kept URL-encoded rather than base64 so the markup stays readable and\n * reviewable (`#` must be `%23`; `<`, `>`, `\"` and the CSS braces are legal\n * enough in a data URI but are encoded so the value is also safe to paste\n * into markup).\n */\n\n/** Encodes an SVG for use in a `data:` URI, smaller than base64 and readable. */\nfunction svgDataUri(svg: string): string {\n const compact = svg.replace(/\\s+/g, \" \").trim();\n return `data:image/svg+xml,${compact\n .replace(/%/g, \"%25\")\n .replace(/#/g, \"%23\")\n .replace(/</g, \"%3C\")\n .replace(/>/g, \"%3E\")\n .replace(/\"/g, \"%22\")\n .replace(/\\{/g, \"%7B\")\n .replace(/\\}/g, \"%7D\")}`;\n}\n\n// The Powerhouse mark: four petals on a 64 grid, each a square with one\n// quarter-circle bite taken out of its inner corner.\nconst PETALS = [\n \"M0 4.6C0 2.1 2.1 0 4.6 0h21.2c2.5 0 4.6 2.1 4.6 4.6v2.8c0 12.7-10.3 23-23 23H4.6C2.1 30.4 0 28.4 0 25.8V4.6Z\",\n \"M33.6 56.6c0-12.7 10.3-23 23-23h2.8c2.5 0 4.6 2.1 4.6 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6H38.2c-2.5 0-4.6-2.1-4.6-4.6v-2.8Z\",\n \"M0 38.2c0-2.5 2.1-4.6 4.6-4.6h2.8c12.7 0 23 10.3 23 23v2.8c0 2.5-2.1 4.6-4.6 4.6H4.6C2.1 64 0 61.9 0 59.4V38.2Z\",\n \"M33.6 4.6C33.6 2.1 35.6 0 38.2 0h21.2C61.9 0 64 2.1 64 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6h-2.8c-12.7 0-23-10.3-23-23V4.6Z\",\n];\n\n/** The mark in the light theme's grey. */\nconst LIGHT_FILL = \"#404345\";\n\n/** The mark in the dark theme's grey. */\nconst DARK_FILL = \"#F3F5F7\";\n\n// Drawn in one grey that follows the theme, so the icon sits in the sidebar\n// beside the single-tone `currentcolor` glyphs of the other drives instead of\n// competing with them.\n//\n// A data URI rendered through an `<img>` is its own document and cannot see\n// the host page's `.dark` class, so the theme is read from the embedded\n// document's own color scheme. That is the OS preference by default; the\n// renderer propagates an explicit in-app theme choice by setting\n// `color-scheme` on the `<img>`, which overrides it where the browser\n// supports the propagation.\nconst MARK_SVG = `\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\" width=\"32\" height=\"32\">\n <style>\n path { fill: ${LIGHT_FILL} }\n @media (prefers-color-scheme: dark) { path { fill: ${DARK_FILL} } }\n </style>\n <path d=\"${PETALS[0]}\"/>\n <path d=\"${PETALS[1]}\"/>\n <path d=\"${PETALS[2]}\"/>\n <path d=\"${PETALS[3]}\"/>\n</svg>`;\n\n/** Icon for the drives ph-cli creates. */\nexport const POWERHOUSE_DRIVE_ICON = svgDataUri(MARK_SVG);\n","import type { ResolvedPlugin } from \"@powerhousedao/host-core\";\nimport { DEFAULT_DRIVE_ICON } from \"@powerhousedao/shared/clis\";\nimport {\n callerOverEnv,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport { switchboardConfigFromEnv } from \"@powerhousedao/switchboard/config/env\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport {\n initSwitchboardProcess,\n startSwitchboard as startSwitchboardServer,\n type IdentityOptions,\n type StartServerOptions,\n} from \"@powerhousedao/switchboard/server\";\nimport type { ILogger } from \"document-model\";\nimport { createHash } from \"node:crypto\";\nimport type { SwitchboardArgs } from \"./classic-args.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\n\nexport { POWERHOUSE_DRIVE_ICON };\n\nconst EGRESS_ALLOW_ENV = \"PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES\";\nconst LOCALHOST_ADDRESSES = [\"127.0.0.1/32\", \"::1/128\"];\n\n// Lets pieces reach services on this machine, keeping any addresses already set\nexport function allowLocalhostEgress(env: NodeJS.ProcessEnv = process.env) {\n const current = (env[EGRESS_ALLOW_ENV] ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n const missing = LOCALHOST_ADDRESSES.filter(\n (address) => !current.includes(address),\n );\n if (missing.length > 0)\n env[EGRESS_ALLOW_ENV] = [...current, ...missing].join(\",\");\n}\n\n// No `dbPath` default here: the classic commands always carry the parsed\n// `dbPath` key (undefined without --db-path) and so always overrode it — the\n// server's own split defaults (`.ph/reactor-storage` for the reactor,\n// `.ph/read-storage` for the read model) are the legacy layout. A default\n// here resurfaces for any caller that omits the key and then names ONE dir\n// for both PGlite stores (two writers on one PGDATA).\nexport const defaultSwitchboardOptions = {\n port: 4001,\n drive: {\n id: \"powerhouse\",\n slug: \"powerhouse\",\n global: {\n name: \"Powerhouse\",\n icon: DEFAULT_DRIVE_ICON,\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n mcp: true,\n} satisfies StartServerOptions;\n\nfunction getDefaultVetraSwitchboardOptions(\n vetraDriveId: string,\n): Partial<StartServerOptions> {\n return {\n port: 4001,\n drive: {\n id: vetraDriveId,\n slug: vetraDriveId,\n global: {\n name: \"Vetra\",\n icon: POWERHOUSE_DRIVE_ICON,\n },\n preferredEditor: \"vetra-drive-app\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n };\n}\n\nexport type StartSwitchboardOptions = Omit<SwitchboardArgs, \"mcp\"> & {\n /** A declared composition (R2) leaves this unset: the mcp plugin's presence sets it. */\n mcp?: boolean;\n /** `undefined` suppresses the default drive (declared drives replace it). */\n drive?: StartServerOptions[\"drive\"];\n strictPort?: boolean;\n processorConfig?: Map<string, unknown>;\n /** False under a supervising compound, which owns SIGINT/SIGTERM. */\n signalHandlers?: boolean;\n /** A declared composition (R2), resolved by the runner. */\n pluginComposition?: ResolvedPlugin[];\n /** Drives the caller seeds after start; `/ready` waits for them. */\n readyAfter?: Promise<unknown>;\n};\n\nexport async function startSwitchboard(\n options: StartSwitchboardOptions,\n logger?: ILogger,\n /** The layer under the command's options; default: this process's env. */\n base?: SwitchboardConfigInput,\n) {\n const { readyAfter, ...serverOptions } = options;\n const { config, finalOptions } = switchboardConfigOf(\n serverOptions,\n logger,\n base,\n );\n initSwitchboardProcess(config);\n const reactor = await startSwitchboardServer(config, {\n logger,\n pluginComposition: finalOptions.pluginComposition,\n signalHandlers: finalOptions.signalHandlers,\n readyAfter,\n fatalErrorShutdown: true,\n });\n\n return reactor;\n}\n\n/** The server config a start runs with: the command's options over `base`. */\nexport function switchboardConfigOf(\n options: StartSwitchboardOptions,\n logger?: ILogger,\n base?: SwitchboardConfigInput,\n): {\n config: SwitchboardConfigInput;\n finalOptions: StartServerOptions;\n} {\n const {\n packages: packagesString,\n remoteDrives,\n useVetraDrive,\n vetraDriveId,\n useIdentity,\n keypairPath,\n requireIdentity,\n basePath,\n ...serverOptions\n } = options;\n\n // Vetra and dev mode run against local services\n if (useVetraDrive || serverOptions.dev) allowLocalhostEgress();\n\n // Choose the appropriate default configuration\n const defaultOptions = useVetraDrive\n ? getDefaultVetraSwitchboardOptions(vetraDriveId)\n : defaultSwitchboardOptions;\n\n // Build identity options if enabled\n const identity: IdentityOptions | undefined =\n useIdentity || keypairPath || requireIdentity\n ? {\n keypairPath,\n requireExisting: requireIdentity,\n }\n : undefined;\n\n const packages = packagesString?.split(\",\");\n\n // Only include the default drive if no remote drives are provided\n const finalOptions =\n remoteDrives.length > 0\n ? {\n ...defaultOptions,\n drive: undefined, // Don't create default drive when syncing with remote\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n }\n : {\n ...defaultOptions,\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n };\n\n // The env (or the caller's base) under the command's own options.\n const config = callerOverEnv(\n base ?? switchboardConfigFromEnv(process.env, { logger }),\n configLayerOf(finalOptions, basePath),\n );\n return { config, finalOptions };\n}\n\n/** The keys of the server's options view this command sets, as a config layer. */\nfunction configLayerOf(\n options: StartServerOptions,\n basePath: string | undefined,\n): SwitchboardConfigInput {\n const dbPath = options.dbPath || undefined;\n return {\n server: {\n basePath: basePath || undefined,\n port: options.port,\n strictPort: options.strictPort,\n dev: options.dev,\n https: options.https,\n },\n storage: {\n // `dbPath` names both stores, over the env, as it did as an option.\n readModel: { url: dbPath },\n reactor: { url: dbPath },\n },\n features: { mcp: options.mcp },\n packages: {\n list: options.packages,\n disableLocal: options.disableLocalPackages,\n },\n identity: options.identity,\n drive: options.drive,\n remoteDrives: options.remoteDrives,\n processorConfig: options.processorConfig,\n };\n}\n\n/** A drive's id for this project: the same path always gives the same one. */\nexport function projectDriveId(name: string, projectRoot: string): string {\n const hash = createHash(\"sha256\").update(projectRoot).digest(\"hex\");\n return `${name}-${hash.substring(0, 8)}`;\n}\n\n/** The drive `reactor.workflows` seeds, the same one `ph vetra` does. */\nexport async function seedWorkflowsDrive(\n reactor: Parameters<typeof addDefaultDrive>[0],\n port: number,\n projectRoot: string,\n): Promise<string | null> {\n const driveUrl = await addDefaultDrive(\n reactor,\n {\n id: projectDriveId(\"workflows\", projectRoot),\n slug: \"workflows\",\n global: { name: \"Workflows\" },\n preferredEditor: \"workflow-studio\",\n local: {\n availableOffline: true,\n listeners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AAO,QAAQ;EACjB;EACA,SAAS;GAEP,WAAW,EAAE,KAAK,OAAO;GACzB,SAAS,EAAE,KAAK,OAAO;EACzB;EACA,UAAU,EAAE,KAAK,QAAQ,IAAI;EAC7B,UAAU;GACR,MAAM,QAAQ;GACd,cAAc,QAAQ;EACxB;EACA,UAAU,QAAQ;EAClB,OAAO,QAAQ;EACf,cAAc,QAAQ;EACtB,iBAAiB,QAAQ;CAC3B;AACF;;AAGA,SAAgB,eAAe,MAAc,aAA6B;CAExE,OAAO,GAAG,KAAK,GADF,WAAW,QAAQ,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,OAAO,KACxC,CAAC,CAAC,UAAU,GAAG,CAAC;AACvC;;AAGA,eAAsB,mBACpB,SACA,MACA,aACwB;CAiBxB,OAAO,MAhBgB,gBACrB,SACA;EACE,IAAI,eAAe,aAAa,WAAW;EAC3C,MAAM;EACN,QAAQ,EAAE,MAAM,YAAY;EAC5B,iBAAiB;EACjB,OAAO;GACL,kBAAkB;GAClB,WAAW,CAAC;GACZ,aAAa;GACb,UAAU,CAAC;EACb;CACF,GACA,IACF,KACmB;AACrB"}
|
|
1
|
+
{"version":3,"file":"switchboard.mjs","sources":["../../src/utils/drive-icons.ts","../../src/services/switchboard.ts"],"sourcesContent":["/**\n * Icon for the drives ph-cli creates, inlined as a data URI.\n *\n * This used to be an IPFS URL on a private gateway, which now answers 403 -\n * and a drive stores its icon as a plain URL in document state, so the moment\n * that URL rots every client renders a broken image, for as long as the drive\n * exists. A public gateway would only move the problem: IPFS gateways are\n * frequently overloaded, and a drive icon must not depend on the network at\n * all.\n *\n * A data URI keeps the asset inside this package and inside the drive: no\n * fetch, no gateway, no deploy-base or cross-origin question, and nothing to\n * 404. A few hundred bytes - the size of the string below is the entire cost,\n * paid once in the drive's state.\n *\n * Kept URL-encoded rather than base64 so the markup stays readable and\n * reviewable (`#` must be `%23`; `<`, `>`, `\"` and the CSS braces are legal\n * enough in a data URI but are encoded so the value is also safe to paste\n * into markup).\n */\n\n/** Encodes an SVG for use in a `data:` URI, smaller than base64 and readable. */\nfunction svgDataUri(svg: string): string {\n const compact = svg.replace(/\\s+/g, \" \").trim();\n return `data:image/svg+xml,${compact\n .replace(/%/g, \"%25\")\n .replace(/#/g, \"%23\")\n .replace(/</g, \"%3C\")\n .replace(/>/g, \"%3E\")\n .replace(/\"/g, \"%22\")\n .replace(/\\{/g, \"%7B\")\n .replace(/\\}/g, \"%7D\")}`;\n}\n\n// The Powerhouse mark: four petals on a 64 grid, each a square with one\n// quarter-circle bite taken out of its inner corner.\nconst PETALS = [\n \"M0 4.6C0 2.1 2.1 0 4.6 0h21.2c2.5 0 4.6 2.1 4.6 4.6v2.8c0 12.7-10.3 23-23 23H4.6C2.1 30.4 0 28.4 0 25.8V4.6Z\",\n \"M33.6 56.6c0-12.7 10.3-23 23-23h2.8c2.5 0 4.6 2.1 4.6 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6H38.2c-2.5 0-4.6-2.1-4.6-4.6v-2.8Z\",\n \"M0 38.2c0-2.5 2.1-4.6 4.6-4.6h2.8c12.7 0 23 10.3 23 23v2.8c0 2.5-2.1 4.6-4.6 4.6H4.6C2.1 64 0 61.9 0 59.4V38.2Z\",\n \"M33.6 4.6C33.6 2.1 35.6 0 38.2 0h21.2C61.9 0 64 2.1 64 4.6v21.2c0 2.5-2.1 4.6-4.6 4.6h-2.8c-12.7 0-23-10.3-23-23V4.6Z\",\n];\n\n/** The mark in the light theme's grey. */\nconst LIGHT_FILL = \"#404345\";\n\n/** The mark in the dark theme's grey. */\nconst DARK_FILL = \"#F3F5F7\";\n\n// Drawn in one grey that follows the theme, so the icon sits in the sidebar\n// beside the single-tone `currentcolor` glyphs of the other drives instead of\n// competing with them.\n//\n// A data URI rendered through an `<img>` is its own document and cannot see\n// the host page's `.dark` class, so the theme is read from the embedded\n// document's own color scheme. That is the OS preference by default; the\n// renderer propagates an explicit in-app theme choice by setting\n// `color-scheme` on the `<img>`, which overrides it where the browser\n// supports the propagation.\nconst MARK_SVG = `\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\" width=\"32\" height=\"32\">\n <style>\n path { fill: ${LIGHT_FILL} }\n @media (prefers-color-scheme: dark) { path { fill: ${DARK_FILL} } }\n </style>\n <path d=\"${PETALS[0]}\"/>\n <path d=\"${PETALS[1]}\"/>\n <path d=\"${PETALS[2]}\"/>\n <path d=\"${PETALS[3]}\"/>\n</svg>`;\n\n/** Icon for the drives ph-cli creates. */\nexport const POWERHOUSE_DRIVE_ICON = svgDataUri(MARK_SVG);\n","import type { ResolvedPlugin } from \"@powerhousedao/host-core\";\nimport { DEFAULT_DRIVE_ICON } from \"@powerhousedao/shared/clis\";\nimport {\n callerOverEnv,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport { switchboardConfigFromEnv } from \"@powerhousedao/switchboard/config/env\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport {\n initSwitchboardProcess,\n startSwitchboard as startSwitchboardServer,\n type IdentityOptions,\n type StartServerOptions,\n} from \"@powerhousedao/switchboard/server\";\nimport type { ILogger } from \"document-model\";\nimport { createHash } from \"node:crypto\";\nimport type { SwitchboardArgs } from \"./classic-args.js\";\nimport { POWERHOUSE_DRIVE_ICON } from \"../utils/drive-icons.js\";\n\nexport { POWERHOUSE_DRIVE_ICON };\n\nconst EGRESS_ALLOW_ENV = \"PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES\";\nconst LOCALHOST_ADDRESSES = [\"127.0.0.1/32\", \"::1/128\"];\n\n// Lets pieces reach services on this machine, keeping any addresses already set\nexport function allowLocalhostEgress(env: NodeJS.ProcessEnv = process.env) {\n const current = (env[EGRESS_ALLOW_ENV] ?? \"\")\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n const missing = LOCALHOST_ADDRESSES.filter(\n (address) => !current.includes(address),\n );\n if (missing.length > 0)\n env[EGRESS_ALLOW_ENV] = [...current, ...missing].join(\",\");\n}\n\n// No `dbPath` default here: the classic commands always carry the parsed\n// `dbPath` key (undefined without --db-path) and so always overrode it — the\n// server's own split defaults (`.ph/reactor-storage` for the reactor,\n// `.ph/read-storage` for the read model) are the legacy layout. A default\n// here resurfaces for any caller that omits the key and then names ONE dir\n// for both PGlite stores (two writers on one PGDATA).\nexport const defaultSwitchboardOptions = {\n port: 4001,\n drive: {\n id: \"powerhouse\",\n slug: \"powerhouse\",\n global: {\n name: \"Powerhouse\",\n icon: DEFAULT_DRIVE_ICON,\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n mcp: true,\n} satisfies StartServerOptions;\n\nfunction getDefaultVetraSwitchboardOptions(\n vetraDriveId: string,\n): Partial<StartServerOptions> {\n return {\n port: 4001,\n drive: {\n id: vetraDriveId,\n slug: vetraDriveId,\n global: {\n name: \"Vetra\",\n icon: POWERHOUSE_DRIVE_ICON,\n },\n preferredEditor: \"vetra-drive-app\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\",\n triggers: [],\n },\n },\n };\n}\n\nexport type StartSwitchboardOptions = Omit<SwitchboardArgs, \"mcp\"> & {\n /** A declared composition (R2) leaves this unset: the mcp plugin's presence sets it. */\n mcp?: boolean;\n /** `undefined` suppresses the default drive (declared drives replace it). */\n drive?: StartServerOptions[\"drive\"];\n strictPort?: boolean;\n processorConfig?: Map<string, unknown>;\n /** False under a supervising compound, which owns SIGINT/SIGTERM. */\n signalHandlers?: boolean;\n /** A declared composition (R2), resolved by the runner. */\n pluginComposition?: ResolvedPlugin[];\n /** Drives the caller seeds after start; `/ready` waits for them. */\n readyAfter?: Promise<unknown>;\n};\n\nexport async function startSwitchboard(\n options: StartSwitchboardOptions,\n logger?: ILogger,\n /** The layer under the command's options; default: this process's env. */\n base?: SwitchboardConfigInput,\n) {\n const { readyAfter, ...serverOptions } = options;\n const { config, finalOptions } = switchboardConfigOf(\n serverOptions,\n logger,\n base,\n );\n initSwitchboardProcess(config);\n const reactor = await startSwitchboardServer(config, {\n logger,\n pluginComposition: finalOptions.pluginComposition,\n signalHandlers: finalOptions.signalHandlers,\n readyAfter,\n fatalErrorShutdown: true,\n });\n\n return reactor;\n}\n\n/** The server config a start runs with: the command's options over `base`. */\nexport function switchboardConfigOf(\n options: StartSwitchboardOptions,\n logger?: ILogger,\n base?: SwitchboardConfigInput,\n): {\n config: SwitchboardConfigInput;\n finalOptions: StartServerOptions;\n} {\n const {\n packages: packagesString,\n remoteDrives,\n useVetraDrive,\n vetraDriveId,\n useIdentity,\n keypairPath,\n requireIdentity,\n basePath,\n ...serverOptions\n } = options;\n\n // Vetra and dev mode run against local services\n if (useVetraDrive || serverOptions.dev) allowLocalhostEgress();\n\n // Choose the appropriate default configuration\n const defaultOptions = useVetraDrive\n ? getDefaultVetraSwitchboardOptions(vetraDriveId)\n : defaultSwitchboardOptions;\n\n // Build identity options if enabled\n const identity: IdentityOptions | undefined =\n useIdentity || keypairPath || requireIdentity\n ? {\n keypairPath,\n requireExisting: requireIdentity,\n }\n : undefined;\n\n const packages = packagesString?.split(\",\");\n\n // Only include the default drive if no remote drives are provided\n const finalOptions =\n remoteDrives.length > 0\n ? {\n ...defaultOptions,\n drive: undefined, // Don't create default drive when syncing with remote\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n }\n : {\n ...defaultOptions,\n ...serverOptions,\n remoteDrives,\n identity,\n packages,\n logger,\n };\n\n // The env (or the caller's base) under the command's own options.\n const config = callerOverEnv(\n base ?? switchboardConfigFromEnv(process.env, { logger }),\n configLayerOf(finalOptions, basePath),\n );\n return { config, finalOptions };\n}\n\n/** The keys of the server's options view this command sets, as a config layer. */\nfunction configLayerOf(\n options: StartServerOptions,\n basePath: string | undefined,\n): SwitchboardConfigInput {\n const dbPath = options.dbPath || undefined;\n return {\n server: {\n basePath: basePath || undefined,\n port: options.port,\n strictPort: options.strictPort,\n dev: options.dev,\n https: options.https,\n },\n storage: {\n // `dbPath` names both stores, over the env, as it did as an option.\n readModel: { url: dbPath },\n reactor: { url: dbPath },\n },\n features: { mcp: options.mcp },\n packages: {\n list: options.packages,\n disableLocal: options.disableLocalPackages,\n },\n identity: options.identity,\n drive: options.drive,\n remoteDrives: options.remoteDrives,\n processorConfig: options.processorConfig,\n };\n}\n\n/** A drive's id for this project: the same path always gives the same one. */\nexport function projectDriveId(name: string, projectRoot: string): string {\n const hash = createHash(\"sha256\").update(projectRoot).digest(\"hex\");\n return `${name}-${hash.substring(0, 8)}`;\n}\n\n/** The drive `reactor.workflows` seeds, the same one `ph vetra` does. */\nexport async function seedWorkflowsDrive(\n reactor: Parameters<typeof addDefaultDrive>[0],\n port: number,\n projectRoot: string,\n): Promise<string | null> {\n const driveUrl = await addDefaultDrive(\n reactor,\n {\n id: projectDriveId(\"workflows\", projectRoot),\n slug: \"workflows\",\n global: { name: \"Workflows\" },\n preferredEditor: \"workflow-studio\",\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n },\n port,\n );\n return driveUrl ?? null;\n}\n"],"names":["startSwitchboardServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,WAAW,KAAqB;CAEvC,OAAO,sBADS,IAAI,QAAQ,QAAQ,GAAG,CAAC,CAAC,KACN,CAAC,CACjC,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,MAAM,KAAK,CAAC,CACpB,QAAQ,OAAO,KAAK,CAAC,CACrB,QAAQ,OAAO,KAAK;AACzB;AAIA,MAAM,SAAS;CACb;CACA;CACA;CACA;AACF;;AA+BA,MAAa,wBAAwB,WAAW;;;;;;aAPnC,OAAO,GAAG;aACV,OAAO,GAAG;aACV,OAAO,GAAG;aACV,OAAO,GAAG;OAIiC;;;ACnDxD,MAAM,mBAAmB;AACzB,MAAM,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AkB;GAClB,WAAW,CAAC;GACZ,aAAa;GACb,UAAU,CAAC;EACb;CACF,GACA,IACF,KACmB;AACrB","debug_id":"0abe8f97-362c-5b02-b409-0f8e81033ab0"}
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="a803084f-2032-5068-a22f-4875a78cd073")}catch(e){}}();
|
|
1
3
|
import { ONE_SHOT_VERBS, clearRunRecord, getVerb, isSchemaLike, loadHost, loadProducers, outputRefsOf, probeRun, processResolveEnv, producerOutputsSchemas, readProjectName, readRunRecord, resolveHostOutputs, resolveRunnerModule, runRecordOutputSource, toStartedHandle, validateDeclaredHost, validateHost, writeRunRecord } from "@powerhousedao/host-core";
|
|
2
4
|
//#region src/services/run/start-run.ts
|
|
3
5
|
/**
|
|
@@ -119,4 +121,5 @@ async function publishOutputs(runner, result, target) {
|
|
|
119
121
|
//#endregion
|
|
120
122
|
export { startRun as t };
|
|
121
123
|
|
|
122
|
-
//# sourceMappingURL=start-run-DWn2cVyi.mjs.map
|
|
124
|
+
//# sourceMappingURL=start-run-DWn2cVyi.mjs.map
|
|
125
|
+
//# debugId=a803084f-2032-5068-a22f-4875a78cd073
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-run-DWn2cVyi.mjs","
|
|
1
|
+
{"version":3,"file":"start-run-DWn2cVyi.mjs","sources":["../src/services/run/start-run.ts"],"sourcesContent":["import {\n clearRunRecord,\n getVerb,\n isSchemaLike,\n loadHost,\n loadProducers,\n ONE_SHOT_VERBS,\n outputRefsOf,\n probeRun,\n processResolveEnv,\n producerOutputsSchemas,\n readProjectName,\n readRunRecord,\n resolveHostOutputs,\n resolveRunnerModule,\n runRecordOutputSource,\n toStartedHandle,\n validateDeclaredHost,\n validateHost,\n writeRunRecord,\n type RunnerModule,\n} from \"@powerhousedao/host-core\";\n\nexport interface StartRunArgs {\n host: string;\n verb?: string;\n projectRoot?: string;\n debug?: boolean;\n}\n\n/**\n * `ph run <host> [verb]`: dispatch the verb (default `run`) of the host's\n * declared runner. There is deliberately no type→runner registry — what a\n * host does is written in its own file.\n *\n * The pipeline (typed-host-configs 3.5): declared validation (token shapes,\n * `$output` paths against the producers' outputsSchemas, the runner's\n * declaredHostSchema), the live-instance lock, resolution (`$output` from\n * the producers' live run records, `$env` from this process, the\n * `${userData}` sugar), resolved validation, then the verb with the parsed\n * host. A compound runner gets its declared host: its members resolve their\n * own tokens as they start.\n *\n * A reactor runner that exports `outputsSchema` has its handle's outputs\n * published in a v2 `.ph/run/<name>.json` record once ready; this is the only\n * standalone writer (mastra included). Compounds write their own record with\n * the members in it; one-shot verbs (`build`) return nothing and write none.\n */\nexport async function startRun(args: StartRunArgs): Promise<unknown> {\n // Loading a host loads its plugins, and React settles on its development or\n // production build the first time it's loaded. `vite build` sets NODE_ENV only\n // after that, so a build would run one half of React with the other half's\n // renderer (TypeError: dispatcher.getOwner is not a function).\n if (ONE_SHOT_VERBS.has(args.verb ?? \"run\")) {\n process.env.NODE_ENV ??= \"production\";\n }\n const projectRoot = args.projectRoot ?? process.cwd();\n const loaded = await loadHost(projectRoot, args.host);\n const { warnSupersededConfigKeys } = await import(\"./superseded-config.js\");\n warnSupersededConfigKeys(projectRoot);\n const specifier = loaded.host.runner.module;\n const runner = await resolveRunnerModule(projectRoot, specifier);\n const verb = args.verb ?? \"run\";\n const fn = getVerb(runner, specifier, verb);\n const file = loaded.file;\n if (args.debug) {\n console.log({ host: loaded.host.name, runner: specifier, verb });\n }\n\n if (runner.kind === \"compound\") {\n validateDeclaredHost(runner, specifier, loaded.host, file);\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n\n const projectName = readProjectName(projectRoot);\n const producers = await loadProducers(projectRoot, outputRefsOf(loaded.host));\n validateDeclaredHost(runner, specifier, loaded.host, file, {\n outputsSchemaOf: producerOutputsSchemas(producers),\n });\n const oneShot = ONE_SHOT_VERBS.has(verb);\n if (oneShot) {\n // `build` reads no other host's outputs: no producer needs to run.\n const host = validateHost(runner, specifier, loaded.host, file, {\n tokens: \"allow\",\n });\n return fn(host, { projectRoot, verb, env: process.env });\n }\n const publishes = isSchemaLike(runner.outputsSchema);\n // Before the verb starts anything: a second live instance would take\n // over the first one's record (and clear it on exit).\n if (publishes) assertNotRunning(projectRoot, loaded.host.name, projectName);\n const resolved = resolveHostOutputs(loaded.host, {\n outputs: runRecordOutputSource(projectRoot, {\n consumer: args.host,\n producers,\n projectName,\n }),\n ...processResolveEnv(projectRoot),\n where: `hosts/${args.host}/host.js`,\n });\n const host = validateHost(runner, specifier, resolved, file);\n const result = await fn(host, { projectRoot, verb, env: process.env });\n if (publishes && result !== undefined && result !== null) {\n await publishOutputs(runner, result, {\n projectRoot,\n projectName,\n hostName: loaded.host.name,\n specifier,\n verb,\n });\n }\n return result;\n}\n\nfunction assertNotRunning(\n projectRoot: string,\n hostName: string,\n projectName: string,\n): void {\n const probe = probeRun(projectRoot, hostName, projectName);\n if (probe.status === \"live\" && probe.record.pid !== process.pid) {\n throw new Error(\n `${hostName} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`,\n );\n }\n if (probe.status === \"foreign\") {\n throw new Error(\n `.ph/run/${hostName}.json describes a live \"${probe.record.projectName}\", but this project is \"${projectName}\". Refusing to start a second instance.`,\n );\n }\n}\n\ninterface PublishTarget {\n projectRoot: string;\n projectName: string;\n hostName: string;\n specifier: string;\n verb: string;\n}\n\n/** Await `ready`, validate the outputs, write the v2 record and clear it on\n * exit. A handle that never gets ready or reports invalid outputs is shut\n * down before the error propagates. */\nasync function publishOutputs(\n runner: RunnerModule,\n result: unknown,\n target: PublishTarget,\n): Promise<void> {\n const where = `${target.specifier} ${target.verb}`;\n const handle = toStartedHandle(result, where);\n const name = target.projectName;\n let outputs: unknown;\n try {\n if (!isSchemaLike(runner.outputsSchema)) return;\n // Checked again after the start: an instance that started meanwhile.\n assertNotRunning(target.projectRoot, target.hostName, name);\n if (handle.ready) await handle.ready;\n const parsed = runner.outputsSchema.safeParse(handle.outputs);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map(\n (issue) =>\n ` - ${issue.path.map(String).join(\".\") || \"<root>\"}: ${issue.message}`,\n )\n .join(\"\\n\");\n throw new Error(\n `${where} reported outputs that fail its outputsSchema:\\n${issues}`,\n );\n }\n outputs = parsed.data;\n } catch (error) {\n await handle.shutdown?.();\n throw error;\n }\n\n writeRunRecord(target.projectRoot, {\n version: 2,\n host: target.hostName,\n projectName: name,\n kind: \"reactor\",\n verb: target.verb,\n pid: process.pid,\n startedAt: new Date().toISOString(),\n outputs: outputs as Record<string, unknown>,\n });\n // No SIGINT/SIGTERM handler: the switchboard reactor's own handler kills\n // the reactor before draining the api, and a parallel shutdown() would\n // break that order. Without an exit event the record keeps a dead pid,\n // which probeRun reports as stale.\n process.on(\"exit\", () => {\n if (readRunRecord(target.projectRoot, target.hostName)?.pid === process.pid)\n clearRunRecord(target.projectRoot, target.hostName);\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,eAAsB,SAAS,MAAsC;CAKnE,IAAI,eAAe,IAAI,KAAK,QAAQ,KAAK,GACvC,QAAQ,IAAI,aAAa;CAE3B,MAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;CACpD,MAAM,SAAS,MAAM,SAAS,aAAa,KAAK,IAAI;CACpD,MAAM,EAAE,6BAA6B,MAAM,OAAO;CAClD,yBAAyB,WAAW;CACpC,MAAM,YAAY,OAAO,KAAK,OAAO;CACrC,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;CAC/D,MAAM,OAAO,KAAK,QAAQ;CAC1B,MAAM,KAAK,QAAQ,QAAQ,WAAW,IAAI;CAC1C,MAAM,OAAO,OA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C;AACH","debug_id":"a803084f-2032-5068-a22f-4875a78cd073"}
|
|
@@ -1,3 +1,5 @@
|
|
|
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]="9af619e6-270e-547b-9b87-014cced19b9f")}catch(e){}}();
|
|
1
3
|
import path from "node:path";
|
|
2
4
|
import fs from "node:fs";
|
|
3
5
|
//#region src/services/run/superseded-config.ts
|
|
@@ -47,4 +49,5 @@ function warnSupersededConfigKeys(projectRoot, warn = console.warn) {
|
|
|
47
49
|
//#endregion
|
|
48
50
|
export { warnSupersededConfigKeys };
|
|
49
51
|
|
|
50
|
-
//# sourceMappingURL=superseded-config-CpHrCuNq.mjs.map
|
|
52
|
+
//# sourceMappingURL=superseded-config-CpHrCuNq.mjs.map
|
|
53
|
+
//# debugId=9af619e6-270e-547b-9b87-014cced19b9f
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"superseded-config-CpHrCuNq.mjs","
|
|
1
|
+
{"version":3,"file":"superseded-config-CpHrCuNq.mjs","sources":["../src/services/run/superseded-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * P2.7 — the fixed legacy→hosts mapping table. With hosts/ active, these\n * powerhouse.config.json keys are superseded by host.js structure and the run\n * path ignores them; each present key warns ONCE per run, naming its new home.\n *\n * Keys the scaffolded host files REFERENCE (studio.port, reactor.port,\n * vetra.connectPort, assistant.port, and the WHOLE connect.* block — handed to the runtime\n * unchanged, connect.instance.* included) are expected to remain and are\n * deliberately absent from this table.\n */\nconst SUPERSEDED: Record<string, string> = {\n \"studio.host\": \"hosts/connect/host.js → runner.host\",\n \"studio.https\": \"hosts/connect/host.js → runner.https\",\n \"studio.openBrowser\": \"hosts/connect/host.js → runner.openBrowser\",\n \"reactor.https\": \"hosts/switchboard/host.js → runner.https\",\n \"reactor.storage\":\n \"hosts/switchboard/host.js → reactor.backends.<name>.storage\",\n \"switchboard.database.url\":\n \"hosts/switchboard/host.js → reactor.backends.<name>.storage.url\",\n};\n\nfunction lookup(config: unknown, dottedKey: string): unknown {\n let cursor: unknown = config;\n for (const part of dottedKey.split(\".\")) {\n if (cursor === null || typeof cursor !== \"object\") return undefined;\n cursor = (cursor as Record<string, unknown>)[part];\n }\n return cursor;\n}\n\n/** Warn once per run for each superseded key present in the project config.\n * Returns the warned keys (for tests). Never throws — a malformed config is\n * the loader's problem, not the warner's. */\nexport function warnSupersededConfigKeys(\n projectRoot: string,\n warn: (message: string) => void = console.warn,\n): string[] {\n let config: unknown;\n try {\n config = JSON.parse(\n fs.readFileSync(path.join(projectRoot, \"powerhouse.config.json\"), \"utf8\"),\n );\n } catch {\n return [];\n }\n const warned: string[] = [];\n for (const [key, newHome] of Object.entries(SUPERSEDED)) {\n if (lookup(config, key) !== undefined) {\n warned.push(key);\n warn(\n `[ph run] powerhouse.config.json \"${key}\" is ignored in hosts projects — ` +\n `its home is now ${newHome}.`,\n );\n }\n }\n return warned;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAaA,MAAM,aAAqC;CACzC,eAAe;CACf,gBAAgB;CAChB,sBAAsB;CACtB,iBAAiB;CACjB,mBACE;CACF,4BACE;AACJ;AAEA,SAAS,OAAO,QAAiB,WAA4B;CAC3D,IAAI,SAAkB;CACtB,KAAK,MAAM,QAAQ,UAAU,MAAM,GAAG,GAAG;EACvC,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU,OAAO,KAAA;EAC1D,SAAU,OAAmC;CAC/C;CACA,OAAO;AACT;;;;AAKA,SAAgB,yBACd,aACA,OAAkC,QAAQ,MAChC;CACV,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MACZ,GAAG,aAAa,KAAK,KAAK,aAAa,wBAAwB,GAAG,MAAM,CAC1E;CACF,QAAQ;EACN,OAAO,CAAC;CACV;CACA,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,CAAC,KAAK,YAAY,OAAO,QAAQ,UAAU,GACpD,IAAI,OAAO,QAAQ,GAAG,MAAM,KAAA,GAAW;EACrC,OAAO,KAAK,GAAG;EACf,KACE,oCAAoC,IAAI,mDACnB,QAAQ,EAC/B;CACF;CAEF,OAAO;AACT","debug_id":"9af619e6-270e-547b-9b87-014cced19b9f"}
|
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.90",
|
|
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.90",
|
|
76
|
+
"@powerhousedao/host-core": "6.2.3-dev.90",
|
|
77
|
+
"@powerhousedao/reactor": "6.2.3-dev.90",
|
|
78
|
+
"@powerhousedao/shared": "6.2.3-dev.90",
|
|
79
|
+
"@powerhousedao/switchboard": "6.2.3-dev.90",
|
|
80
80
|
"cmd-ts": "0.15.0",
|
|
81
|
-
"document-model": "6.2.3-dev.
|
|
81
|
+
"document-model": "6.2.3-dev.90",
|
|
82
82
|
"dotenv": "16.4.7",
|
|
83
83
|
"sirv": "^3.0.2",
|
|
84
84
|
"zod": "^4.5.4"
|