@powerhousedao/ph-cli 6.2.3-dev.82 → 6.2.3-dev.84

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.
Files changed (48) hide show
  1. package/dist/{check-DkH9B91Z.mjs → check-D2r9Qbyf.mjs} +5 -5
  2. package/dist/{check-DkH9B91Z.mjs.map → check-D2r9Qbyf.mjs.map} +1 -1
  3. package/dist/{cli-connect-override-CpHjVMDt.mjs → cli-connect-override-Bv5y96A5.mjs} +4 -4
  4. package/dist/{cli-connect-override-CpHjVMDt.mjs.map → cli-connect-override-Bv5y96A5.mjs.map} +1 -1
  5. package/dist/cli.mjs +4 -4
  6. package/dist/{compound-YHuVvCFd-C5NLunJf.mjs → compound-GhJAA2dK-Cj36zhoQ.mjs} +16 -4
  7. package/dist/compound-GhJAA2dK-Cj36zhoQ.mjs.map +1 -0
  8. package/dist/{connect-build-BxFswE45.mjs → connect-build-_HyX7OUY.mjs} +4 -4
  9. package/dist/{connect-build-BxFswE45.mjs.map → connect-build-_HyX7OUY.mjs.map} +1 -1
  10. package/dist/{connect-config-4WOy_Zua.mjs → connect-config-BD1WzHpY.mjs} +4 -4
  11. package/dist/{connect-config-4WOy_Zua.mjs.map → connect-config-BD1WzHpY.mjs.map} +1 -1
  12. package/dist/{connect-plugin-configs-uOxnR-7b.mjs → connect-plugin-configs-tVn11Qb_.mjs} +4 -4
  13. package/dist/{connect-plugin-configs-uOxnR-7b.mjs.map → connect-plugin-configs-tVn11Qb_.mjs.map} +1 -1
  14. package/dist/{connect-studio-DrwbiFVf.mjs → connect-studio-7Bx53D6Z.mjs} +3 -3
  15. package/dist/{connect-studio-qmgFWSt8.mjs → connect-studio-C0LLX1TD.mjs} +4 -4
  16. package/dist/{connect-studio-qmgFWSt8.mjs.map → connect-studio-C0LLX1TD.mjs.map} +1 -1
  17. package/dist/{dist-BlpdH3RP.mjs → dist-BiB5aiS6.mjs} +124 -66
  18. package/dist/dist-BiB5aiS6.mjs.map +1 -0
  19. package/dist/{explain-DARxM6-8.mjs → explain-DnKF_KNm.mjs} +5 -5
  20. package/dist/{explain-DARxM6-8.mjs.map → explain-DnKF_KNm.mjs.map} +1 -1
  21. package/dist/{export-DCMLPFSh.mjs → export-1QvYpjR1.mjs} +4 -4
  22. package/dist/{export-DCMLPFSh.mjs.map → export-1QvYpjR1.mjs.map} +1 -1
  23. package/dist/{generate-all-tbCt5ty4.mjs → generate-all-BVRk64NX.mjs} +4 -4
  24. package/dist/{generate-all-tbCt5ty4.mjs.map → generate-all-BVRk64NX.mjs.map} +1 -1
  25. package/dist/{get-version-CeWPXpXy.mjs → get-version-CUoLKAxV.mjs} +4 -4
  26. package/dist/{get-version-CeWPXpXy.mjs.map → get-version-CUoLKAxV.mjs.map} +1 -1
  27. package/dist/{mcp-YVqVelqp.mjs → mcp-BANOeLfA.mjs} +4 -4
  28. package/dist/{mcp-YVqVelqp.mjs.map → mcp-BANOeLfA.mjs.map} +1 -1
  29. package/dist/{member-config-BMqPMA0P.mjs → member-config-ZEe4PlHE.mjs} +4 -4
  30. package/dist/{member-config-BMqPMA0P.mjs.map → member-config-ZEe4PlHE.mjs.map} +1 -1
  31. package/dist/{ph-cli-commands-DPINuS0Q.mjs → ph-cli-commands-BS4Nacdg.mjs} +13 -13
  32. package/dist/{ph-cli-commands-DPINuS0Q.mjs.map → ph-cli-commands-BS4Nacdg.mjs.map} +1 -1
  33. package/dist/ph-cli-commands-CWu73AaF.mjs +4 -0
  34. package/dist/{run-sugar-BaVU46_Q.mjs → run-sugar-DWPDmuRj.mjs} +4 -4
  35. package/dist/{run-sugar-BaVU46_Q.mjs.map → run-sugar-DWPDmuRj.mjs.map} +1 -1
  36. package/dist/runners/connect.d.mts +88 -68
  37. package/dist/runners/connect.d.mts.map +1 -1
  38. package/dist/runners/connect.mjs +14 -17
  39. package/dist/runners/connect.mjs.map +1 -1
  40. package/dist/runners/switchboard.mjs +4 -4
  41. package/dist/{start-run-BogXSscB.mjs → start-run-CuQEMKRZ.mjs} +4 -4
  42. package/dist/{start-run-BogXSscB.mjs.map → start-run-CuQEMKRZ.mjs.map} +1 -1
  43. package/dist/{vetra-DUONHuYK.mjs → vetra-Ch4M1DtV.mjs} +6 -6
  44. package/dist/{vetra-DUONHuYK.mjs.map → vetra-Ch4M1DtV.mjs.map} +1 -1
  45. package/package.json +14 -14
  46. package/dist/compound-YHuVvCFd-C5NLunJf.mjs.map +0 -1
  47. package/dist/dist-BlpdH3RP.mjs.map +0 -1
  48. package/dist/ph-cli-commands-B5zSKfeX.mjs +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"connect-build-BxFswE45.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n ownProjectPackage,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n deepMerge,\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport {\n isPrecompressEnabled,\n precompressAssets,\n} from \"../utils/precompress.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(\n args: ConnectBuildArgs,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const cli = buildCliConnectOverride(args);\n const { packageRegistryUrl } = cli;\n // A runner's host config sits under the CLI's flags.\n const connectOverride = callerOverride\n ? deepMerge(callerOverride, cli.connectOverride ?? {})\n : cli.connectOverride;\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n routes,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n\n // Runs after the PWA plugin, so the siblings never enter the precache list.\n if (isPrecompressEnabled()) {\n const r = await precompressAssets(outDirAbs);\n console.log(\n `ph connect build: precompressed ${r.files} wasm/data files ` +\n `(${r.written} .gz written, ${(r.outputBytes / 1e6).toFixed(1)} MB) in ${(r.ms / 1000).toFixed(1)}s`,\n );\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n // One core and router for Connect and packages; the route tree, config and\n // embedded subpaths stay with the app.\n \"@powerhousedao/connect-core\",\n \"@powerhousedao/connect-core/router\",\n \"@powerhousedao/connect-core/plugins\",\n \"@powerhousedao/connect-core/runtime\",\n \"@powerhousedao/connect-core/views\",\n \"@tanstack/react-router\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n const configured = (config.packages ?? [])\n .filter((p) => p.provider === \"local\")\n .map((p) => p.packageName);\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself, and its models are the ones the worker\n // cannot otherwise get.\n const own = ownProjectPackage(dirname);\n const localPackages = [...new Set([...configured, ...(own ? [own] : [])])];\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n packages: localPackages,\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAmCA,eAAsB,gBACpB,MACA,gBACA,EAAE,WAAwC,CAAC,GAC3C;CACA,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,IAAI;CAK5B,IAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,GAC/D,MAAM,IAAI,MACR,4LACF;CAKF,6BAA6B,OAAO;CAOpC,MAAM,MAAM,wBAAwB,IAAI;CACxC,MAAM,EAAE,uBAAuB;CAE/B,MAAM,kBAAkB,iBACpB,UAAU,gBAAgB,IAAI,mBAAmB,CAAC,CAAC,IACnD,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,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"21e08da7-0a3e-512a-9aaf-d60eedfcf6d8"}
1
+ {"version":3,"file":"connect-build-_HyX7OUY.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n ownProjectPackage,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n deepMerge,\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport {\n isPrecompressEnabled,\n precompressAssets,\n} from \"../utils/precompress.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(\n args: ConnectBuildArgs,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const cli = buildCliConnectOverride(args);\n const { packageRegistryUrl } = cli;\n // A runner's host config sits under the CLI's flags.\n const connectOverride = callerOverride\n ? deepMerge(callerOverride, cli.connectOverride ?? {})\n : cli.connectOverride;\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n routes,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n\n // Runs after the PWA plugin, so the siblings never enter the precache list.\n if (isPrecompressEnabled()) {\n const r = await precompressAssets(outDirAbs);\n console.log(\n `ph connect build: precompressed ${r.files} wasm/data files ` +\n `(${r.written} .gz written, ${(r.outputBytes / 1e6).toFixed(1)} MB) in ${(r.ms / 1000).toFixed(1)}s`,\n );\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n // One core and router for Connect and packages; the route tree, config and\n // embedded subpaths stay with the app.\n \"@powerhousedao/connect-core\",\n \"@powerhousedao/connect-core/router\",\n \"@powerhousedao/connect-core/plugins\",\n \"@powerhousedao/connect-core/runtime\",\n \"@powerhousedao/connect-core/views\",\n \"@tanstack/react-router\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n const configured = (config.packages ?? [])\n .filter((p) => p.provider === \"local\")\n .map((p) => p.packageName);\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself, and its models are the ones the worker\n // cannot otherwise get.\n const own = ownProjectPackage(dirname);\n const localPackages = [...new Set([...configured, ...(own ? [own] : [])])];\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n packages: localPackages,\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAmCA,eAAsB,gBACpB,MACA,gBACA,EAAE,WAAwC,CAAC,GAC3C;CACA,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,IAAI;CAK5B,IAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,GAC/D,MAAM,IAAI,MACR,4LACF;CAKF,6BAA6B,OAAO;CAOpC,MAAM,MAAM,wBAAwB,IAAI;CACxC,MAAM,EAAE,uBAAuB;CAE/B,MAAM,kBAAkB,iBACpB,UAAU,gBAAgB,IAAI,mBAAmB,CAAC,CAAC,IACnD,IAAI;CAER,MAAM,SAAS;EACb,QAAQ;EACR;EAGA,cAAc;EACd,kBAAkB;CACpB,CAAC;CAOD,MAAM,YAAY,QAAQ,SAAS,MAAM;CACzC,IAAI,SAAgC;CAGpC,IAAI,UAAU;CAId,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CACxC,IAAI,gBAAgB,GAAG;EACrB,MAAM,WAAiC,CAAC;EAIxC,MAAM,WAAW,UAAU,KAA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AAK,WAAW,sBAAsB,UAAU;EACxD,QAAQ,SACJ;GAAE,SAAS,OAAO;GAAS,KAAK,KAAK,WAAW,YAAY;EAAE,IAC9D,KAAA;EACJ;EACA,SAAS;EACT;CACF,CAAC,GAEC,QAAQ,KACN,+EACE,SAAS,UAAU,MAAM,SAAS,YAAY,GAC/C,sEACH;AAEJ;;;;;;;AAQA,SAAgB,gBAAgB,MAAc,OAAiB,CAAC,GAAW;CACzE,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,SAAS,YAAY,IAAI,GAAG;EACrC,IAAI,KAAK,SAAS,KAAK,GAAG;EAC1B,OAAO,KAAK,MAAM,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC1D,WAAW;CACb;CACA,OAAO;AACT;AAEA,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,wBAAwB,CACvC,CAAC,CAAC,YAAY,CAAC,EAAA,CAAG,QAC3C,MAAM,EAAE,aAAa,OACxB;CACA,IAAI,cAAc,WAAW,GAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,cAAc,CACjE,CACJ;CACA,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,WAAW;CAC9C,MAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"5cf8c1a2-dad7-56af-b093-a054ac57d28f"}
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bcc4bb90-4fec-5cc0-9df3-933998614351")}catch(e){}}();
3
- import { c as validateConnectKeyValue, i as wasFlagExplicitlyPassed, l as validateConnectPatch, n as buildConnectFlagPatch, o as normalizeKey, s as parseCliValue } from "./cli-connect-override-CpHjVMDt.mjs";
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]="83b0dc83-50a3-5535-85af-621cd11598e8")}catch(e){}}();
3
+ import { c as validateConnectKeyValue, i as wasFlagExplicitlyPassed, l as validateConnectPatch, n as buildConnectFlagPatch, o as normalizeKey, s as parseCliValue } from "./cli-connect-override-Bv5y96A5.mjs";
4
4
  import { existsSync } from "node:fs";
5
5
  import { isAbsolute, join, resolve } from "node:path";
6
6
  import { ConfigLoader, JsonConfigAdapter, deepMerge, resolveSourceConnect } from "@powerhousedao/shared/connect";
@@ -192,5 +192,5 @@ async function runConnectConfig(args) {
192
192
  //#endregion
193
193
  export { runConnectConfig };
194
194
 
195
- //# sourceMappingURL=connect-config-4WOy_Zua.mjs.map
196
- //# debugId=bcc4bb90-4fec-5cc0-9df3-933998614351
195
+ //# sourceMappingURL=connect-config-BD1WzHpY.mjs.map
196
+ //# debugId=83b0dc83-50a3-5535-85af-621cd11598e8
@@ -1 +1 @@
1
- {"version":3,"file":"connect-config-4WOy_Zua.mjs","sources":["../src/utils/get-at-path.ts","../src/services/connect-config.ts"],"sourcesContent":["/**\n * Walk a parsed path (e.g. from remeda's `stringToPath`) through a runtime-\n * typed object, returning the value or `undefined` if any segment is\n * missing.\n *\n * Remeda's `prop` is overload-typed for compile-time literal paths and\n * doesn't accept a runtime path array via spread, so we walk inline for\n * the dynamic-path case used by `ph connect config --get`.\n */\nexport function getAtPath(\n obj: unknown,\n parts: ReadonlyArray<string | number>,\n): unknown {\n let cur: unknown = obj;\n for (const key of parts) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[String(key)];\n }\n return cur;\n}\n","// `ph connect config` — read or update Connect's runtime configuration.\n//\n// Mode dispatch (exactly one mode per invocation; mutex enforced below):\n//\n// ph connect config → list mode (print effective merged config)\n// ph connect config <key> → get mode (positional)\n// ph connect config --get <dotted.path> → get mode (flag form, equivalent)\n// ph connect config <key> <value> → set mode (positional, dual-write source + dist)\n// ph connect config --<field> <value> → set mode (flag form)\n// ph connect config --json '{...}' → bulk-set mode (dual-write)\n//\n// Dual-write semantics for set / bulk-set:\n// - Source `powerhouse.config.json` (project root) gets the connect.* patch\n// deep-merged into `connect.*`. `--packages-registry` lands at the\n// top-level `packageRegistryUrl` field (project-wide setting, also read\n// by `ph install` / `ph publish` / Switchboard).\n// - Dist `powerhouse.config.json` (default `.ph/connect-build/dist/`) gets\n// the same connect.* patch deep-merged in, and the same top-level\n// `packageRegistryUrl` if set. The runtime schema mirrors the source\n// schema, so the field lives at the same path in both files.\n//\n// The dist write is skipped silently if the dist file doesn't exist — that's\n// the \"config-only-before-first-build\" workflow, not an error.\n//\n// Field flags + the 4 commonArgs flags (base, log-level, default-drives-url,\n// drive-preserve-strategy) come from the same source as `ph connect build`'s\n// flags, so the two commands share identical CLI surfaces. The 4 commonArgs\n// flags carry cmd-ts defaults; we gate them through `wasFlagExplicitlyPassed`\n// for the same reason `buildCliConnectOverride` does — to avoid leaking\n// default values into a write the user didn't request.\n\nimport type {\n PHConnectRuntimeConfig,\n PowerhouseConfig,\n} from \"@powerhousedao/shared/clis\";\nimport {\n ConfigLoader,\n JsonConfigAdapter,\n deepMerge,\n resolveSourceConnect,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { stringToPath } from \"remeda\";\nimport type { ConnectConfigArgs } from \"../types.js\";\nimport {\n buildConnectFlagPatch,\n wasFlagExplicitlyPassed,\n type ConnectFlagInput,\n} from \"../utils/cli-connect-override.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"../utils/connect-config-validation.js\";\nimport { getAtPath } from \"../utils/get-at-path.js\";\n\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\nconst SOURCE_FILE = \"powerhouse.config.json\";\nconst DEFAULT_DIST_SUBPATH = \".ph/connect-build/dist\";\n\nfunction resolveSourcePath(cwd: string): string {\n return join(cwd, SOURCE_FILE);\n}\n\nfunction resolveDistPath(cwd: string, distDirArg: string | undefined): string {\n const fromArg = distDirArg;\n const fromEnv = process.env.PH_CONNECT_OUTDIR;\n const dir = fromArg ?? fromEnv ?? DEFAULT_DIST_SUBPATH;\n const abs = isAbsolute(dir) ? dir : resolve(cwd, dir);\n return join(abs, SOURCE_FILE);\n}\n\n/**\n * Read the source file's raw bytes (no merge with defaults). Returns an empty\n * object stub when the file doesn't exist — the operator can config their way\n * to a complete file before ever running `ph connect build`.\n */\nasync function readSourceRaw(path: string): Promise<Record<string, unknown>> {\n if (!existsSync(path)) return {};\n const adapter = new JsonConfigAdapter({ path });\n const raw = await adapter.read();\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n}\n\nasync function writeSourceRaw(\n path: string,\n next: Record<string, unknown>,\n): Promise<void> {\n const adapter = new JsonConfigAdapter({ path });\n // ConfigShape requires a `connect` key; ensure it's present.\n const shape = {\n ...next,\n connect: (next.connect as PHConnectRuntimeConfig | undefined) ?? {},\n };\n await adapter.write(shape);\n}\n\n/**\n * Build the merged \"effective\" connect block for list/get mode: defaults <\n * source.workflows < source.connect. Doesn't go through env or dist — list\n * mode shows what the source declares + defaults, which is what the next\n * build will produce as a baseline (before env seeds + CLI overrides).\n */\nfunction effectiveConnect(\n source: Record<string, unknown>,\n): PHConnectRuntimeConfig {\n const sourceConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as ConnectPartial)\n : {};\n return resolveSourceConnect({\n connect: sourceConnect,\n workflows: source.workflows as PowerhouseConfig[\"workflows\"],\n });\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Translate the parsed `ph connect config` args into the structural\n * `ConnectFlagInput` consumed by `buildConnectFlagPatch`. Common-args flags\n * with cmd-ts defaults are gated through `wasFlagExplicitlyPassed` so the\n * defaults don't leak into a write the user didn't request. `--base` is\n * not translated here — it's rejected up front by `runConnectConfig`.\n */\nfunction argsToFlagInput(args: ConnectConfigArgs): ConnectFlagInput {\n return {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\n renownNamespace: args.renownNamespace,\n renownSwitchboardUrl: args.renownSwitchboardUrl,\n allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\n workflows: args.workflows,\n remoteDrivesEnabled: args.remoteDrivesEnabled,\n remoteDrivesAllowAdd: args.remoteDrivesAllowAdd,\n remoteDrivesAllowDelete: args.remoteDrivesAllowDelete,\n localDrivesEnabled: args.localDrivesEnabled,\n localDrivesAllowAdd: args.localDrivesAllowAdd,\n localDrivesAllowDelete: args.localDrivesAllowDelete,\n appName: args.appName,\n homeBackground: args.homeBackground,\n sentryDsn: args.sentryDsn,\n sentryEnv: args.sentryEnv,\n sentryTracingEnabled: args.sentryTracingEnabled,\n logLevel: wasFlagExplicitlyPassed(\"log-level\") ? args.logLevel : undefined,\n defaultDrivesUrl: wasFlagExplicitlyPassed(\"default-drives-url\")\n ? args.defaultDrivesUrl\n : undefined,\n drivesPreserveStrategy: wasFlagExplicitlyPassed(\"drive-preserve-strategy\")\n ? args.drivesPreserveStrategy\n : undefined,\n };\n}\n\n/**\n * Whether any field flag (any of the 20) was passed. Distinguishes the\n * single-field-set mode from list mode when neither `--get` nor `--json` is\n * present.\n */\nfunction hasAnyFieldFlag(input: ConnectFlagInput): boolean {\n // Object.values doesn't include json (which isn't in ConnectFlagInput here).\n // Cast to a generic record so the `!== undefined` predicate is type-aware:\n // ConnectFlagInput's optional properties narrow `v` in a way TS thinks\n // excludes `undefined`, even though at runtime any of them can be unset.\n return Object.values(input as Record<string, unknown>).some(\n (v) => v !== undefined,\n );\n}\n\nexport async function runConnectConfig(args: ConnectConfigArgs): Promise<void> {\n // `--base` is a build-time field (baked into the Vite bundle's asset URLs\n // and the nginx config template), so writing it post-build leaves the\n // layers disagreeing and the SPA's assets 404. The flag stays declared so\n // cmd-ts parses it; we reject explicit use here with an actionable error.\n if (wasFlagExplicitlyPassed(\"base\")) {\n throw new Error(\n \"ph connect config: --base is a build-time field; run `ph connect build --base <value>` and redeploy the container (or restart with PH_CONNECT_BASE_PATH=<value> set in the environment).\",\n );\n }\n\n const cwd = process.cwd();\n const sourcePath = resolveSourcePath(cwd);\n const distPath = resolveDistPath(cwd, args.distDir);\n\n const flagInput = argsToFlagInput(args);\n const hasGet = args.get !== undefined;\n const hasJson = args.json !== undefined;\n const hasFieldFlag = hasAnyFieldFlag(flagInput);\n // `--packages-registry` is a top-level field, not part of the connect-flag\n // patch. Track it separately so the set-mode write puts it in the right\n // place and the mutex counts it as a \"field flag\".\n const explicitRegistry = args.packagesRegistry;\n const hasExplicitRegistry = explicitRegistry !== undefined;\n // Positional pair: 1 positional = get, 2 = set. cmd-ts assigns the first\n // positional to `keyPositional` and the second to `valuePositional`, so a\n // standalone <value> isn't representable here.\n const hasPositionalKey = args.keyPositional !== undefined;\n const hasPositionalValue = args.valuePositional !== undefined;\n const hasPositional = hasPositionalKey;\n\n // Mutex: positional / --get / --json / (any field flag OR\n // --packages-registry) are mutually exclusive. Exactly one mode (or none →\n // list) per call. Counting positional as a single mode regardless of arity:\n // a `<key>` alone is a get, `<key> <value>` is a set, both occupy the same\n // \"positional mode\" slot vs. the other forms.\n const modeCount = [\n hasPositional,\n hasGet,\n hasJson,\n hasFieldFlag || hasExplicitRegistry,\n ].filter(Boolean).length;\n if (modeCount > 1) {\n throw new Error(\n \"ph connect config: positional <key>/<value>, --get, --json, and individual field flags are mutually exclusive. Use one mode per invocation.\",\n );\n }\n\n const source = await readSourceRaw(sourcePath);\n\n // List mode.\n if (modeCount === 0) {\n printJson(effectiveConnect(source));\n return;\n }\n\n // Get mode (either positional `<key>` alone or `--get <key>`).\n if (hasGet || (hasPositional && !hasPositionalValue)) {\n const rawKey = hasGet ? args.get! : args.keyPositional!;\n const sourceLabel = hasGet ? \"--get\" : \"<key>\";\n const normalized = normalizeKey(rawKey);\n if (!normalized) {\n throw new Error(\n `ph connect config ${sourceLabel}: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).`,\n );\n }\n // `packageRegistryUrl` is a top-level field — look it up on the raw\n // source object, not inside `effectiveConnect`.\n if (normalized === \"packageRegistryUrl\") {\n const value = source.packageRegistryUrl;\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n const value = getAtPath(effectiveConnect(source), stringToPath(normalized));\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n\n // Set / bulk-set mode. Build the connect-side patch from positional\n // `<key> <value>` (Ajv-validated against the schema at that path), --json\n // (Ajv-validated as a partial connect.* blob), or individual field flags\n // (shape guaranteed by cmd-ts type coercion). `--packages-registry` is a\n // top-level field; if positional `<key>` is `packageRegistryUrl` or --json\n // carries it, route that to the top-level write.\n let topLevelRegistry: string | undefined = explicitRegistry;\n let patch: ConnectPartial;\n if (hasPositional && hasPositionalValue) {\n const normalized = normalizeKey(args.keyPositional!);\n if (!normalized) {\n throw new Error(\n \"ph connect config <key>: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n // Top-level: positional `packageRegistryUrl <value>` writes the top-level\n // field instead of a connect.* path.\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional!);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect config: packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n topLevelRegistry = parsed;\n patch = {};\n } else {\n patch = validateConnectKeyValue(\n normalized,\n args.valuePositional!,\n ) as ConnectPartial;\n }\n } else if (hasJson) {\n const validated = validateConnectPatch(args.json!) as Record<\n string,\n unknown\n >;\n if (typeof validated.packageRegistryUrl === \"string\") {\n topLevelRegistry = topLevelRegistry ?? validated.packageRegistryUrl;\n }\n const connectOnly = { ...validated };\n delete connectOnly.packageRegistryUrl;\n patch = connectOnly as ConnectPartial;\n } else {\n patch = buildConnectFlagPatch(flagInput) as ConnectPartial;\n }\n\n if (Object.keys(patch).length === 0 && topLevelRegistry === undefined) {\n throw new Error(\n \"ph connect config: nothing to set. Pass at least one field flag (e.g. --renown-url <url>) or --json with a non-empty payload.\",\n );\n }\n\n // Build the next source: top-level packageRegistryUrl (if set) +\n // connect.* deep-merge.\n const currentConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as PHConnectRuntimeConfig)\n : ({} as PHConnectRuntimeConfig);\n const nextConnect = deepMerge(\n currentConnect,\n patch as PHConnectRuntimeConfig,\n );\n const nextSource: Record<string, unknown> = {\n ...source,\n connect: nextConnect,\n };\n if (topLevelRegistry !== undefined) {\n nextSource.packageRegistryUrl = topLevelRegistry;\n }\n\n await writeSourceRaw(sourcePath, nextSource);\n\n // Dual-write to dist if it exists. Same shape as source: connect.* block\n // is deep-merged; top-level `packageRegistryUrl` is set in place.\n if (existsSync(distPath)) {\n const distLoader = new ConfigLoader(\n new JsonConfigAdapter({ path: distPath }),\n );\n const distPatch: Record<string, unknown> = { connect: patch };\n if (topLevelRegistry !== undefined) {\n distPatch.packageRegistryUrl = topLevelRegistry;\n }\n await distLoader.write(distPatch);\n }\n\n process.stdout.write(\n `ph connect config: wrote ${sourcePath}${existsSync(distPath)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AM,YAAY,qBAAqB,KAAK,IAAK;EAIjD,IAAI,OAAO,UAAU,uBAAuB,UAC1C,mBAAmB,oBAAoB,UAAU;EAEnD,MAAM,cAAc,EAAE,GAAG,UAAU;EACnC,OAAO,YAAY;EACnB,QAAQ;CACV,OACE,QAAQ,sBAAsB,SAAS;CAGzC,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,qBAAqB,KAAA,GAC1D,MAAM,IAAI,MACR,+HACF;CAKF,MAAM,iBACJ,OAAO,WACP,OAAO,OAAO,YAAY,YAC1B,CAAC,MAAM,QAAQ,OAAO,OAAO,IACxB,OAAO,UACP,CAAC;CACR,MAAM,cAAc,UAClB,gBACA,KACF;CACA,MAAM,aAAsC;EAC1C,GAAG;EACH,SAAS;CACX;CACA,IAAI,qBAAqB,KAAA,GACvB,WAAW,qBAAqB;CAGlC,MAAM,eAAe,YAAY,UAAU;CAI3C,IAAI,WAAW,QAAQ,GAAG;EACxB,MAAM,aAAa,IAAI,aACrB,IAAI,kBAAkB,EAAE,MAAM,SAAS,CAAC,CAC1C;EACA,MAAM,YAAqC,EAAE,SAAS,MAAM;EAC5D,IAAI,qBAAqB,KAAA,GACvB,UAAU,qBAAqB;EAEjC,MAAM,WAAW,MAAM,SAAS;CAClC;CAEA,QAAQ,OAAO,MACb,4BAA4B,aAAa,WAAW,QAAQ,IAAI,QAAQ,aAAa,GAAG,GAC1F;AACF","debug_id":"bcc4bb90-4fec-5cc0-9df3-933998614351"}
1
+ {"version":3,"file":"connect-config-BD1WzHpY.mjs","sources":["../src/utils/get-at-path.ts","../src/services/connect-config.ts"],"sourcesContent":["/**\n * Walk a parsed path (e.g. from remeda's `stringToPath`) through a runtime-\n * typed object, returning the value or `undefined` if any segment is\n * missing.\n *\n * Remeda's `prop` is overload-typed for compile-time literal paths and\n * doesn't accept a runtime path array via spread, so we walk inline for\n * the dynamic-path case used by `ph connect config --get`.\n */\nexport function getAtPath(\n obj: unknown,\n parts: ReadonlyArray<string | number>,\n): unknown {\n let cur: unknown = obj;\n for (const key of parts) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[String(key)];\n }\n return cur;\n}\n","// `ph connect config` — read or update Connect's runtime configuration.\n//\n// Mode dispatch (exactly one mode per invocation; mutex enforced below):\n//\n// ph connect config → list mode (print effective merged config)\n// ph connect config <key> → get mode (positional)\n// ph connect config --get <dotted.path> → get mode (flag form, equivalent)\n// ph connect config <key> <value> → set mode (positional, dual-write source + dist)\n// ph connect config --<field> <value> → set mode (flag form)\n// ph connect config --json '{...}' → bulk-set mode (dual-write)\n//\n// Dual-write semantics for set / bulk-set:\n// - Source `powerhouse.config.json` (project root) gets the connect.* patch\n// deep-merged into `connect.*`. `--packages-registry` lands at the\n// top-level `packageRegistryUrl` field (project-wide setting, also read\n// by `ph install` / `ph publish` / Switchboard).\n// - Dist `powerhouse.config.json` (default `.ph/connect-build/dist/`) gets\n// the same connect.* patch deep-merged in, and the same top-level\n// `packageRegistryUrl` if set. The runtime schema mirrors the source\n// schema, so the field lives at the same path in both files.\n//\n// The dist write is skipped silently if the dist file doesn't exist — that's\n// the \"config-only-before-first-build\" workflow, not an error.\n//\n// Field flags + the 4 commonArgs flags (base, log-level, default-drives-url,\n// drive-preserve-strategy) come from the same source as `ph connect build`'s\n// flags, so the two commands share identical CLI surfaces. The 4 commonArgs\n// flags carry cmd-ts defaults; we gate them through `wasFlagExplicitlyPassed`\n// for the same reason `buildCliConnectOverride` does — to avoid leaking\n// default values into a write the user didn't request.\n\nimport type {\n PHConnectRuntimeConfig,\n PowerhouseConfig,\n} from \"@powerhousedao/shared/clis\";\nimport {\n ConfigLoader,\n JsonConfigAdapter,\n deepMerge,\n resolveSourceConnect,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { stringToPath } from \"remeda\";\nimport type { ConnectConfigArgs } from \"../types.js\";\nimport {\n buildConnectFlagPatch,\n wasFlagExplicitlyPassed,\n type ConnectFlagInput,\n} from \"../utils/cli-connect-override.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"../utils/connect-config-validation.js\";\nimport { getAtPath } from \"../utils/get-at-path.js\";\n\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\nconst SOURCE_FILE = \"powerhouse.config.json\";\nconst DEFAULT_DIST_SUBPATH = \".ph/connect-build/dist\";\n\nfunction resolveSourcePath(cwd: string): string {\n return join(cwd, SOURCE_FILE);\n}\n\nfunction resolveDistPath(cwd: string, distDirArg: string | undefined): string {\n const fromArg = distDirArg;\n const fromEnv = process.env.PH_CONNECT_OUTDIR;\n const dir = fromArg ?? fromEnv ?? DEFAULT_DIST_SUBPATH;\n const abs = isAbsolute(dir) ? dir : resolve(cwd, dir);\n return join(abs, SOURCE_FILE);\n}\n\n/**\n * Read the source file's raw bytes (no merge with defaults). Returns an empty\n * object stub when the file doesn't exist — the operator can config their way\n * to a complete file before ever running `ph connect build`.\n */\nasync function readSourceRaw(path: string): Promise<Record<string, unknown>> {\n if (!existsSync(path)) return {};\n const adapter = new JsonConfigAdapter({ path });\n const raw = await adapter.read();\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n}\n\nasync function writeSourceRaw(\n path: string,\n next: Record<string, unknown>,\n): Promise<void> {\n const adapter = new JsonConfigAdapter({ path });\n // ConfigShape requires a `connect` key; ensure it's present.\n const shape = {\n ...next,\n connect: (next.connect as PHConnectRuntimeConfig | undefined) ?? {},\n };\n await adapter.write(shape);\n}\n\n/**\n * Build the merged \"effective\" connect block for list/get mode: defaults <\n * source.workflows < source.connect. Doesn't go through env or dist — list\n * mode shows what the source declares + defaults, which is what the next\n * build will produce as a baseline (before env seeds + CLI overrides).\n */\nfunction effectiveConnect(\n source: Record<string, unknown>,\n): PHConnectRuntimeConfig {\n const sourceConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as ConnectPartial)\n : {};\n return resolveSourceConnect({\n connect: sourceConnect,\n workflows: source.workflows as PowerhouseConfig[\"workflows\"],\n });\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Translate the parsed `ph connect config` args into the structural\n * `ConnectFlagInput` consumed by `buildConnectFlagPatch`. Common-args flags\n * with cmd-ts defaults are gated through `wasFlagExplicitlyPassed` so the\n * defaults don't leak into a write the user didn't request. `--base` is\n * not translated here — it's rejected up front by `runConnectConfig`.\n */\nfunction argsToFlagInput(args: ConnectConfigArgs): ConnectFlagInput {\n return {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\n renownNamespace: args.renownNamespace,\n renownSwitchboardUrl: args.renownSwitchboardUrl,\n allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\n workflows: args.workflows,\n remoteDrivesEnabled: args.remoteDrivesEnabled,\n remoteDrivesAllowAdd: args.remoteDrivesAllowAdd,\n remoteDrivesAllowDelete: args.remoteDrivesAllowDelete,\n localDrivesEnabled: args.localDrivesEnabled,\n localDrivesAllowAdd: args.localDrivesAllowAdd,\n localDrivesAllowDelete: args.localDrivesAllowDelete,\n appName: args.appName,\n homeBackground: args.homeBackground,\n sentryDsn: args.sentryDsn,\n sentryEnv: args.sentryEnv,\n sentryTracingEnabled: args.sentryTracingEnabled,\n logLevel: wasFlagExplicitlyPassed(\"log-level\") ? args.logLevel : undefined,\n defaultDrivesUrl: wasFlagExplicitlyPassed(\"default-drives-url\")\n ? args.defaultDrivesUrl\n : undefined,\n drivesPreserveStrategy: wasFlagExplicitlyPassed(\"drive-preserve-strategy\")\n ? args.drivesPreserveStrategy\n : undefined,\n };\n}\n\n/**\n * Whether any field flag (any of the 20) was passed. Distinguishes the\n * single-field-set mode from list mode when neither `--get` nor `--json` is\n * present.\n */\nfunction hasAnyFieldFlag(input: ConnectFlagInput): boolean {\n // Object.values doesn't include json (which isn't in ConnectFlagInput here).\n // Cast to a generic record so the `!== undefined` predicate is type-aware:\n // ConnectFlagInput's optional properties narrow `v` in a way TS thinks\n // excludes `undefined`, even though at runtime any of them can be unset.\n return Object.values(input as Record<string, unknown>).some(\n (v) => v !== undefined,\n );\n}\n\nexport async function runConnectConfig(args: ConnectConfigArgs): Promise<void> {\n // `--base` is a build-time field (baked into the Vite bundle's asset URLs\n // and the nginx config template), so writing it post-build leaves the\n // layers disagreeing and the SPA's assets 404. The flag stays declared so\n // cmd-ts parses it; we reject explicit use here with an actionable error.\n if (wasFlagExplicitlyPassed(\"base\")) {\n throw new Error(\n \"ph connect config: --base is a build-time field; run `ph connect build --base <value>` and redeploy the container (or restart with PH_CONNECT_BASE_PATH=<value> set in the environment).\",\n );\n }\n\n const cwd = process.cwd();\n const sourcePath = resolveSourcePath(cwd);\n const distPath = resolveDistPath(cwd, args.distDir);\n\n const flagInput = argsToFlagInput(args);\n const hasGet = args.get !== undefined;\n const hasJson = args.json !== undefined;\n const hasFieldFlag = hasAnyFieldFlag(flagInput);\n // `--packages-registry` is a top-level field, not part of the connect-flag\n // patch. Track it separately so the set-mode write puts it in the right\n // place and the mutex counts it as a \"field flag\".\n const explicitRegistry = args.packagesRegistry;\n const hasExplicitRegistry = explicitRegistry !== undefined;\n // Positional pair: 1 positional = get, 2 = set. cmd-ts assigns the first\n // positional to `keyPositional` and the second to `valuePositional`, so a\n // standalone <value> isn't representable here.\n const hasPositionalKey = args.keyPositional !== undefined;\n const hasPositionalValue = args.valuePositional !== undefined;\n const hasPositional = hasPositionalKey;\n\n // Mutex: positional / --get / --json / (any field flag OR\n // --packages-registry) are mutually exclusive. Exactly one mode (or none →\n // list) per call. Counting positional as a single mode regardless of arity:\n // a `<key>` alone is a get, `<key> <value>` is a set, both occupy the same\n // \"positional mode\" slot vs. the other forms.\n const modeCount = [\n hasPositional,\n hasGet,\n hasJson,\n hasFieldFlag || hasExplicitRegistry,\n ].filter(Boolean).length;\n if (modeCount > 1) {\n throw new Error(\n \"ph connect config: positional <key>/<value>, --get, --json, and individual field flags are mutually exclusive. Use one mode per invocation.\",\n );\n }\n\n const source = await readSourceRaw(sourcePath);\n\n // List mode.\n if (modeCount === 0) {\n printJson(effectiveConnect(source));\n return;\n }\n\n // Get mode (either positional `<key>` alone or `--get <key>`).\n if (hasGet || (hasPositional && !hasPositionalValue)) {\n const rawKey = hasGet ? args.get! : args.keyPositional!;\n const sourceLabel = hasGet ? \"--get\" : \"<key>\";\n const normalized = normalizeKey(rawKey);\n if (!normalized) {\n throw new Error(\n `ph connect config ${sourceLabel}: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).`,\n );\n }\n // `packageRegistryUrl` is a top-level field — look it up on the raw\n // source object, not inside `effectiveConnect`.\n if (normalized === \"packageRegistryUrl\") {\n const value = source.packageRegistryUrl;\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n const value = getAtPath(effectiveConnect(source), stringToPath(normalized));\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n\n // Set / bulk-set mode. Build the connect-side patch from positional\n // `<key> <value>` (Ajv-validated against the schema at that path), --json\n // (Ajv-validated as a partial connect.* blob), or individual field flags\n // (shape guaranteed by cmd-ts type coercion). `--packages-registry` is a\n // top-level field; if positional `<key>` is `packageRegistryUrl` or --json\n // carries it, route that to the top-level write.\n let topLevelRegistry: string | undefined = explicitRegistry;\n let patch: ConnectPartial;\n if (hasPositional && hasPositionalValue) {\n const normalized = normalizeKey(args.keyPositional!);\n if (!normalized) {\n throw new Error(\n \"ph connect config <key>: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n // Top-level: positional `packageRegistryUrl <value>` writes the top-level\n // field instead of a connect.* path.\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional!);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect config: packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n topLevelRegistry = parsed;\n patch = {};\n } else {\n patch = validateConnectKeyValue(\n normalized,\n args.valuePositional!,\n ) as ConnectPartial;\n }\n } else if (hasJson) {\n const validated = validateConnectPatch(args.json!) as Record<\n string,\n unknown\n >;\n if (typeof validated.packageRegistryUrl === \"string\") {\n topLevelRegistry = topLevelRegistry ?? validated.packageRegistryUrl;\n }\n const connectOnly = { ...validated };\n delete connectOnly.packageRegistryUrl;\n patch = connectOnly as ConnectPartial;\n } else {\n patch = buildConnectFlagPatch(flagInput) as ConnectPartial;\n }\n\n if (Object.keys(patch).length === 0 && topLevelRegistry === undefined) {\n throw new Error(\n \"ph connect config: nothing to set. Pass at least one field flag (e.g. --renown-url <url>) or --json with a non-empty payload.\",\n );\n }\n\n // Build the next source: top-level packageRegistryUrl (if set) +\n // connect.* deep-merge.\n const currentConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as PHConnectRuntimeConfig)\n : ({} as PHConnectRuntimeConfig);\n const nextConnect = deepMerge(\n currentConnect,\n patch as PHConnectRuntimeConfig,\n );\n const nextSource: Record<string, unknown> = {\n ...source,\n connect: nextConnect,\n };\n if (topLevelRegistry !== undefined) {\n nextSource.packageRegistryUrl = topLevelRegistry;\n }\n\n await writeSourceRaw(sourcePath, nextSource);\n\n // Dual-write to dist if it exists. Same shape as source: connect.* block\n // is deep-merged; top-level `packageRegistryUrl` is set in place.\n if (existsSync(distPath)) {\n const distLoader = new ConfigLoader(\n new JsonConfigAdapter({ path: distPath }),\n );\n const distPatch: Record<string, unknown> = { connect: patch };\n if (topLevelRegistry !== undefined) {\n distPatch.packageRegistryUrl = topLevelRegistry;\n }\n await distLoader.write(distPatch);\n }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,YACA,KAAK,eACP;CAEJ,OAAO,IAAI,SAAS;EAClB,MAAM,YAAY,qBAAqB,KAAK,IAAK;EAIjD,IAAI,OAAO,UAAU,uBAAuB,UAC1C,mBAAmB,oBAAoB,UAAU;EAEnD,MAAM,cAAc,EAAE,GAAG,UAAU;EACnC,OAAO,YAAY;EACnB,QAAQ;CACV,OACE,QAAQ,sBAAsB,SAAS;CAGzC,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,qBAAqB,KAAA,GAC1D,MAAM,IAAI,MACR,+HACF;CAKF,MAAM,iBACJ,OAAO,WACP,OAAO,OAAO,YAAY,YAC1B,CAAC,MAAM,QAAQ,OAAO,OAAO,IACxB,OAAO,UACP,CAAC;CACR,MAAM,cAAc,UAClB,gBACA,KACF;CACA,MAAM,aAAsC;EAC1C,GAAG;EACH,SAAS;CACX;CACA,IAAI,qBAAqB,KAAA,GACvB,WAAW,qBAAqB;CAGlC,MAAM,eAAe,YAAY,UAAU;CAI3C,IAAI,WAAW,QAAQ,GAAG;EACxB,MAAM,aAAa,IAAI,aACrB,IAAI,kBAAkB,EAAE,MAAM,SAAS,CAAC,CAC1C;EACA,MAAM,YAAqC,EAAE,SAAS,MAAM;EAC5D,IAAI,qBAAqB,KAAA,GACvB,UAAU,qBAAqB;EAEjC,MAAM,WAAW,MAAM,SAAS;CAClC;CAEA,QAAQ,OAAO,MACb,4BAA4B,aAAa,WAAW,QAAQ,IAAI,QAAQ,aAAa,GAAG,GAC1F;AACF","debug_id":"83b0dc83-50a3-5535-85af-621cd11598e8"}
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8ca9dd41-32ca-5b24-848d-bafd97044f07")}catch(e){}}();
3
- import { E as isSchemaLike, N as normalizePluginEntries, _ as entryActiveForVerb, i as PluginError } from "./compound-YHuVvCFd-C5NLunJf.mjs";
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]="d433bf73-ee3a-5afe-8a0e-f4693f603432")}catch(e){}}();
3
+ import { E as isSchemaLike, N as normalizePluginEntries, _ as entryActiveForVerb, i as PluginError } from "./compound-GhJAA2dK-Cj36zhoQ.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -46,5 +46,5 @@ async function loadPluginConfigSchemas(projectRoot) {
46
46
  //#endregion
47
47
  export { validateConnectPluginConfigs };
48
48
 
49
- //# sourceMappingURL=connect-plugin-configs-uOxnR-7b.mjs.map
50
- //# debugId=8ca9dd41-32ca-5b24-848d-bafd97044f07
49
+ //# sourceMappingURL=connect-plugin-configs-tVn11Qb_.mjs.map
50
+ //# debugId=d433bf73-ee3a-5afe-8a0e-f4693f603432
@@ -1 +1 @@
1
- {"version":3,"file":"connect-plugin-configs-uOxnR-7b.mjs","sources":["../src/runners/connect-plugin-configs.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n entryActiveForVerb,\n isSchemaLike,\n normalizePluginEntries,\n PluginError,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\n\n/** The zod-only entry Connect publishes with every built-in plugin's entry\n * config schema, keyed by plugin specifier. */\nconst PLUGIN_CONFIGS_ENTRY = \"@powerhousedao/connect/plugin-configs\";\n\n/**\n * Validate the entry configs of the Connect plugins composed for `verb`\n * before Connect boots, so a typo fails at `ph run` naming the plugin and the\n * key instead of at browser boot. The schemas come from the project's own\n * `@powerhousedao/connect/plugin-configs` (resolved from the project tree,\n * like runner and plugin modules); without it, or for a specifier it has no\n * schema for, the browser's own validation stays the only check.\n */\nexport async function validateConnectPluginConfigs(\n projectRoot: string,\n entries: readonly PluginEntryData[] | undefined,\n verb: string,\n where: string,\n): Promise<void> {\n if (entries === undefined || entries.length === 0) return;\n const schemas = await loadPluginConfigSchemas(projectRoot);\n if (!schemas) return;\n for (const entry of normalizePluginEntries(entries, where)) {\n if (!entryActiveForVerb(entry, verb)) continue;\n const schema = schemas[entry.module];\n if (!isSchemaLike(schema)) continue;\n const parsed = schema.safeParse(entry.config);\n if (parsed.success) continue;\n const issues = parsed.error.issues.map((issue) => {\n const key = [\"config\", ...issue.path.map(String)].join(\".\");\n return ` - ${key}: ${issue.message}`;\n });\n throw new PluginError(\n `${where}: config for plugin \"${entry.module}\" is invalid:\\n${issues.join(\"\\n\")}`,\n );\n }\n}\n\nasync function loadPluginConfigSchemas(\n projectRoot: string,\n): Promise<Record<string, unknown> | undefined> {\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let file: string;\n try {\n file = projectRequire.resolve(PLUGIN_CONFIGS_ENTRY);\n } catch {\n return undefined;\n }\n const module = (await import(pathToFileURL(file).href)) as {\n connectPluginConfigSchemas?: unknown;\n };\n const schemas = module.connectPluginConfigSchemas;\n return typeof schemas === \"object\" && schemas !== null\n ? (schemas as Record<string, unknown>)\n : undefined;\n}\n"],"names":[],"mappings":";;;;;;;;;AAaA,MAAM,uBAAuB;;;;;;;;;AAU7B,eAAsB,6BACpB,aACA,SACA,MACA,OACe;CACf,IAAI,YAAY,KAAA,KAAa,QAAQ,WAAW,GAAG;CACnD,MAAM,UAAU,MAAM,wBAAwB,WAAW;CACzD,IAAI,CAAC,SAAS;CACd,KAAK,MAAM,SAAS,uBAAuB,SAAS,KAAK,GAAG;EAC1D,IAAI,CAAC,mBAAmB,OAAO,IAAI,GAAG;EACtC,MAAM,SAAS,QAAQ,MAAM;EAC7B,IAAI,CAAC,aAAa,MAAM,GAAG;EAC3B,MAAM,SAAS,OAAO,UAAU,MAAM,MAAM;EAC5C,IAAI,OAAO,SAAS;EACpB,MAAM,SAAS,OAAO,MAAM,OAAO,KAAK,UAAU;GAEhD,OAAO,OADK,CAAC,UAAU,GAAG,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GACvC,EAAE,IAAI,MAAM;EAC9B,CAAC;EACD,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,MAAM,OAAO,iBAAiB,OAAO,KAAK,IAAI,GAChF;CACF;AACF;AAEA,eAAe,wBACb,aAC8C;CAC9C,MAAM,iBAAiB,cACrB,cAAc,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CAAC,IACxD;CACA,IAAI;CACJ,IAAI;EACF,OAAO,eAAe,QAAQ,oBAAoB;CACpD,QAAQ;EACN;CACF;CAIA,MAAM,WAAU,MAHM,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CAG1B;CACvB,OAAO,OAAO,YAAY,YAAY,YAAY,OAC7C,UACD,KAAA;AACN","debug_id":"8ca9dd41-32ca-5b24-848d-bafd97044f07"}
1
+ {"version":3,"file":"connect-plugin-configs-tVn11Qb_.mjs","sources":["../src/runners/connect-plugin-configs.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n entryActiveForVerb,\n isSchemaLike,\n normalizePluginEntries,\n PluginError,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\n\n/** The zod-only entry Connect publishes with every built-in plugin's entry\n * config schema, keyed by plugin specifier. */\nconst PLUGIN_CONFIGS_ENTRY = \"@powerhousedao/connect/plugin-configs\";\n\n/**\n * Validate the entry configs of the Connect plugins composed for `verb`\n * before Connect boots, so a typo fails at `ph run` naming the plugin and the\n * key instead of at browser boot. The schemas come from the project's own\n * `@powerhousedao/connect/plugin-configs` (resolved from the project tree,\n * like runner and plugin modules); without it, or for a specifier it has no\n * schema for, the browser's own validation stays the only check.\n */\nexport async function validateConnectPluginConfigs(\n projectRoot: string,\n entries: readonly PluginEntryData[] | undefined,\n verb: string,\n where: string,\n): Promise<void> {\n if (entries === undefined || entries.length === 0) return;\n const schemas = await loadPluginConfigSchemas(projectRoot);\n if (!schemas) return;\n for (const entry of normalizePluginEntries(entries, where)) {\n if (!entryActiveForVerb(entry, verb)) continue;\n const schema = schemas[entry.module];\n if (!isSchemaLike(schema)) continue;\n const parsed = schema.safeParse(entry.config);\n if (parsed.success) continue;\n const issues = parsed.error.issues.map((issue) => {\n const key = [\"config\", ...issue.path.map(String)].join(\".\");\n return ` - ${key}: ${issue.message}`;\n });\n throw new PluginError(\n `${where}: config for plugin \"${entry.module}\" is invalid:\\n${issues.join(\"\\n\")}`,\n );\n }\n}\n\nasync function loadPluginConfigSchemas(\n projectRoot: string,\n): Promise<Record<string, unknown> | undefined> {\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let file: string;\n try {\n file = projectRequire.resolve(PLUGIN_CONFIGS_ENTRY);\n } catch {\n return undefined;\n }\n const module = (await import(pathToFileURL(file).href)) as {\n connectPluginConfigSchemas?: unknown;\n };\n const schemas = module.connectPluginConfigSchemas;\n return typeof schemas === \"object\" && schemas !== null\n ? (schemas as Record<string, unknown>)\n : undefined;\n}\n"],"names":[],"mappings":";;;;;;;;;AAaA,MAAM,uBAAuB;;;;;;;;;AAU7B,eAAsB,6BACpB,aACA,SACA,MACA,OACe;CACf,IAAI,YAAY,KAAA,KAAa,QAAQ,WAAW,GAAG;CACnD,MAAM,UAAU,MAAM,wBAAwB,WAAW;CACzD,IAAI,CAAC,SAAS;CACd,KAAK,MAAM,SAAS,uBAAuB,SAAS,KAAK,GAAG;EAC1D,IAAI,CAAC,mBAAmB,OAAO,IAAI,GAAG;EACtC,MAAM,SAAS,QAAQ,MAAM;EAC7B,IAAI,CAAC,aAAa,MAAM,GAAG;EAC3B,MAAM,SAAS,OAAO,UAAU,MAAM,MAAM;EAC5C,IAAI,OAAO,SAAS;EACpB,MAAM,SAAS,OAAO,MAAM,OAAO,KAAK,UAAU;GAEhD,OAAO,OADK,CAAC,UAAU,GAAG,MAAM,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GACvC,EAAE,IAAI,MAAM;EAC9B,CAAC;EACD,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,MAAM,OAAO,iBAAiB,OAAO,KAAK,IAAI,GAChF;CACF;AACF;AAEA,eAAe,wBACb,aAC8C;CAC9C,MAAM,iBAAiB,cACrB,cAAc,KAAK,KAAK,aAAa,cAAc,CAAC,CAAC,CAAC,IACxD;CACA,IAAI;CACJ,IAAI;EACF,OAAO,eAAe,QAAQ,oBAAoB;CACpD,QAAQ;EACN;CACF;CAIA,MAAM,WAAU,MAHM,OAAO,cAAc,IAAI,CAAC,CAAC,MAAA,CAG1B;CACvB,OAAO,OAAO,YAAY,YAAY,YAAY,OAC7C,UACD,KAAA;AACN","debug_id":"d433bf73-ee3a-5afe-8a0e-f4693f603432"}
@@ -1,4 +1,4 @@
1
- import { t as runConnectStudio } from "./connect-studio-qmgFWSt8.mjs";
1
+ import { t as runConnectStudio } from "./connect-studio-C0LLX1TD.mjs";
2
2
  export { runConnectStudio };
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]="630f1abe-86a3-5757-b719-e759e60050f5")}catch(e){}}();
4
- //# debugId=630f1abe-86a3-5757-b719-e759e60050f5
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]="0d9bc7df-c740-5b58-b0e3-5faedacc420d")}catch(e){}}();
4
+ //# debugId=0d9bc7df-c740-5b58-b0e3-5faedacc420d
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="72edcf39-645f-5ed2-9768-6dee1da1a9ed")}catch(e){}}();
3
- import { r as buildStudioConnectOverride } from "./cli-connect-override-CpHjVMDt.mjs";
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]="f27a5bd4-fb09-526b-b839-fc851277079f")}catch(e){}}();
3
+ import { r as buildStudioConnectOverride } from "./cli-connect-override-Bv5y96A5.mjs";
4
4
  import { t as switchboardProxy } from "./switchboard-proxy-CGfMtENM.mjs";
5
5
  import { readFileSync, watch } from "node:fs";
6
6
  import { join } from "node:path";
@@ -77,5 +77,5 @@ async function runConnectStudio(args, customLogger, callerOverride, { routes, ca
77
77
  //#endregion
78
78
  export { runConnectStudio as t };
79
79
 
80
- //# sourceMappingURL=connect-studio-qmgFWSt8.mjs.map
81
- //# debugId=72edcf39-645f-5ed2-9768-6dee1da1a9ed
80
+ //# sourceMappingURL=connect-studio-C0LLX1TD.mjs.map
81
+ //# debugId=f27a5bd4-fb09-526b-b839-fc851277079f
@@ -1 +1 @@
1
- {"version":3,"file":"connect-studio-qmgFWSt8.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n};\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n { routes, cacheDir, reloadOnConfigChange, proxy }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) return first;\n\n let server = first;\n let loaded = readConfig(configFile);\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n const restart = async () => {\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await server.close();\n server = await start(false);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file !== CONFIG_FILE) return;\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n });\n watcher.unref();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAWA,MAAM,cAAc;AACpB,MAAM,qBAAqB;AAW3B,SAAS,WAAW,MAAuB;CACzC,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EAEN;CACF;AACF;;AAGA,eAAsB,iBACpB,MACA,cACA,gBAGA,EAAE,QAAQ,UAAU,sBAAsB,UAAgC,CAAC,GACnD;CACxB,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,aAAa,KAAK,SAAS,WAAW;CAE5C,MAAM,QAAQ,OAAO,UAAmB;EACtC,MAAM,WACJ,OAAO,mBAAmB,aAAa,eAAe,IAAI;EAC5D,MAAM,aAAa,yBAAyB;GAC1C;GACA;GACA,oBAAoB,2BAA2B,MAAM,QAAQ;GAC7D;GACA;EACF,CAAC;EACD,MAAM,kBAAgC;GAEpC,QAAQ;IACN;IACA;IACA,MAAM,SAAS;IACf;IACA;IACA,GAAI,QAAQ,EAAE,OAAO,iBAAiB,KAAK,EAAE,IAAI,CAAC;GACpD;GACA;EACF;EACA,MAAM,SAAS,MAAM,aAAa,YAAY,YAAY,eAAe,CAAC;EAC1E,MAAM,OAAO,OAAO;EACpB,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,MAAM,CAAC;EAC9D,OAAO;CACT;CAEA,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,IAAI,WAAW,MAAM,UAAU;CAC/B,IAAI,CAAC,sBAAsB,OAAO;CAElC,IAAI,SAAS;CACb,IAAI,SAAS,WAAW,UAAU;CAClC,IAAI;CACJ,IAAI,WAAW,QAAQ,QAAQ;CAC/B,MAAM,UAAU,YAAY;EAC1B,MAAM,UAAU,WAAW,UAAU;EACrC,IAAI,YAAY,KAAA,KAAa,kBAAkB,SAAS,MAAM,GAAG;EACjE,SAAS;EACT,OAAO,OAAO,OAAO,KACnB,aAAa,YAAY,uCACzB,EAAE,WAAW,KAAK,CACpB;EACA,MAAM,OAAO,MAAM;EACnB,SAAS,MAAM,MAAM,KAAK;CAC5B;CAaA,MAXsB,UAAU,QAAQ,SAAS;EAC/C,IAAI,SAAS,aAAa;EAC1B,aAAa,KAAK;EAClB,QAAQ,iBAAiB;GACvB,WAAW,SAAS,KAAK,OAAO,CAAC,CAAC,OAAO,UAAmB;IAC1D,OAAO,OAAO,OAAO,MACnB,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC9F;GACF,CAAC;EACH,GAAG,kBAAkB;CACvB,CACM,CAAC,CAAC,MAAM;CACd,OAAO;AACT","debug_id":"72edcf39-645f-5ed2-9768-6dee1da1a9ed"}
1
+ {"version":3,"file":"connect-studio-C0LLX1TD.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n};\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n { routes, cacheDir, reloadOnConfigChange, proxy }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) return first;\n\n let server = first;\n let loaded = readConfig(configFile);\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n const restart = async () => {\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await server.close();\n server = await start(false);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file !== CONFIG_FILE) return;\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n });\n watcher.unref();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAWA,MAAM,cAAc;AACpB,MAAM,qBAAqB;AAW3B,SAAS,WAAW,MAAuB;CACzC,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EAEN;CACF;AACF;;AAGA,eAAsB,iBACpB,MACA,cACA,gBAGA,EAAE,QAAQ,UAAU,sBAAsB,UAAgC,CAAC,GACnD;CACxB,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,aAAa,KAAK,SAAS,WAAW;CAE5C,MAAM,QAAQ,OAAO,UAAmB;EACtC,MAAM,WACJ,OAAO,mBAAmB,aAAa,eAAe,IAAI;EAC5D,MAAM,aAAa,yBAAyB;GAC1C;GACA;GACA,oBAAoB,2BAA2B,MAAM,QAAQ;GAC7D;GACA;EACF,CAAC;EACD,MAAM,kBAAgC;GAEpC,QAAQ;IACN;IACA;IACA,MAAM,SAAS;IACf;IACA;IACA,GAAI,QAAQ,EAAE,OAAO,iBAAiB,KAAK,EAAE,IAAI,CAAC;GACpD;GACA;EACF;EACA,MAAM,SAAS,MAAM,aAAa,YAAY,YAAY,eAAe,CAAC;EAC1E,MAAM,OAAO,OAAO;EACpB,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,MAAM,CAAC;EAC9D,OAAO;CACT;CAEA,MAAM,QAAQ,MAAM,MAAM,IAAI;CAC9B,IAAI,WAAW,MAAM,UAAU;CAC/B,IAAI,CAAC,sBAAsB,OAAO;CAElC,IAAI,SAAS;CACb,IAAI,SAAS,WAAW,UAAU;CAClC,IAAI;CACJ,IAAI,WAAW,QAAQ,QAAQ;CAC/B,MAAM,UAAU,YAAY;EAC1B,MAAM,UAAU,WAAW,UAAU;EACrC,IAAI,YAAY,KAAA,KAAa,kBAAkB,SAAS,MAAM,GAAG;EACjE,SAAS;EACT,OAAO,OAAO,OAAO,KACnB,aAAa,YAAY,uCACzB,EAAE,WAAW,KAAK,CACpB;EACA,MAAM,OAAO,MAAM;EACnB,SAAS,MAAM,MAAM,KAAK;CAC5B;CAaA,MAXsB,UAAU,QAAQ,SAAS;EAC/C,IAAI,SAAS,aAAa;EAC1B,aAAa,KAAK;EAClB,QAAQ,iBAAiB;GACvB,WAAW,SAAS,KAAK,OAAO,CAAC,CAAC,OAAO,UAAmB;IAC1D,OAAO,OAAO,OAAO,MACnB,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC9F;GACF,CAAC;EACH,GAAG,kBAAkB;CACvB,CACM,CAAC,CAAC,MAAM;CACd,OAAO;AACT","debug_id":"f27a5bd4-fb09-526b-b839-fc851277079f"}
@@ -1,7 +1,7 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="90281515-fbc7-5ef6-a96b-c1bf0052a971")}catch(e){}}();
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]="83992fb2-0f08-58f7-82ff-1b52277f747b")}catch(e){}}();
3
3
  import { a as custom, d as string, g as prettifyError, l as record, o as literal, u as strictObject } from "./schemas-ByfuhvAb.mjs";
4
- import { $ as takesCspRegistrySync, A as loadProducers, B as processResolveEnv, C as hostSchemaIssues, F as outputSitesOf, H as projectDriveIdWith, I as planCompound, K as resolveHostOutputs, L as prepareMember, M as memberVerbOf, O as kindShapeIssues, P as outputRefsOf, Q as substituteBuiltinEnv, S as getVerb, T as isPlainObject, U as readProjectName, V as producerOutputsSchemas, Y as resolveRunnerModule, Z as runnerOutputsSchema, a as TokenResolutionError, b as findRemovedForms, c as checkTokenSites, f as compoundStartVerb, j as memberForRef, k as loadHost, n as HostLoadError, p as declaredHostSchemas, r as ONE_SHOT_VERBS, s as checkOutputPaths, tt as unsetEnvMessage, v as envSitesOf, w as isBuiltinEnvName } from "./compound-YHuVvCFd-C5NLunJf.mjs";
4
+ import { $ as takesCspRegistrySync, A as loadProducers, B as processResolveEnv, C as hostSchemaIssues, F as outputSitesOf, H as projectDriveIdWith, I as planCompound, K as resolveHostOutputs, L as prepareMember, M as memberVerbOf, O as kindShapeIssues, P as outputRefsOf, Q as substituteBuiltinEnv, S as getVerb, T as isPlainObject, U as readProjectName, V as producerOutputsSchemas, Y as resolveRunnerModule, Z as runnerOutputsSchema, a as TokenResolutionError, b as findRemovedForms, c as checkTokenSites, f as compoundStartVerb, j as memberForRef, k as loadHost, n as HostLoadError, p as declaredHostSchemas, r as ONE_SHOT_VERBS, s as checkOutputPaths, tt as unsetEnvMessage, v as envSitesOf, w as isBuiltinEnvName } from "./compound-GhJAA2dK-Cj36zhoQ.mjs";
5
5
  import "node:module";
6
6
  import "node:fs";
7
7
  import path from "node:path";
@@ -10,7 +10,7 @@ import { DRIVE_ICON_MAX_BYTES, resolveImageRef } from "@powerhousedao/shared/con
10
10
  import "@powerhousedao/shared/connect/origin-placeholder";
11
11
  import crypto from "node:crypto";
12
12
  import "node:url";
13
- import "@powerhousedao/shared/host-tokens";
13
+ import { switchboardOfDrive } from "@powerhousedao/shared/host-tokens";
14
14
  //#region ../../packages/host-core/dist/index.mjs
15
15
  /** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */
16
16
  async function checkHost(name, options) {
@@ -409,6 +409,79 @@ function explainDrivePlan(plan) {
409
409
  return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;
410
410
  })].join("\n");
411
411
  }
412
+ function projectStorage(name, storage) {
413
+ switch (storage.kind) {
414
+ case "idb": return { kind: "idb" };
415
+ case "memory": return { kind: "memory" };
416
+ case "path":
417
+ if (!storage.dataDir) throw new Error(`Backend "${name}": storage kind "path" requires dataDir.`);
418
+ return {
419
+ kind: "path",
420
+ dataDir: storage.dataDir
421
+ };
422
+ case "postgres": throw new Error(`Backend "${name}": storage kind "postgres" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a "remote" backend at the switchboard that owns that database instead.`);
423
+ }
424
+ }
425
+ /** One backend → one descriptor. The protocol's featureFlags ride every
426
+ * descriptor (they are fleet consensus, not per-backend). A remote backend
427
+ * must carry remote.url — provision() requires it. */
428
+ function backendToDescriptor(name, backend, protocol) {
429
+ const descriptor = {
430
+ kind: backend.kind,
431
+ name
432
+ };
433
+ if (descriptor.kind === "remote") {
434
+ const url = backend.remote?.url;
435
+ if (!url) throw new Error(`Backend "${name}" is kind "remote" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);
436
+ descriptor.remote = { url };
437
+ return descriptor;
438
+ }
439
+ if (backend.storage) descriptor.storage = projectStorage(name, backend.storage);
440
+ if (backend.packages) descriptor.packages = backend.packages;
441
+ if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;
442
+ return descriptor;
443
+ }
444
+ /** All named backends, in placement-primary-first order (the order a
445
+ * createReactorClients step would provision them). */
446
+ function backendsToDescriptors(reactor) {
447
+ const backends = reactor?.backends;
448
+ if (!backends) return [];
449
+ const names = Object.keys(backends);
450
+ const primary = reactor.placement?.primary;
451
+ return (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));
452
+ }
453
+ const LOCAL_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
454
+ /**
455
+ * Structural multi-reactor (phase 4): true when the block names BOTH a local
456
+ * backend (in-process/worker — the tab's own reactor) and a remote one. This
457
+ * is the shape Connect's routing client serves; a lone remote backend is an
458
+ * attach-only host (assistant/agent shape), not a routed tab.
459
+ */
460
+ function isStructuralMultiReactor(reactor) {
461
+ const backends = reactor?.backends;
462
+ if (!backends) return false;
463
+ const kinds = Object.values(backends).map((b) => b.kind);
464
+ return kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === "remote");
465
+ }
466
+ /** The remote backends' drive addresses, placement order. */
467
+ function remoteBackendUrls(reactor) {
468
+ return backendsToDescriptors(reactor).filter((d) => d.kind === "remote").map((d) => d.remote?.url).filter((u) => typeof u === "string");
469
+ }
470
+ /** The remote backends by host key, placement order. */
471
+ function remoteBackends(reactor) {
472
+ return backendsToDescriptors(reactor).flatMap((d) => d.kind === "remote" && d.remote ? [{
473
+ name: d.name,
474
+ url: d.remote.url
475
+ }] : []);
476
+ }
477
+ /**
478
+ * The shared `reactor` host-config block and its projections onto the
479
+ * Switchboard config / Connect runtime config. Phase 2 of uniform-runners: makes
480
+ * the reactor block live through the bridge runners, BEFORE track R replaces
481
+ * the projection with reactor-monitor's provision(). The headline is
482
+ * single-sourced `reactor.protocol` — both projections read the same block, so
483
+ * client and server cannot diverge, and a contradicting pre-set env fails boot.
484
+ */
412
485
  /** The single primary backend for phase-2 projection (multi-backend routing is
413
486
  * track R). Prefers placement.primary, else "main"/"local", else the first. */
414
487
  function primaryBackend(reactor) {
@@ -477,7 +550,7 @@ function reactorClientMode(reactor) {
477
550
  }
478
551
  /** Project the reactor block onto the Connect runtime config: protocol →
479
552
  * connect.reactor (same shape), backend topology → instance.reactorWorker
480
- * (legacy) + instance.reactorClient (the explicit 4-way selector),
553
+ * (legacy), instance.reactorClient and instance.remoteBackends,
481
554
  * workflows → app.workflowsEnabled. */
482
555
  function projectReactorToConnect(reactor) {
483
556
  const connect = {};
@@ -486,7 +559,8 @@ function projectReactorToConnect(reactor) {
486
559
  const mode = reactorClientMode(reactor);
487
560
  if (backend?.kind !== void 0 || mode !== void 0) connect.instance = {
488
561
  ...backend?.kind !== void 0 ? { reactorWorker: backend.kind === "worker" } : {},
489
- ...mode !== void 0 ? { reactorClient: mode } : {}
562
+ ...mode !== void 0 ? { reactorClient: mode } : {},
563
+ ...mode === "router" || mode === "remote" ? { remoteBackends: remoteBackends(reactor) } : {}
490
564
  };
491
565
  if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
492
566
  return { connect };
@@ -513,64 +587,6 @@ function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
513
587
  const conflict = protocolConflicts(protocol, env, hostFile).at(0);
514
588
  if (conflict) throw new Error(conflict);
515
589
  }
516
- function projectStorage(name, storage) {
517
- switch (storage.kind) {
518
- case "idb": return { kind: "idb" };
519
- case "memory": return { kind: "memory" };
520
- case "path":
521
- if (!storage.dataDir) throw new Error(`Backend "${name}": storage kind "path" requires dataDir.`);
522
- return {
523
- kind: "path",
524
- dataDir: storage.dataDir
525
- };
526
- case "postgres": throw new Error(`Backend "${name}": storage kind "postgres" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a "remote" backend at the switchboard that owns that database instead.`);
527
- }
528
- }
529
- /** One backend → one descriptor. The protocol's featureFlags ride every
530
- * descriptor (they are fleet consensus, not per-backend). A remote backend
531
- * must carry remote.url — provision() requires it. */
532
- function backendToDescriptor(name, backend, protocol) {
533
- const descriptor = {
534
- kind: backend.kind,
535
- name
536
- };
537
- if (descriptor.kind === "remote") {
538
- const url = backend.remote?.url;
539
- if (!url) throw new Error(`Backend "${name}" is kind "remote" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);
540
- descriptor.remote = { url };
541
- return descriptor;
542
- }
543
- if (backend.storage) descriptor.storage = projectStorage(name, backend.storage);
544
- if (backend.packages) descriptor.packages = backend.packages;
545
- if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;
546
- return descriptor;
547
- }
548
- /** All named backends, in placement-primary-first order (the order a
549
- * createReactorClients step would provision them). */
550
- function backendsToDescriptors(reactor) {
551
- const backends = reactor?.backends;
552
- if (!backends) return [];
553
- const names = Object.keys(backends);
554
- const primary = reactor.placement?.primary;
555
- return (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));
556
- }
557
- const LOCAL_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
558
- /**
559
- * Structural multi-reactor (phase 4): true when the block names BOTH a local
560
- * backend (in-process/worker — the tab's own reactor) and a remote one. This
561
- * is the shape Connect's routing client serves; a lone remote backend is an
562
- * attach-only host (assistant/agent shape), not a routed tab.
563
- */
564
- function isStructuralMultiReactor(reactor) {
565
- const backends = reactor?.backends;
566
- if (!backends) return false;
567
- const kinds = Object.values(backends).map((b) => b.kind);
568
- return kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === "remote");
569
- }
570
- /** The remote backends' drive addresses, placement order. */
571
- function remoteBackendUrls(reactor) {
572
- return backendsToDescriptors(reactor).filter((d) => d.kind === "remote").map((d) => d.remote?.url).filter((u) => typeof u === "string");
573
- }
574
590
  /**
575
591
  * Instance-fact projection for compound hosts: the drives a compound's
576
592
  * reactor member created, projected into the Connect member's runtime-config
@@ -636,8 +652,50 @@ function projectDrivesIntoConnect(input) {
636
652
  preserveStrategy: "preserve-all"
637
653
  } };
638
654
  }
655
+ /** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */
656
+ function servesSlug(declared, served) {
657
+ return served === declared || served.startsWith(`${declared}-`) && /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1));
658
+ }
659
+ /** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */
660
+ function placeConnectDrives(reactor, defaultDrives) {
661
+ const remotes = remoteBackends(reactor).flatMap(({ name, url }) => {
662
+ const at = switchboardOfDrive(url);
663
+ return at ? [{
664
+ name,
665
+ base: at.base
666
+ }] : [];
667
+ });
668
+ if (remotes.length === 0) return { defaultDrives: [...defaultDrives] };
669
+ const placement = Object.entries(reactor?.placement?.drives ?? {});
670
+ const matched = /* @__PURE__ */ new Set();
671
+ const placed = defaultDrives.map((drive) => {
672
+ if (!("url" in drive)) return drive;
673
+ const at = switchboardOfDrive(drive.url);
674
+ const backend = remotes.find((remote) => remote.base === at?.base)?.name;
675
+ if (!at || !backend) return drive;
676
+ const entry = placement.find(([slug]) => servesSlug(slug, at.slug));
677
+ if (entry) matched.add(entry[0]);
678
+ return entry?.[1] === backend ? {
679
+ ...drive,
680
+ backend,
681
+ sync: false
682
+ } : {
683
+ ...drive,
684
+ backend
685
+ };
686
+ });
687
+ const names = new Set(remotes.map((remote) => remote.name));
688
+ const collections = Object.fromEntries(placement.filter(([slug, backend]) => !matched.has(slug) && names.has(backend)).map(([slug, backend]) => [slug, {
689
+ backend,
690
+ sync: false
691
+ }]));
692
+ return Object.keys(collections).length > 0 ? {
693
+ defaultDrives: placed,
694
+ collections
695
+ } : { defaultDrives: placed };
696
+ }
639
697
  //#endregion
640
- export { seedDrives as _, isStructuralMultiReactor as a, primaryBackend as c, protocolConflicts as d, protocolEnv as f, resolveDriveDeclaration as g, remoteBackendUrls as h, exportHost as i, projectDrivesIntoConnect as l, rebaseDriveUrl as m, checkHost as n, mergeDefaultDrives as o, reactorBlockToSwitchboardConfig as p, explainDrivePlan as r, mergeDrivePlan as s, assertProtocolConsistency as t, projectReactorToConnect as u };
698
+ export { resolveDriveDeclaration as _, isStructuralMultiReactor as a, placeConnectDrives as c, projectReactorToConnect as d, protocolConflicts as f, remoteBackendUrls as g, rebaseDriveUrl as h, exportHost as i, primaryBackend as l, reactorBlockToSwitchboardConfig as m, checkHost as n, mergeDefaultDrives as o, protocolEnv as p, explainDrivePlan as r, mergeDrivePlan as s, assertProtocolConsistency as t, projectDrivesIntoConnect as u, seedDrives as v };
641
699
 
642
- //# sourceMappingURL=dist-BlpdH3RP.mjs.map
643
- //# debugId=90281515-fbc7-5ef6-a96b-c1bf0052a971
700
+ //# sourceMappingURL=dist-BiB5aiS6.mjs.map
701
+ //# debugId=83992fb2-0f08-58f7-82ff-1b52277f747b