@powerhousedao/ph-run 6.2.3-dev.89 → 6.2.3-dev.91
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.d.mts +6 -0
- package/dist/runners/connect.d.mts.map +1 -1
- package/dist/runners/connect.mjs +5 -2
- package/dist/runners/connect.mjs.map +1 -1
- package/dist/runners/member-config.d.mts +4 -0
- package/dist/runners/member-config.d.mts.map +1 -1
- package/dist/runners/member-config.mjs +2 -0
- package/dist/runners/switchboard.d.mts +10 -0
- package/dist/runners/switchboard.d.mts.map +1 -1
- 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard.d.mts","names":[],"sources":["../../src/runners/switchboard.ts"],"mappings":";;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B,KAAK;EACvC;;;;;;;;;;;;;;wBAqGoB,aACpB,aACA,mBACA,eAAe,kBACf,mBAAkB,QACjB;;YAqBS,oBAAoB,aAAa;wBAiTvB,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;qBAIE,cAAK;qBAEL;wBAES,IACpB,MAAM,uBACN,KAAK,gBACJ,QAAQ;;wBAKW,UACpB,MAAM,uBACN,KAAK,mBACJ,QAAQ"}
|
|
@@ -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,MAAM,KAAK,MAAO,IAAI,SAAS,IAAA,CAAM,QAAQ,CAAC,EA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vD,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,KAAK,MAAM,QAAQ,EAAE,EAAE;AAChC;AAEA,SAAS,KAAK,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AM,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":";;;;;;;;;;;AA0CA,SAAgB,cAAc,YAAyC;CACrE,IAAI,CAAC,YAAY,O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,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,IAAI,UAAU,+BAA+B,GAAG;CAChD,IAAI,IAAI,WAAW,WAAW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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: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n },\n port,\n );\n return driveUr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AO;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,sBAAsB,CAAC,gBAAgB,SAAS;AAGtD,SAAgB,qBAAqB,MAA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;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,OAAO;CACpB,IAAI,KAAK,OACP,QAAQ,IAAI;EAAE,MAAM,OAA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,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
|