@powerhousedao/ph-cli 6.2.3-dev.57 → 6.2.3-dev.59

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 (54) hide show
  1. package/dist/{cli-connect-override-DGXyoqdV.mjs → cli-connect-override-65mFEDEB.mjs} +4 -4
  2. package/dist/{cli-connect-override-DGXyoqdV.mjs.map → cli-connect-override-65mFEDEB.mjs.map} +1 -1
  3. package/dist/cli.mjs +5 -5
  4. package/dist/{connect-build-EYGNSUc_.mjs → connect-build-D9zrBKG4.mjs} +4 -4
  5. package/dist/{connect-build-EYGNSUc_.mjs.map → connect-build-D9zrBKG4.mjs.map} +1 -1
  6. package/dist/{connect-config-BDmghUZF.mjs → connect-config-C1tf7DqD.mjs} +4 -4
  7. package/dist/{connect-config-BDmghUZF.mjs.map → connect-config-C1tf7DqD.mjs.map} +1 -1
  8. package/dist/{connect-studio-CM4t2tWz.mjs → connect-studio-BbsQuED_.mjs} +3 -3
  9. package/dist/{connect-studio-sc-e0xBI.mjs → connect-studio-Q93rzqnC.mjs} +4 -4
  10. package/dist/{connect-studio-sc-e0xBI.mjs.map → connect-studio-Q93rzqnC.mjs.map} +1 -1
  11. package/dist/{dist-BVyjAjXL.mjs → dist-D5lAfbKQ.mjs} +55 -5
  12. package/dist/dist-D5lAfbKQ.mjs.map +1 -0
  13. package/dist/explain-BHB_4rJ3.mjs +27 -0
  14. package/dist/explain-BHB_4rJ3.mjs.map +1 -0
  15. package/dist/feature-flags-xwqcHEWC.mjs +4 -0
  16. package/dist/host-schemas-CL_wFpY7-DOvIjrBA.mjs +478 -0
  17. package/dist/host-schemas-CL_wFpY7-DOvIjrBA.mjs.map +1 -0
  18. package/dist/{index-s1ABBFjB.d.mts → index-CApW1xbO.d.mts} +3 -3
  19. package/dist/{index-s1ABBFjB.d.mts.map → index-CApW1xbO.d.mts.map} +1 -1
  20. package/dist/{init-B6dv9eCs.mjs → init-ScuT3z7P.mjs} +4 -4
  21. package/dist/{init-B6dv9eCs.mjs.map → init-ScuT3z7P.mjs.map} +1 -1
  22. package/dist/ph-cli-commands-BxKtXZgb.mjs +4 -0
  23. package/dist/{ph-cli-commands-B95L289j.mjs → ph-cli-commands-DGOKk392.mjs} +23 -10
  24. package/dist/{ph-cli-commands-B95L289j.mjs.map → ph-cli-commands-DGOKk392.mjs.map} +1 -1
  25. package/dist/{host-schemas-C_MLcYX6-B2qQIdZ-.mjs → plugins-DtJUVtyg.mjs} +200 -308
  26. package/dist/plugins-DtJUVtyg.mjs.map +1 -0
  27. package/dist/reactor-env-D9p2G8jW.mjs +4 -0
  28. package/dist/{reactor-env-CtavpGtJ.mjs → reactor-env-Da_bfekg.mjs} +4 -4
  29. package/dist/{reactor-env-CtavpGtJ.mjs.map → reactor-env-Da_bfekg.mjs.map} +1 -1
  30. package/dist/{run-sugar-Dqn7up5U.mjs → run-sugar-Dq3ZrLL_.mjs} +4 -4
  31. package/dist/{run-sugar-Dqn7up5U.mjs.map → run-sugar-Dq3ZrLL_.mjs.map} +1 -1
  32. package/dist/runners/compound.d.mts +40 -3
  33. package/dist/runners/compound.d.mts.map +1 -1
  34. package/dist/runners/compound.mjs +6 -5
  35. package/dist/runners/compound.mjs.map +1 -1
  36. package/dist/runners/connect.d.mts +49 -5
  37. package/dist/runners/connect.d.mts.map +1 -1
  38. package/dist/runners/connect.mjs +57 -12
  39. package/dist/runners/connect.mjs.map +1 -1
  40. package/dist/runners/switchboard.d.mts +48 -5
  41. package/dist/runners/switchboard.d.mts.map +1 -1
  42. package/dist/runners/switchboard.mjs +62 -17
  43. package/dist/runners/switchboard.mjs.map +1 -1
  44. package/dist/{start-run-CAgkeWI1.mjs → start-run-DsZRHbM1.mjs} +4 -4
  45. package/dist/{start-run-CAgkeWI1.mjs.map → start-run-DsZRHbM1.mjs.map} +1 -1
  46. package/dist/{vetra-BY-MHg9R.mjs → vetra-BNJZ5LHN.mjs} +6 -6
  47. package/dist/{vetra-BY-MHg9R.mjs.map → vetra-BNJZ5LHN.mjs.map} +1 -1
  48. package/package.json +12 -12
  49. package/dist/dist-BVyjAjXL.mjs.map +0 -1
  50. package/dist/feature-flags-DhEVzlCC.mjs +0 -23
  51. package/dist/feature-flags-DhEVzlCC.mjs.map +0 -1
  52. package/dist/host-schemas-C_MLcYX6-B2qQIdZ-.mjs.map +0 -1
  53. package/dist/ph-cli-commands-C-uB91lq.mjs +0 -4
  54. package/dist/reactor-env-BXG9PlMa.mjs +0 -4
@@ -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]="2501e434-4b6e-50f8-b96e-8b7747da3e36")}catch(e){}}();
3
- import { i as mergeDefaultDrives } from "./host-schemas-C_MLcYX6-B2qQIdZ-.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]="1e44cdf3-7946-5e2c-bb9f-344e49236c1b")}catch(e){}}();
3
+ import { a as mergeDefaultDrives } from "./host-schemas-CL_wFpY7-DOvIjrBA.mjs";
4
4
  import { deepMerge, phConnectRuntimeConfigSchema } from "@powerhousedao/shared/connect";
5
5
  import AjvNs from "ajv";
6
6
  import { isPlainObject, stringToPath } from "remeda";
@@ -289,5 +289,5 @@ function buildStudioConnectOverride(args, callerOverride) {
289
289
  //#endregion
290
290
  export { parseDefaultDrivesUrl as a, validateConnectKeyValue as c, wasFlagExplicitlyPassed as i, validateConnectPatch as l, buildConnectFlagPatch as n, normalizeKey as o, buildStudioConnectOverride as r, parseCliValue as s, buildCliConnectOverride as t };
291
291
 
292
- //# sourceMappingURL=cli-connect-override-DGXyoqdV.mjs.map
293
- //# debugId=2501e434-4b6e-50f8-b96e-8b7747da3e36
292
+ //# sourceMappingURL=cli-connect-override-65mFEDEB.mjs.map
293
+ //# debugId=1e44cdf3-7946-5e2c-bb9f-344e49236c1b
@@ -1 +1 @@
1
- {"version":3,"file":"cli-connect-override-DGXyoqdV.mjs","sources":["../src/utils/connect-config-validation.ts","../src/utils/parse-default-drives.ts","../src/utils/cli-connect-override.ts"],"sourcesContent":["// Ajv-backed validation for `ph connect config` writes.\n//\n// Two entry points:\n//\n// - validateConnectKeyValue(key, value)\n// For the `<key> <value>` form. Sets the value at the dotted path inside a\n// stub connect block, then validates the result against the runtime schema.\n// Catches both invalid paths (key doesn't map to a real field) and invalid\n// types (e.g. `connect.renown.chainId \"abc\"` — schema says number).\n//\n// - validateConnectPatch(patch)\n// For the `--json` form. Validates the whole patch as a partial connect.*\n// blob. Same schema, but we only check the keys actually present in the\n// patch (additional keys still fail per `additionalProperties: false`).\n//\n// Both return a typed `connect.*` partial on success or throw with a multi-\n// line, actionable message on failure.\n\nimport { phConnectRuntimeConfigSchema } from \"@powerhousedao/shared/connect\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport AjvNs from \"ajv\";\nimport { isPlainObject, stringToPath } from \"remeda\";\n\ntype PlainObject = Record<string, unknown>;\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\n// Ajv ships as CJS — under NodeNext ESM the default lands on `.default` while\n// types still point at the class on the namespace. Normalize the constructor.\ntype AjvCtor = new (opts?: Record<string, unknown>) => {\n compile: (schema: unknown) => AjvValidate;\n};\ntype AjvError = {\n instancePath?: string;\n message?: string;\n params?: { additionalProperty?: string };\n};\ntype AjvValidate = ((data: unknown) => boolean) & {\n errors?: AjvError[] | null;\n};\n\nconst Ajv = ((AjvNs as unknown as { default?: AjvCtor }).default ??\n (AjvNs as unknown as AjvCtor)) as AjvCtor;\n\nconst ajv = new Ajv({ allErrors: true, strict: false });\nconst validateConnect: AjvValidate = ajv.compile(phConnectRuntimeConfigSchema);\n\n/**\n * Parse the CLI-supplied value. Tries JSON first so `true`, `42`, `\"a\"`,\n * `null`, `[1,2]` coerce; falls back to the raw string for unquoted text.\n *\n * Examples:\n * \"true\" -> true (boolean)\n * \"42\" -> 42 (number)\n * '\"x\"' -> \"x\" (string, quoted)\n * \"x\" -> \"x\" (string, bare)\n * \"[1,2]\" -> [1, 2] (array)\n */\nexport function parseCliValue(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Strip the optional leading \"connect.\" prefix so callers can pass either\n * \"connect.renown.url\" or \"renown.url\" interchangeably.\n */\nexport function normalizeKey(key: string): string {\n return key.startsWith(\"connect.\") ? key.slice(\"connect.\".length) : key;\n}\n\nfunction formatErrors(errors: AjvError[] | null | undefined): string {\n if (!errors || errors.length === 0) return \"unknown validation error\";\n return errors\n .map((e) => {\n const path = e.instancePath || \"(root)\";\n const extra = e.params?.additionalProperty;\n const suffix = extra === undefined ? \"\" : ` (${JSON.stringify(extra)})`;\n return ` ${path} ${e.message ?? \"\"}${suffix}`.trim();\n })\n .join(\"\\n\");\n}\n\n/**\n * Validate a single `<key> <value>` pair. Returns the parsed connect-partial\n * that, when deep-merged into the existing config, applies the change.\n *\n * Throws on:\n * - Empty key\n * - Path that doesn't exist in the schema\n * - Value whose type doesn't match the schema at the leaf path\n */\nexport function validateConnectKeyValue(\n key: string,\n rawValue: string,\n): ConnectPartial {\n const normalized = normalizeKey(key);\n if (!normalized) {\n throw new Error(\n \"ph connect config: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n const parsed = parseCliValue(rawValue);\n // Build a nested-stub object from the dotted path so Ajv can validate\n // the value's shape against the schema (e.g. \"renown.url\" + parsed →\n // { renown: { url: parsed } }). Remeda's `setPath` requires the path\n // to exist; this is the sparse-creation case, so we fold the parts.\n const stub = stringToPath(normalized).reduceRight<unknown>(\n (acc, key) => ({ [String(key)]: acc }),\n parsed,\n ) as PlainObject;\n if (!validateConnect(stub)) {\n throw new Error(\n `ph connect config: validation failed for key=\"${normalized}\" value=${JSON.stringify(parsed)} (parsed as ${typeof parsed}):\\n${formatErrors(validateConnect.errors)}`,\n );\n }\n return stub;\n}\n\n/**\n * Validate a `--json` bulk override. Returns the parsed partial.\n *\n * `packageRegistryUrl` is a top-level runtime field (not part of the\n * `connect.*` schema). If present in the payload, it is extracted before\n * validation so the connect-only blob can be checked against the schema,\n * then re-attached on the returned object so the caller can route it.\n *\n * `command` prefixes error messages (e.g. \"ph connect build\").\n */\nexport function validateConnectPatch(\n raw: string,\n command = \"ph connect config\",\n): ConnectPartial & {\n packageRegistryUrl?: unknown;\n} {\n const label = `${command} --json`;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(\n `${label}: invalid JSON (${msg}). Expected a partial connect.* blob, e.g. --json '{\"renown\":{\"url\":\"...\"}}'.`,\n { cause: e },\n );\n }\n if (!isPlainObject(parsed)) {\n throw new Error(\n `${label}: payload must be a JSON object, got ${typeof parsed}.`,\n );\n }\n if (Object.prototype.hasOwnProperty.call(parsed, \"connect\")) {\n const inner = JSON.stringify((parsed as PlainObject).connect);\n throw new Error(\n `${label}: pass the connect.* block without the \"connect\" wrapper, e.g. --json '${inner}'.`,\n );\n }\n // Extract `packageRegistryUrl` (top-level field, not in the connect schema)\n // before validating, so a payload like `{\"packageRegistryUrl\":\"…\"}` doesn't\n // fail the `additionalProperties: false` check on the connect schema.\n const top = parsed as PlainObject;\n const hasPackageRegistryUrl = Object.prototype.hasOwnProperty.call(\n top,\n \"packageRegistryUrl\",\n );\n const packageRegistryUrl = top.packageRegistryUrl;\n const connectOnly: PlainObject = { ...top };\n delete connectOnly.packageRegistryUrl;\n if (!validateConnect(connectOnly)) {\n throw new Error(\n `${label}: validation failed:\\n${formatErrors(validateConnect.errors)}\\nExpected a partial connect.* blob with nested keys, e.g. --json '{\"app\":{\"workflowsEnabled\":true}}'.`,\n );\n }\n return hasPackageRegistryUrl\n ? ({ ...connectOnly, packageRegistryUrl } as ConnectPartial & {\n packageRegistryUrl?: unknown;\n })\n : (connectOnly as ConnectPartial);\n}\n","/**\n * Comma-separated URL string → array of `{url, name: null, icon: null}`\n * entries suitable for `connect.drives.defaultDrives`. Used by ph-cli's\n * CLI-override builders and by `ph vetra` when forwarding the local\n * switchboard's drive URLs into the runtime config.\n */\nexport const parseDefaultDrivesUrl = (\n v: string,\n): Array<{ url: string; name: null; icon: null }> =>\n v\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null }));\n","// Builds a `connectOverride` partial from CLI flags. Shared by:\n//\n// - `ph connect build` — uses `buildCliConnectOverride` to produce the\n// `cliConnectOverride` patch the Vite plugin applies at the top of the\n// precedence ladder:\n//\n// DEFAULT_CONNECT_CONFIG < env-var seeds < source connect.* < --json < individual --flag\n//\n// - `ph connect config` — uses `buildConnectFlagPatch` (the per-field\n// partial builder) to translate flag-set values into the patch that\n// gets dual-written to source + dist `powerhouse.config.json`.\n//\n// `--json` parses as a partial `connect.*` blob and merges in first; then any\n// individual --flag values merge on top, so a flag beats a conflicting --json\n// value.\n\nimport type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { deepMerge } from \"@powerhousedao/shared/connect\";\nimport { mergeDefaultDrives } from \"@powerhousedao/host-core\";\nimport type { ConnectBuildArgs, ConnectStudioArgs } from \"../types.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"./connect-config-validation.js\";\nimport { parseDefaultDrivesUrl } from \"./parse-default-drives.js\";\n\ntype PlainObject = Record<string, unknown>;\n\n/**\n * Structural input shape consumed by `buildConnectFlagPatch`. Every property\n * is strict-optional — `undefined` means \"user did not pass this flag\" and\n * the path is excluded from the patch.\n *\n * Callers with cmd-ts-typed args where some flags have built-in defaults\n * (e.g. the 4 commonArgs flags `--base` / `--log-level` /\n * `--default-drives-url` / `--drive-preserve-strategy`) must filter through\n * `wasFlagExplicitlyPassed` BEFORE building this input — otherwise default\n * values like `\"info\"` will silently clobber source `powerhouse.config.json`\n * values.\n */\nexport type ConnectFlagInput = {\n // Strict-optional flags from connectRuntimeOverrideArgs (excluding\n // `packagesRegistry`, which is a top-level runtime field — see\n // `buildCliConnectOverride`).\n json?: string | undefined;\n renownUrl?: string | undefined;\n renownNetworkId?: string | undefined;\n renownChainId?: number | undefined;\n renownNamespace?: string | undefined;\n renownSwitchboardUrl?: string | undefined;\n allowAddDrive?: boolean | undefined;\n externalPackages?: boolean | undefined;\n workflows?: boolean | undefined;\n remoteDrivesEnabled?: boolean | undefined;\n remoteDrivesAllowAdd?: boolean | undefined;\n remoteDrivesAllowDelete?: boolean | undefined;\n localDrivesEnabled?: boolean | undefined;\n localDrivesAllowAdd?: boolean | undefined;\n localDrivesAllowDelete?: boolean | undefined;\n appName?: string | undefined;\n homeBackground?: string | undefined;\n sentryDsn?: string | undefined;\n sentryEnv?: string | undefined;\n sentryTracingEnabled?: boolean | undefined;\n // commonArgs flags. Callers must apply `wasFlagExplicitlyPassed`\n // filtering (see above).\n basePath?: string | undefined;\n logLevel?: string | undefined;\n defaultDrivesUrl?: string | undefined;\n drivesPreserveStrategy?: string | undefined;\n};\n\n// Schema-validates `--json` so unknown keys, a `connect` wrapper or wrong\n// types fail instead of being dropped from the dist config.\nfunction parseJsonOverride(raw: string | undefined): PlainObject {\n if (raw === undefined || raw === \"\") return {};\n return validateConnectPatch(raw, \"ph connect build\") as PlainObject;\n}\n\nfunction setIfDefined<V>(\n target: PlainObject,\n key: string,\n value: V | undefined,\n): void {\n if (value !== undefined) target[key] = value;\n}\n\n/**\n * Detect whether the user literally typed `--<longName>` on the command\n * line. Used to gate the 4 commonArgs flags through `cliConnectOverride` —\n * those flags have cmd-ts defaults, so their parsed value is always\n * defined, and a naive merge would silently clobber source values with the\n * default on every build.\n *\n * Handles both `--flag value` and `--flag=value` forms.\n */\nexport function wasFlagExplicitlyPassed(longName: string): boolean {\n const dashed = `--${longName}`;\n return process.argv.some(\n (arg) => arg === dashed || arg.startsWith(`${dashed}=`),\n );\n}\n\n/**\n * Build a `connect.*` partial from the 20 field flags. Only includes paths\n * the user explicitly set (undefined values are excluded).\n *\n * Single source of truth for the flag → JSON-path mapping; consumed by both\n * `ph connect build` and `ph connect config`.\n */\nexport function buildConnectFlagPatch(args: ConnectFlagInput): PlainObject {\n const out: PlainObject = {};\n\n const app: PlainObject = {};\n setIfDefined(app, \"basePath\", args.basePath);\n setIfDefined(app, \"logLevel\", args.logLevel);\n setIfDefined(app, \"workflowsEnabled\", args.workflows);\n if (Object.keys(app).length > 0) out.app = app;\n\n const renown: PlainObject = {};\n setIfDefined(renown, \"url\", args.renownUrl);\n setIfDefined(renown, \"networkId\", args.renownNetworkId);\n setIfDefined(renown, \"chainId\", args.renownChainId);\n setIfDefined(renown, \"namespace\", args.renownNamespace);\n setIfDefined(renown, \"switchboardUrl\", args.renownSwitchboardUrl);\n if (Object.keys(renown).length > 0) out.renown = renown;\n\n const packages: PlainObject = {};\n setIfDefined(packages, \"externalEnabled\", args.externalPackages);\n if (Object.keys(packages).length > 0) out.packages = packages;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option).\n const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (args.homeBackground !== undefined) {\n branding.homeBackground =\n args.homeBackground === \"\" ? null : args.homeBackground;\n }\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --sentry-dsn: empty string is the explicit \"set null\" form (disables\n // Sentry). Same pattern as --home-background.\n const sentry: PlainObject = {};\n if (args.sentryDsn !== undefined) {\n sentry.dsn = args.sentryDsn === \"\" ? null : args.sentryDsn;\n }\n setIfDefined(sentry, \"env\", args.sentryEnv);\n setIfDefined(sentry, \"tracing\", args.sentryTracingEnabled);\n if (Object.keys(sentry).length > 0) out.sentry = sentry;\n\n const drives: PlainObject = {};\n setIfDefined(drives, \"allowAddDrive\", args.allowAddDrive);\n setIfDefined(drives, \"preserveStrategy\", args.drivesPreserveStrategy);\n if (args.defaultDrivesUrl !== undefined && args.defaultDrivesUrl !== \"\") {\n drives.defaultDrives = parseDefaultDrivesUrl(args.defaultDrivesUrl);\n }\n\n const remote: PlainObject = {};\n setIfDefined(remote, \"enabled\", args.remoteDrivesEnabled);\n setIfDefined(remote, \"allowAdd\", args.remoteDrivesAllowAdd);\n setIfDefined(remote, \"allowDelete\", args.remoteDrivesAllowDelete);\n\n const local: PlainObject = {};\n setIfDefined(local, \"enabled\", args.localDrivesEnabled);\n setIfDefined(local, \"allowAdd\", args.localDrivesAllowAdd);\n setIfDefined(local, \"allowDelete\", args.localDrivesAllowDelete);\n\n const sections: PlainObject = {};\n if (Object.keys(remote).length > 0) sections.remote = remote;\n if (Object.keys(local).length > 0) sections.local = local;\n if (Object.keys(sections).length > 0) drives.sections = sections;\n if (Object.keys(drives).length > 0) out.drives = drives;\n\n return out;\n}\n\n/**\n * Combine `--json` and the individual flag values into the two override\n * inputs `ph connect build` forwards to the Vite plugin:\n *\n * - `connectOverride`: a partial `connect.*` patch (deep-merged at the top\n * of the runtime-config precedence ladder).\n * - `packageRegistryUrl`: a separate top-level override; mirrors the\n * source-config top-level field (the SPA reads it directly).\n *\n * `--packages-registry` and `--json` containing a top-level\n * `packageRegistryUrl` both flow into `packageRegistryUrl`; the flag wins on\n * collision. Returns `undefined` for whichever override was not supplied.\n *\n * The 4 commonArgs flags (`--base`, `--log-level`, `--default-drives-url`,\n * `--drive-preserve-strategy`) are gated through `wasFlagExplicitlyPassed`\n * because they carry cmd-ts defaults that would otherwise leak into the\n * override on every build.\n */\nexport function buildCliConnectOverride(args: ConnectBuildArgs): {\n connectOverride: PHConnectRuntimeConfig | undefined;\n packageRegistryUrl: string | undefined;\n} {\n const fromJson = parseJsonOverride(args.json);\n\n const input: ConnectFlagInput = {\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 // commonArgs flags — only forward when the user explicitly passed them.\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\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 const fromFlags = buildConnectFlagPatch(input);\n\n // Positional `<key> <value>` override (only set when both are present;\n // `runConnectBuild` rejects the 1-positional case up front because build\n // has no read mode). Layered on top of --json + flags so a positional\n // override wins on collision — matches the user's literal command line.\n let positionalRegistry: string | undefined;\n let fromPositional: PlainObject = {};\n if (args.keyPositional !== undefined && args.valuePositional !== undefined) {\n const normalized = normalizeKey(args.keyPositional);\n if (!normalized) {\n throw new Error(\n \"ph connect build: positional <key> cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect build: positional packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n positionalRegistry = parsed;\n } else {\n fromPositional = validateConnectKeyValue(\n normalized,\n args.valuePositional,\n );\n }\n }\n\n // Top-level `packageRegistryUrl` can come from --json (top-level),\n // --packages-registry flag, or positional `packageRegistryUrl <value>`.\n // Precedence (highest → lowest): positional > flag > --json.\n const jsonRegistry =\n typeof fromJson.packageRegistryUrl === \"string\"\n ? (fromJson.packageRegistryUrl as string)\n : undefined;\n const packageRegistryUrl =\n positionalRegistry ?? args.packagesRegistry ?? jsonRegistry;\n // Strip the top-level field from the JSON patch before deep-merging into\n // the connect partial — it isn't a `connect.*` field.\n const jsonConnect = { ...fromJson };\n delete jsonConnect.packageRegistryUrl;\n\n const hasJsonConnect = Object.keys(jsonConnect).length > 0;\n const hasFlags = Object.keys(fromFlags).length > 0;\n const hasPositional = Object.keys(fromPositional).length > 0;\n const connectOverride =\n !hasJsonConnect && !hasFlags && !hasPositional\n ? undefined\n : deepMerge(\n deepMerge(\n jsonConnect as PHConnectRuntimeConfig,\n fromFlags as PHConnectRuntimeConfig,\n ),\n fromPositional as PHConnectRuntimeConfig,\n );\n\n return { connectOverride, packageRegistryUrl };\n}\n\n/**\n * Parallel of `buildCliConnectOverride` for `ph connect studio` / `ph vetra`.\n * Studio only exposes the 4 commonArgs flags (`--base`, `--log-level`,\n * `--default-drives-url`, `--drive-preserve-strategy`); each is gated through\n * `wasFlagExplicitlyPassed` so cmd-ts defaults don't leak into the override.\n *\n * `callerOverride` is supplied by wrappers around studio (notably `ph vetra`,\n * which sets default drives + preserveStrategy directly). The flag override\n * deep-merges on top of it: caller choices apply for every flag the user\n * didn't type, and an explicitly passed flag wins for its own field —\n * except `drives.defaultDrives`, which merges additively: a flag's drives\n * are appended to the caller's list (de-duplicated by drive identity) rather\n * than replacing it, so vetra's own drives stay in Connect's default set.\n * Without a caller override (plain `ph connect studio`) only the flag can\n * carry defaultDrives, so that command's behavior is unchanged.\n */\nexport function buildStudioConnectOverride(\n args: ConnectStudioArgs,\n callerOverride: PHConnectRuntimeConfig | undefined,\n): PHConnectRuntimeConfig | undefined {\n const flagOverride = buildConnectFlagPatch({\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\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 renownNamespace: args.renownNamespace,\n }) as PHConnectRuntimeConfig;\n\n // Studio commands (`ph connect studio`, `ph vetra`) always run in studio\n // mode: Connect loads the vetra package and offers builder document types.\n const studioOverride: PHConnectRuntimeConfig = { app: { studioMode: true } };\n const layers = [callerOverride, flagOverride, studioOverride].filter(\n (o): o is PHConnectRuntimeConfig =>\n o !== undefined && Object.keys(o).length > 0,\n );\n const merged = layers.reduce(\n (acc, o) => deepMerge(acc, o),\n {} as PHConnectRuntimeConfig,\n );\n\n // `deepMerge` replaces arrays, so the flag's defaultDrives would clobber\n // the caller's list; re-apply them as the de-duplicated union instead.\n // Only needed when two or more layers contribute default drives (the\n // plain-studio single-layer case is already exactly the flag's list).\n const driveGroups = layers\n .map((l) => l.drives?.defaultDrives)\n .filter(\n (d): d is PHConnectDefaultDrive[] => Array.isArray(d) && d.length > 0,\n );\n if (driveGroups.length > 1) {\n merged.drives = {\n ...merged.drives,\n defaultDrives: mergeDefaultDrives(...driveGroups),\n };\n }\n return merged;\n}\n"],"names":[],"mappings":";;;;;;;AA4CA,MAAM,kBAA+B,KAJvB,MAA2C,WACtD,OAEiB;CAAE,WAAW;CAAM,QAAQ;AAAM,CACd,CAAC,CAAC,QAAQ,4BAA4B;;;;;;;;;;;;AAa7E,SAAgB,cAAc,KAAsB;CAClD,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,aAAa,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KAAK,EACd;CAAC,CAAC,CAAC,QAC3D,MACC,MAAM,KAAA,KAAa,OAAO,KAAK,CAAC,CAAC,CAAC,SAAS,CAC/C;CACA,MAAM,SAAS,OAAO,QACnB,KAAK,MAAM,UAAU,KAAK,CAAC,GAC5B,CAAC,CACH;CAMA,MAAM,cAAc,OACjB,KAAK,MAAM,EAAE,QAAQ,aAAa,CAAC,CACnC,QACE,MAAoC,MAAM,QAAQ,CAAC,KAAK,EAAE,SAAS,CACtE;CACF,IAAI,YAAY,SAAS,GACvB,OAAO,SAAS;EACd,GAAG,OAAO;EACV,eAAe,mBAAmB,GAAG,WAAW;CAClD;CAEF,OAAO;AACT","debug_id":"2501e434-4b6e-50f8-b96e-8b7747da3e36"}
1
+ {"version":3,"file":"cli-connect-override-65mFEDEB.mjs","sources":["../src/utils/connect-config-validation.ts","../src/utils/parse-default-drives.ts","../src/utils/cli-connect-override.ts"],"sourcesContent":["// Ajv-backed validation for `ph connect config` writes.\n//\n// Two entry points:\n//\n// - validateConnectKeyValue(key, value)\n// For the `<key> <value>` form. Sets the value at the dotted path inside a\n// stub connect block, then validates the result against the runtime schema.\n// Catches both invalid paths (key doesn't map to a real field) and invalid\n// types (e.g. `connect.renown.chainId \"abc\"` — schema says number).\n//\n// - validateConnectPatch(patch)\n// For the `--json` form. Validates the whole patch as a partial connect.*\n// blob. Same schema, but we only check the keys actually present in the\n// patch (additional keys still fail per `additionalProperties: false`).\n//\n// Both return a typed `connect.*` partial on success or throw with a multi-\n// line, actionable message on failure.\n\nimport { phConnectRuntimeConfigSchema } from \"@powerhousedao/shared/connect\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport AjvNs from \"ajv\";\nimport { isPlainObject, stringToPath } from \"remeda\";\n\ntype PlainObject = Record<string, unknown>;\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\n// Ajv ships as CJS — under NodeNext ESM the default lands on `.default` while\n// types still point at the class on the namespace. Normalize the constructor.\ntype AjvCtor = new (opts?: Record<string, unknown>) => {\n compile: (schema: unknown) => AjvValidate;\n};\ntype AjvError = {\n instancePath?: string;\n message?: string;\n params?: { additionalProperty?: string };\n};\ntype AjvValidate = ((data: unknown) => boolean) & {\n errors?: AjvError[] | null;\n};\n\nconst Ajv = ((AjvNs as unknown as { default?: AjvCtor }).default ??\n (AjvNs as unknown as AjvCtor)) as AjvCtor;\n\nconst ajv = new Ajv({ allErrors: true, strict: false });\nconst validateConnect: AjvValidate = ajv.compile(phConnectRuntimeConfigSchema);\n\n/**\n * Parse the CLI-supplied value. Tries JSON first so `true`, `42`, `\"a\"`,\n * `null`, `[1,2]` coerce; falls back to the raw string for unquoted text.\n *\n * Examples:\n * \"true\" -> true (boolean)\n * \"42\" -> 42 (number)\n * '\"x\"' -> \"x\" (string, quoted)\n * \"x\" -> \"x\" (string, bare)\n * \"[1,2]\" -> [1, 2] (array)\n */\nexport function parseCliValue(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Strip the optional leading \"connect.\" prefix so callers can pass either\n * \"connect.renown.url\" or \"renown.url\" interchangeably.\n */\nexport function normalizeKey(key: string): string {\n return key.startsWith(\"connect.\") ? key.slice(\"connect.\".length) : key;\n}\n\nfunction formatErrors(errors: AjvError[] | null | undefined): string {\n if (!errors || errors.length === 0) return \"unknown validation error\";\n return errors\n .map((e) => {\n const path = e.instancePath || \"(root)\";\n const extra = e.params?.additionalProperty;\n const suffix = extra === undefined ? \"\" : ` (${JSON.stringify(extra)})`;\n return ` ${path} ${e.message ?? \"\"}${suffix}`.trim();\n })\n .join(\"\\n\");\n}\n\n/**\n * Validate a single `<key> <value>` pair. Returns the parsed connect-partial\n * that, when deep-merged into the existing config, applies the change.\n *\n * Throws on:\n * - Empty key\n * - Path that doesn't exist in the schema\n * - Value whose type doesn't match the schema at the leaf path\n */\nexport function validateConnectKeyValue(\n key: string,\n rawValue: string,\n): ConnectPartial {\n const normalized = normalizeKey(key);\n if (!normalized) {\n throw new Error(\n \"ph connect config: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n const parsed = parseCliValue(rawValue);\n // Build a nested-stub object from the dotted path so Ajv can validate\n // the value's shape against the schema (e.g. \"renown.url\" + parsed →\n // { renown: { url: parsed } }). Remeda's `setPath` requires the path\n // to exist; this is the sparse-creation case, so we fold the parts.\n const stub = stringToPath(normalized).reduceRight<unknown>(\n (acc, key) => ({ [String(key)]: acc }),\n parsed,\n ) as PlainObject;\n if (!validateConnect(stub)) {\n throw new Error(\n `ph connect config: validation failed for key=\"${normalized}\" value=${JSON.stringify(parsed)} (parsed as ${typeof parsed}):\\n${formatErrors(validateConnect.errors)}`,\n );\n }\n return stub;\n}\n\n/**\n * Validate a `--json` bulk override. Returns the parsed partial.\n *\n * `packageRegistryUrl` is a top-level runtime field (not part of the\n * `connect.*` schema). If present in the payload, it is extracted before\n * validation so the connect-only blob can be checked against the schema,\n * then re-attached on the returned object so the caller can route it.\n *\n * `command` prefixes error messages (e.g. \"ph connect build\").\n */\nexport function validateConnectPatch(\n raw: string,\n command = \"ph connect config\",\n): ConnectPartial & {\n packageRegistryUrl?: unknown;\n} {\n const label = `${command} --json`;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(\n `${label}: invalid JSON (${msg}). Expected a partial connect.* blob, e.g. --json '{\"renown\":{\"url\":\"...\"}}'.`,\n { cause: e },\n );\n }\n if (!isPlainObject(parsed)) {\n throw new Error(\n `${label}: payload must be a JSON object, got ${typeof parsed}.`,\n );\n }\n if (Object.prototype.hasOwnProperty.call(parsed, \"connect\")) {\n const inner = JSON.stringify((parsed as PlainObject).connect);\n throw new Error(\n `${label}: pass the connect.* block without the \"connect\" wrapper, e.g. --json '${inner}'.`,\n );\n }\n // Extract `packageRegistryUrl` (top-level field, not in the connect schema)\n // before validating, so a payload like `{\"packageRegistryUrl\":\"…\"}` doesn't\n // fail the `additionalProperties: false` check on the connect schema.\n const top = parsed as PlainObject;\n const hasPackageRegistryUrl = Object.prototype.hasOwnProperty.call(\n top,\n \"packageRegistryUrl\",\n );\n const packageRegistryUrl = top.packageRegistryUrl;\n const connectOnly: PlainObject = { ...top };\n delete connectOnly.packageRegistryUrl;\n if (!validateConnect(connectOnly)) {\n throw new Error(\n `${label}: validation failed:\\n${formatErrors(validateConnect.errors)}\\nExpected a partial connect.* blob with nested keys, e.g. --json '{\"app\":{\"workflowsEnabled\":true}}'.`,\n );\n }\n return hasPackageRegistryUrl\n ? ({ ...connectOnly, packageRegistryUrl } as ConnectPartial & {\n packageRegistryUrl?: unknown;\n })\n : (connectOnly as ConnectPartial);\n}\n","/**\n * Comma-separated URL string → array of `{url, name: null, icon: null}`\n * entries suitable for `connect.drives.defaultDrives`. Used by ph-cli's\n * CLI-override builders and by `ph vetra` when forwarding the local\n * switchboard's drive URLs into the runtime config.\n */\nexport const parseDefaultDrivesUrl = (\n v: string,\n): Array<{ url: string; name: null; icon: null }> =>\n v\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null }));\n","// Builds a `connectOverride` partial from CLI flags. Shared by:\n//\n// - `ph connect build` — uses `buildCliConnectOverride` to produce the\n// `cliConnectOverride` patch the Vite plugin applies at the top of the\n// precedence ladder:\n//\n// DEFAULT_CONNECT_CONFIG < env-var seeds < source connect.* < --json < individual --flag\n//\n// - `ph connect config` — uses `buildConnectFlagPatch` (the per-field\n// partial builder) to translate flag-set values into the patch that\n// gets dual-written to source + dist `powerhouse.config.json`.\n//\n// `--json` parses as a partial `connect.*` blob and merges in first; then any\n// individual --flag values merge on top, so a flag beats a conflicting --json\n// value.\n\nimport type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport { deepMerge } from \"@powerhousedao/shared/connect\";\nimport { mergeDefaultDrives } from \"@powerhousedao/host-core\";\nimport type { ConnectBuildArgs, ConnectStudioArgs } from \"../types.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"./connect-config-validation.js\";\nimport { parseDefaultDrivesUrl } from \"./parse-default-drives.js\";\n\ntype PlainObject = Record<string, unknown>;\n\n/**\n * Structural input shape consumed by `buildConnectFlagPatch`. Every property\n * is strict-optional — `undefined` means \"user did not pass this flag\" and\n * the path is excluded from the patch.\n *\n * Callers with cmd-ts-typed args where some flags have built-in defaults\n * (e.g. the 4 commonArgs flags `--base` / `--log-level` /\n * `--default-drives-url` / `--drive-preserve-strategy`) must filter through\n * `wasFlagExplicitlyPassed` BEFORE building this input — otherwise default\n * values like `\"info\"` will silently clobber source `powerhouse.config.json`\n * values.\n */\nexport type ConnectFlagInput = {\n // Strict-optional flags from connectRuntimeOverrideArgs (excluding\n // `packagesRegistry`, which is a top-level runtime field — see\n // `buildCliConnectOverride`).\n json?: string | undefined;\n renownUrl?: string | undefined;\n renownNetworkId?: string | undefined;\n renownChainId?: number | undefined;\n renownNamespace?: string | undefined;\n renownSwitchboardUrl?: string | undefined;\n allowAddDrive?: boolean | undefined;\n externalPackages?: boolean | undefined;\n workflows?: boolean | undefined;\n remoteDrivesEnabled?: boolean | undefined;\n remoteDrivesAllowAdd?: boolean | undefined;\n remoteDrivesAllowDelete?: boolean | undefined;\n localDrivesEnabled?: boolean | undefined;\n localDrivesAllowAdd?: boolean | undefined;\n localDrivesAllowDelete?: boolean | undefined;\n appName?: string | undefined;\n homeBackground?: string | undefined;\n sentryDsn?: string | undefined;\n sentryEnv?: string | undefined;\n sentryTracingEnabled?: boolean | undefined;\n // commonArgs flags. Callers must apply `wasFlagExplicitlyPassed`\n // filtering (see above).\n basePath?: string | undefined;\n logLevel?: string | undefined;\n defaultDrivesUrl?: string | undefined;\n drivesPreserveStrategy?: string | undefined;\n};\n\n// Schema-validates `--json` so unknown keys, a `connect` wrapper or wrong\n// types fail instead of being dropped from the dist config.\nfunction parseJsonOverride(raw: string | undefined): PlainObject {\n if (raw === undefined || raw === \"\") return {};\n return validateConnectPatch(raw, \"ph connect build\") as PlainObject;\n}\n\nfunction setIfDefined<V>(\n target: PlainObject,\n key: string,\n value: V | undefined,\n): void {\n if (value !== undefined) target[key] = value;\n}\n\n/**\n * Detect whether the user literally typed `--<longName>` on the command\n * line. Used to gate the 4 commonArgs flags through `cliConnectOverride` —\n * those flags have cmd-ts defaults, so their parsed value is always\n * defined, and a naive merge would silently clobber source values with the\n * default on every build.\n *\n * Handles both `--flag value` and `--flag=value` forms.\n */\nexport function wasFlagExplicitlyPassed(longName: string): boolean {\n const dashed = `--${longName}`;\n return process.argv.some(\n (arg) => arg === dashed || arg.startsWith(`${dashed}=`),\n );\n}\n\n/**\n * Build a `connect.*` partial from the 20 field flags. Only includes paths\n * the user explicitly set (undefined values are excluded).\n *\n * Single source of truth for the flag → JSON-path mapping; consumed by both\n * `ph connect build` and `ph connect config`.\n */\nexport function buildConnectFlagPatch(args: ConnectFlagInput): PlainObject {\n const out: PlainObject = {};\n\n const app: PlainObject = {};\n setIfDefined(app, \"basePath\", args.basePath);\n setIfDefined(app, \"logLevel\", args.logLevel);\n setIfDefined(app, \"workflowsEnabled\", args.workflows);\n if (Object.keys(app).length > 0) out.app = app;\n\n const renown: PlainObject = {};\n setIfDefined(renown, \"url\", args.renownUrl);\n setIfDefined(renown, \"networkId\", args.renownNetworkId);\n setIfDefined(renown, \"chainId\", args.renownChainId);\n setIfDefined(renown, \"namespace\", args.renownNamespace);\n setIfDefined(renown, \"switchboardUrl\", args.renownSwitchboardUrl);\n if (Object.keys(renown).length > 0) out.renown = renown;\n\n const packages: PlainObject = {};\n setIfDefined(packages, \"externalEnabled\", args.externalPackages);\n if (Object.keys(packages).length > 0) out.packages = packages;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option).\n const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (args.homeBackground !== undefined) {\n branding.homeBackground =\n args.homeBackground === \"\" ? null : args.homeBackground;\n }\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --sentry-dsn: empty string is the explicit \"set null\" form (disables\n // Sentry). Same pattern as --home-background.\n const sentry: PlainObject = {};\n if (args.sentryDsn !== undefined) {\n sentry.dsn = args.sentryDsn === \"\" ? null : args.sentryDsn;\n }\n setIfDefined(sentry, \"env\", args.sentryEnv);\n setIfDefined(sentry, \"tracing\", args.sentryTracingEnabled);\n if (Object.keys(sentry).length > 0) out.sentry = sentry;\n\n const drives: PlainObject = {};\n setIfDefined(drives, \"allowAddDrive\", args.allowAddDrive);\n setIfDefined(drives, \"preserveStrategy\", args.drivesPreserveStrategy);\n if (args.defaultDrivesUrl !== undefined && args.defaultDrivesUrl !== \"\") {\n drives.defaultDrives = parseDefaultDrivesUrl(args.defaultDrivesUrl);\n }\n\n const remote: PlainObject = {};\n setIfDefined(remote, \"enabled\", args.remoteDrivesEnabled);\n setIfDefined(remote, \"allowAdd\", args.remoteDrivesAllowAdd);\n setIfDefined(remote, \"allowDelete\", args.remoteDrivesAllowDelete);\n\n const local: PlainObject = {};\n setIfDefined(local, \"enabled\", args.localDrivesEnabled);\n setIfDefined(local, \"allowAdd\", args.localDrivesAllowAdd);\n setIfDefined(local, \"allowDelete\", args.localDrivesAllowDelete);\n\n const sections: PlainObject = {};\n if (Object.keys(remote).length > 0) sections.remote = remote;\n if (Object.keys(local).length > 0) sections.local = local;\n if (Object.keys(sections).length > 0) drives.sections = sections;\n if (Object.keys(drives).length > 0) out.drives = drives;\n\n return out;\n}\n\n/**\n * Combine `--json` and the individual flag values into the two override\n * inputs `ph connect build` forwards to the Vite plugin:\n *\n * - `connectOverride`: a partial `connect.*` patch (deep-merged at the top\n * of the runtime-config precedence ladder).\n * - `packageRegistryUrl`: a separate top-level override; mirrors the\n * source-config top-level field (the SPA reads it directly).\n *\n * `--packages-registry` and `--json` containing a top-level\n * `packageRegistryUrl` both flow into `packageRegistryUrl`; the flag wins on\n * collision. Returns `undefined` for whichever override was not supplied.\n *\n * The 4 commonArgs flags (`--base`, `--log-level`, `--default-drives-url`,\n * `--drive-preserve-strategy`) are gated through `wasFlagExplicitlyPassed`\n * because they carry cmd-ts defaults that would otherwise leak into the\n * override on every build.\n */\nexport function buildCliConnectOverride(args: ConnectBuildArgs): {\n connectOverride: PHConnectRuntimeConfig | undefined;\n packageRegistryUrl: string | undefined;\n} {\n const fromJson = parseJsonOverride(args.json);\n\n const input: ConnectFlagInput = {\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 // commonArgs flags — only forward when the user explicitly passed them.\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\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 const fromFlags = buildConnectFlagPatch(input);\n\n // Positional `<key> <value>` override (only set when both are present;\n // `runConnectBuild` rejects the 1-positional case up front because build\n // has no read mode). Layered on top of --json + flags so a positional\n // override wins on collision — matches the user's literal command line.\n let positionalRegistry: string | undefined;\n let fromPositional: PlainObject = {};\n if (args.keyPositional !== undefined && args.valuePositional !== undefined) {\n const normalized = normalizeKey(args.keyPositional);\n if (!normalized) {\n throw new Error(\n \"ph connect build: positional <key> cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect build: positional packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n positionalRegistry = parsed;\n } else {\n fromPositional = validateConnectKeyValue(\n normalized,\n args.valuePositional,\n );\n }\n }\n\n // Top-level `packageRegistryUrl` can come from --json (top-level),\n // --packages-registry flag, or positional `packageRegistryUrl <value>`.\n // Precedence (highest → lowest): positional > flag > --json.\n const jsonRegistry =\n typeof fromJson.packageRegistryUrl === \"string\"\n ? (fromJson.packageRegistryUrl as string)\n : undefined;\n const packageRegistryUrl =\n positionalRegistry ?? args.packagesRegistry ?? jsonRegistry;\n // Strip the top-level field from the JSON patch before deep-merging into\n // the connect partial — it isn't a `connect.*` field.\n const jsonConnect = { ...fromJson };\n delete jsonConnect.packageRegistryUrl;\n\n const hasJsonConnect = Object.keys(jsonConnect).length > 0;\n const hasFlags = Object.keys(fromFlags).length > 0;\n const hasPositional = Object.keys(fromPositional).length > 0;\n const connectOverride =\n !hasJsonConnect && !hasFlags && !hasPositional\n ? undefined\n : deepMerge(\n deepMerge(\n jsonConnect as PHConnectRuntimeConfig,\n fromFlags as PHConnectRuntimeConfig,\n ),\n fromPositional as PHConnectRuntimeConfig,\n );\n\n return { connectOverride, packageRegistryUrl };\n}\n\n/**\n * Parallel of `buildCliConnectOverride` for `ph connect studio` / `ph vetra`.\n * Studio only exposes the 4 commonArgs flags (`--base`, `--log-level`,\n * `--default-drives-url`, `--drive-preserve-strategy`); each is gated through\n * `wasFlagExplicitlyPassed` so cmd-ts defaults don't leak into the override.\n *\n * `callerOverride` is supplied by wrappers around studio (notably `ph vetra`,\n * which sets default drives + preserveStrategy directly). The flag override\n * deep-merges on top of it: caller choices apply for every flag the user\n * didn't type, and an explicitly passed flag wins for its own field —\n * except `drives.defaultDrives`, which merges additively: a flag's drives\n * are appended to the caller's list (de-duplicated by drive identity) rather\n * than replacing it, so vetra's own drives stay in Connect's default set.\n * Without a caller override (plain `ph connect studio`) only the flag can\n * carry defaultDrives, so that command's behavior is unchanged.\n */\nexport function buildStudioConnectOverride(\n args: ConnectStudioArgs,\n callerOverride: PHConnectRuntimeConfig | undefined,\n): PHConnectRuntimeConfig | undefined {\n const flagOverride = buildConnectFlagPatch({\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\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 renownNamespace: args.renownNamespace,\n }) as PHConnectRuntimeConfig;\n\n // Studio commands (`ph connect studio`, `ph vetra`) always run in studio\n // mode: Connect loads the vetra package and offers builder document types.\n const studioOverride: PHConnectRuntimeConfig = { app: { studioMode: true } };\n const layers = [callerOverride, flagOverride, studioOverride].filter(\n (o): o is PHConnectRuntimeConfig =>\n o !== undefined && Object.keys(o).length > 0,\n );\n const merged = layers.reduce(\n (acc, o) => deepMerge(acc, o),\n {} as PHConnectRuntimeConfig,\n );\n\n // `deepMerge` replaces arrays, so the flag's defaultDrives would clobber\n // the caller's list; re-apply them as the de-duplicated union instead.\n // Only needed when two or more layers contribute default drives (the\n // plain-studio single-layer case is already exactly the flag's list).\n const driveGroups = layers\n .map((l) => l.drives?.defaultDrives)\n .filter(\n (d): d is PHConnectDefaultDrive[] => Array.isArray(d) && d.length > 0,\n );\n if (driveGroups.length > 1) {\n merged.drives = {\n ...merged.drives,\n defaultDrives: m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AkBpC,MAAM,SAAS;EAAC;EAjBK,sBAAsB;GACzC,UAAU,wBAAwB,MAAM,IACpC,KAAK,kBACL,KAAA;GACJ,UAAU,wBAAwB,WAAW,IAAI,KAAK,WAAW,KAAA;GACjE,kBAAkB,wBAAwB,oBAAoB,IAC1D,KAAK,mBACL,KAAA;GACJ,wBAAwB,wBAAwB,yBAAyB,IACrE,KAAK,yBACL,KAAA;GACJ,iBAAiB,KAAK;EACxB,CAK2C;EAAG,EADG,KAAK,EAAE,YAAY,KAAK,EACd;CAAC,CAAC,CAAC,QAC3D,MACC,MAAM,KAAA,KAAa,OAAO,KAAK,CAAC,CAAC,CAAC,SAAS,CAC/C;CACA,MAAM,SAAS,OAAO,QACnB,KAAK,MAAM,UAAU,KAAK,CAAC,GAC5B,CAAC,CACH;CAMA,MAAM,cAAc,OACjB,KAAK,MAAM,EAAE,QAAQ,aAAa,CAAC,CACnC,QACE,MAAoC,MAAM,QAAQ,CAAC,KAAK,EAAE,SAAS,CACtE;CACF,IAAI,YAAY,SAAS,GACvB,OAAO,SAAS;EACd,GAAG,OAAO;EACV,eAAe,mBAAmB,GAAG,WAAW;CAClD;CAEF,OAAO;AACT","debug_id":"1e44cdf3-7946-5e2c-bb9f-344e49236c1b"}
package/dist/cli.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
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]="d751098f-ddb0-5813-9f72-4bdc5e15a867")}catch(e){}}();
4
- import { n as phCliCommands } from "./ph-cli-commands-B95L289j.mjs";
5
- import { t as isUniformRunnersEnabled } from "./feature-flags-DhEVzlCC.mjs";
4
+ import { n as phCliCommands } from "./ph-cli-commands-DGOKk392.mjs";
5
+ import { t as isUniformRunnersEnabled } from "./feature-flags-xwqcHEWC.mjs";
6
6
  import { initCliTelemetry } from "@powerhousedao/shared/clis/telemetry";
7
7
  import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
8
8
  import { run, subcommands } from "cmd-ts";
@@ -10,7 +10,7 @@ import { phCliHelpCommands } from "@powerhousedao/shared/clis/args";
10
10
  import { bold, yellow } from "colorette";
11
11
  //#region src/get-version.ts
12
12
  function getVersion() {
13
- return "6.2.3-dev.57";
13
+ return "6.2.3-dev.59";
14
14
  }
15
15
  //#endregion
16
16
  //#region src/utils/constants.ts
@@ -92,8 +92,8 @@ async function main() {
92
92
  });
93
93
  let args = process.argv.slice(2);
94
94
  if (isUniformRunnersEnabled()) {
95
- const { applyRunSugar } = await import("./run-sugar-Dqn7up5U.mjs");
96
- const { phCliCommands } = await import("./ph-cli-commands-C-uB91lq.mjs");
95
+ const { applyRunSugar } = await import("./run-sugar-Dq3ZrLL_.mjs");
96
+ const { phCliCommands } = await import("./ph-cli-commands-BxKtXZgb.mjs");
97
97
  const sugar = applyRunSugar(args, new Set(Object.keys(phCliCommands)), process.cwd());
98
98
  if (sugar.warning) console.warn(sugar.warning);
99
99
  args = sugar.args;
@@ -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]="6c0e458b-e512-5d5e-a00b-bf14af8e8165")}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]="9b28ceb8-46d6-5906-bf2a-97b76b418d8f")}catch(e){}}();
3
3
  import { i as runBuild } from "./build-skPHsKkL.mjs";
4
- import { t as buildCliConnectOverride } from "./cli-connect-override-DGXyoqdV.mjs";
4
+ import { t as buildCliConnectOverride } from "./cli-connect-override-65mFEDEB.mjs";
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
6
6
  import { join, resolve } from "node:path";
7
7
  import { getConfig } from "@powerhousedao/shared/clis";
@@ -214,5 +214,5 @@ function assertLocalPackagesInstalled(projectPath) {
214
214
  //#endregion
215
215
  export { runConnectBuild };
216
216
 
217
- //# sourceMappingURL=connect-build-EYGNSUc_.mjs.map
218
- //# debugId=6c0e458b-e512-5d5e-a00b-bf14af8e8165
217
+ //# sourceMappingURL=connect-build-D9zrBKG4.mjs.map
218
+ //# debugId=9b28ceb8-46d6-5906-bf2a-97b76b418d8f
@@ -1 +1 @@
1
- {"version":3,"file":"connect-build-EYGNSUc_.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\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 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 { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\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 { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\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 });\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 // 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 }\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\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 ]),\n ];\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":";;;;;;;;;;;AA4BA,eAAsB,gBAAgB,MAAwB;CAC5D,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,EAAE,iBAAiB,uBAAuB,wBAAwB,IAAI;CAE5E,MAAM,SAAS;EACb,QAAQ;EACR;EAG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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":"6c0e458b-e512-5d5e-a00b-bf14af8e8165"}
1
+ {"version":3,"file":"connect-build-D9zrBKG4.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\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 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 { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\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 { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\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 });\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 // 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 }\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\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 ]),\n ];\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":";;;;;;;;;;;AA4BA,eAAsB,gBAAgB,MAAwB;CAC5D,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,IAAI;CAK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;;;;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":"9b28ceb8-46d6-5906-bf2a-97b76b418d8f"}
@@ -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]="b5ee8144-8997-5d0a-ba19-f138a98a6e45")}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-DGXyoqdV.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]="0c4acace-56a2-540d-8d7b-0ef7680bd911")}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-65mFEDEB.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-BDmghUZF.mjs.map
196
- //# debugId=b5ee8144-8997-5d0a-ba19-f138a98a6e45
195
+ //# sourceMappingURL=connect-config-C1tf7DqD.mjs.map
196
+ //# debugId=0c4acace-56a2-540d-8d7b-0ef7680bd911
@@ -1 +1 @@
1
- {"version":3,"file":"connect-config-BDmghUZF.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) ? ` and ${distPath}` : \"\"}\\n`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA,SAAgB,UACd,KACA,OACS;CACT,IAAI,MAAe;CACnB,KAAK,MAAM,OAAO,OAAO;EACvB,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO,KAAA;EACpD,MAAO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AAK,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":"b5ee8144-8997-5d0a-ba19-f138a98a6e45"}
1
+ {"version":3,"file":"connect-config-C1tf7DqD.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) ? ` and ${distPath}` : \"\"}\\n`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA,SAAgB,UACd,KACA,OACS;CACT,IAAI,MAAe;CACnB,KAAK,MAAM,OAAO,OAAO;EACvB,IAAI,QAA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;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":"0c4acace-56a2-540d-8d7b-0ef7680bd911"}
@@ -1,4 +1,4 @@
1
- import { t as runConnectStudio } from "./connect-studio-sc-e0xBI.mjs";
1
+ import { t as runConnectStudio } from "./connect-studio-Q93rzqnC.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]="361e84db-aa48-5286-afcb-3a049627e363")}catch(e){}}();
4
- //# debugId=361e84db-aa48-5286-afcb-3a049627e363
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]="14f1766f-6368-5bb2-95d4-6e159a63e0ad")}catch(e){}}();
4
+ //# debugId=14f1766f-6368-5bb2-95d4-6e159a63e0ad
@@ -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]="07da03d6-ed5f-5632-a443-d0203b4c6304")}catch(e){}}();
3
- import { r as buildStudioConnectOverride } from "./cli-connect-override-DGXyoqdV.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]="b1c0c910-0603-521e-b113-40fcd8601fa5")}catch(e){}}();
3
+ import { r as buildStudioConnectOverride } from "./cli-connect-override-65mFEDEB.mjs";
4
4
  import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
5
5
  import { createServer, mergeConfig } from "vite";
6
6
  //#region src/services/connect-studio.ts
@@ -32,5 +32,5 @@ async function runConnectStudio(args, customLogger, callerOverride) {
32
32
  //#endregion
33
33
  export { runConnectStudio as t };
34
34
 
35
- //# sourceMappingURL=connect-studio-sc-e0xBI.mjs.map
36
- //# debugId=07da03d6-ed5f-5632-a443-d0203b4c6304
35
+ //# sourceMappingURL=connect-studio-Q93rzqnC.mjs.map
36
+ //# debugId=b1c0c910-0603-521e-b113-40fcd8601fa5
@@ -1 +1 @@
1
- {"version":3,"file":"connect-studio-sc-e0xBI.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type { InlineConfig, Logger } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\n\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?: PHConnectRuntimeConfig,\n) {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n\n const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride,\n });\n\n const devServerConfig: InlineConfig = {\n server: { port, host, open, cors, strictPort },\n customLogger,\n };\n\n const config = mergeConfig(baseConfig, devServerConfig);\n\n const server = await createServer(config);\n\n await server.listen();\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n}\n"],"names":[],"mappings":";;;;;;AAOA,eAAsB,iBACpB,MACA,cACA,gBACA;CACA,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAE5B,MAAM,qBAAqB,2BAA2B,MAAM,cAAc;CAE1E,MAAM,aAAa,yBAAyB;EAC1C;EACA;EACA;CACF,CAAC;CAOD,MAAM,SAAS,YAAY,YAAY;EAJrC,QAAQ;GAAE;GAAM;GAAM;GAAM;GAAM;EAAW;EAC7C;CAGmD,CAAC;CAEtD,MAAM,SAAS,MAAM,aAAa,MAAM;CAExC,MAAM,OAAO,OAAO;CAEpB,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;AAC/D","debug_id":"07da03d6-ed5f-5632-a443-d0203b4c6304"}
1
+ {"version":3,"file":"connect-studio-Q93rzqnC.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type { InlineConfig, Logger } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\n\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?: PHConnectRuntimeConfig,\n) {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n\n const cliConnectOverride = buildStudioConnectOverride(args, callerOverride);\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride,\n });\n\n const devServerConfig: InlineConfig = {\n server: { port, host, open, cors, strictPort },\n customLogger,\n };\n\n const config = mergeConfig(baseConfig, devServerConfig);\n\n const server = await createServer(config);\n\n await server.listen();\n\n if (printUrls) server.printUrls();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: true });\n}\n"],"names":[],"mappings":";;;;;;AAOA,eAAsB,iBACpB,MACA,cACA,gBACA;CACA,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAE5B,MAAM,qBAAqB,2BAA2B,MAAM,cAAc;CAE1E,MAAM,aAAa,yBAAyB;EAC1C;EACA;EACA;CACF,CAAC;CAOD,MAAM,SAAS,YAAY,YAAY;EAJrC,QAAQ;GAAE;GAAM;GAAM;GAAM;GAAM;EAAW;EAC7C;CAGmD,CAAC;CAEtD,MAAM,SAAS,MAAM,aAAa,MAAM;CAExC,MAAM,OAAO,OAAO;CAEpB,IAAI,WAAW,OAAO,UAAU;CAChC,IAAI,kBAAkB,OAAO,iBAAiB,EAAE,OAAO,KAAK,CAAC;AAC/D","debug_id":"b1c0c910-0603-521e-b113-40fcd8601fa5"}
@@ -1,6 +1,10 @@
1
- //#region ../../packages/host-core/dist/index.mjs
2
1
 
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]="52e2d8f9-f49d-5819-bb63-c89d9476c43f")}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]="8061e6c6-f2b3-5519-b959-5b0f89e0cf9b")}catch(e){}}();
3
+ import { g as prettifyError, i as normalizePluginEntries, n as entryActiveForVerb, r as hostTypeSatisfies, t as PluginError } from "./plugins-DtJUVtyg.mjs";
4
+ import { createRequire } from "node:module";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ //#region ../../packages/host-core/dist/index.mjs
4
8
  function projectStorage(name, storage) {
5
9
  switch (storage.kind) {
6
10
  case "idb": return { kind: "idb" };
@@ -135,8 +139,54 @@ function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
135
139
  if (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);
136
140
  }
137
141
  }
142
+ /**
143
+ * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
144
+ * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
145
+ * PROJECT dependency tree, exactly like runner modules.
146
+ */
147
+ function isHostPluginShape(value) {
148
+ return value !== null && typeof value === "object" && typeof value.name === "string";
149
+ }
150
+ /**
151
+ * Resolve host.js plugin entries into live plugins for one host boot:
152
+ * verb-filter → module resolution from the project tree (default condition,
153
+ * like runners) → factory/object contract → config validation → appliesTo.
154
+ */
155
+ async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
156
+ const normalized = normalizePluginEntries(entries, where);
157
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
158
+ const resolved = [];
159
+ for (const entry of normalized) {
160
+ if (!entryActiveForVerb(entry, verb)) continue;
161
+ let file;
162
+ try {
163
+ file = projectRequire.resolve(entry.module);
164
+ } catch {
165
+ throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
166
+ }
167
+ const exported = (await import(pathToFileURL(file).href)).default;
168
+ let plugin;
169
+ if (typeof exported === "function") plugin = exported(entry.config);
170
+ else if (isHostPluginShape(exported)) {
171
+ if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
172
+ plugin = exported;
173
+ } else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
174
+ if (plugin.configSchema) {
175
+ const parsed = plugin.configSchema.safeParse(entry.config);
176
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + prettifyError(parsed.error));
177
+ }
178
+ const appliesTo = plugin.appliesTo ?? "reactor";
179
+ if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
180
+ resolved.push({
181
+ entry,
182
+ plugin,
183
+ provenance: "dependency"
184
+ });
185
+ }
186
+ return resolved;
187
+ }
138
188
  //#endregion
139
- export { projectReactorToSwitchboard as a, projectReactorToConnect as i, isStructuralMultiReactor as n, remoteBackendUrls as o, primaryBackend as r, assertProtocolConsistency as t };
189
+ export { projectReactorToSwitchboard as a, projectReactorToConnect as i, isStructuralMultiReactor as n, remoteBackendUrls as o, primaryBackend as r, resolveHostPlugins as s, assertProtocolConsistency as t };
140
190
 
141
- //# sourceMappingURL=dist-BVyjAjXL.mjs.map
142
- //# debugId=52e2d8f9-f49d-5819-bb63-c89d9476c43f
191
+ //# sourceMappingURL=dist-D5lAfbKQ.mjs.map
192
+ //# debugId=8061e6c6-f2b3-5519-b959-5b0f89e0cf9b
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-D5lAfbKQ.mjs","sources":["../../../packages/host-core/dist/index.mjs"],"sourcesContent":["import { A as HostLoadError, C as readRunRecord, D as listVerbs, E as getVerb, F as mergeDefaultDrives, I as projectDrivesIntoConnect, L as rebaseDriveUrl, M as lintHostImports, N as loadHost, O as resolveRunnerModule, P as probeHostsFolder, S as probeRun, T as RunnerError, _ as runCompound, a as reactorBackendSchema, b as clearRunRecord, c as reactorSchema, d as drivesSchema, f as explainDrivePlan, g as seedDrives, h as resolveDriveDeclaration, i as profileSchema, j as findNonStaticValue, k as validateHost, l as runnerBaseSchema, m as projectDriveId, n as compoundHostSchema, o as reactorHostSchema, p as mergeDrivePlan, r as emittedHostSchemas, s as reactorProtocolSchema, t as childrenSchema, u as driveDeclarationSchema, v as defaultUserDataDir, w as writeRunRecord, x as isPidAlive, y as resolveUserDataPlaceholders } from \"./host-schemas-CL_wFpY7.mjs\";\nimport { PluginError, entryActiveForVerb, hostTypeSatisfies, mergeContributions, normalizePluginEntries, normalizePluginEntry, pluginEntrySchema, registerHostType, resolveOrder, runObserveHook, runObserveHookSequential, runProvideHook, runTransformHook } from \"./plugins.mjs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\n//#region src/backend-projection.ts\nfunction projectStorage(name, storage) {\n\tswitch (storage.kind) {\n\t\tcase \"idb\": return { kind: \"idb\" };\n\t\tcase \"memory\": return { kind: \"memory\" };\n\t\tcase \"path\":\n\t\t\tif (!storage.dataDir) throw new Error(`Backend \"${name}\": storage kind \"path\" requires dataDir.`);\n\t\t\treturn {\n\t\t\t\tkind: \"path\",\n\t\t\t\tdataDir: storage.dataDir\n\t\t\t};\n\t\tcase \"postgres\": throw new Error(`Backend \"${name}\": storage kind \"postgres\" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a \"remote\" backend at the switchboard that owns that database instead.`);\n\t}\n}\n/** One backend → one descriptor. The protocol's featureFlags ride every\n* descriptor (they are fleet consensus, not per-backend). A remote backend\n* must carry remote.url — provision() requires it. */\nfunction backendToDescriptor(name, backend, protocol) {\n\tconst descriptor = {\n\t\tkind: backend.kind ?? \"in-process\",\n\t\tname\n\t};\n\tif (descriptor.kind === \"remote\") {\n\t\tconst url = backend.remote?.url;\n\t\tif (!url) throw new Error(`Backend \"${name}\" is kind \"remote\" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);\n\t\tdescriptor.remote = { url };\n\t\treturn descriptor;\n\t}\n\tif (backend.storage) descriptor.storage = projectStorage(name, backend.storage);\n\tif (backend.packages) descriptor.packages = backend.packages;\n\tif (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n\treturn descriptor;\n}\n/** All named backends, in placement-primary-first order (the order a\n* createReactorClients step would provision them). */\nfunction backendsToDescriptors(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return [];\n\tconst names = Object.keys(backends);\n\tconst primary = reactor.placement?.primary;\n\treturn (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));\n}\nconst LOCAL_KINDS = /* @__PURE__ */ new Set([\n\t\"in-process\",\n\t\"worker\",\n\tvoid 0\n]);\n/**\n* Structural multi-reactor (phase 4): true when the block names BOTH a local\n* backend (in-process/worker — the tab's own reactor) and a remote one. This\n* is the shape Connect's routing client serves; a lone remote backend is an\n* attach-only host (assistant/agent shape), not a routed tab.\n*/\nfunction isStructuralMultiReactor(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return false;\n\tconst kinds = Object.values(backends).map((b) => b.kind);\n\treturn kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\");\n}\n/** The remote backends' urls, placement order — what the routing client dials. */\nfunction remoteBackendUrls(reactor) {\n\treturn backendsToDescriptors(reactor).filter((d) => d.kind === \"remote\").map((d) => d.remote?.url).filter((u) => typeof u === \"string\");\n}\n//#endregion\n//#region src/reactor-config.ts\n/** The single primary backend for phase-2 projection (multi-backend routing is\n* track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nfunction primaryBackend(reactor) {\n\tconst backends = reactor?.backends;\n\tif (!backends) return void 0;\n\tconst names = Object.keys(backends);\n\tif (names.length === 0) return void 0;\n\treturn backends[reactor.placement?.primary ?? (names.includes(\"main\") ? \"main\" : names.includes(\"local\") ? \"local\" : names[0])];\n}\nconst FLAG_ENV = {\n\tdocumentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n\tauthEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n\tauthGroups: \"REACTOR_AUTH_GROUPS\",\n\tauthConditions: \"REACTOR_AUTH_CONDITIONS\"\n};\n/** The env vars a protocol block maps onto, with their string values. Only\n* keys the block actually sets appear. */\nfunction protocolEnv(protocol) {\n\tconst env = {};\n\tif (!protocol) return env;\n\tfor (const [key, varName] of Object.entries(FLAG_ENV)) {\n\t\tconst value = protocol.featureFlags?.[key];\n\t\tif (value !== void 0) env[varName] = value ? \"true\" : \"false\";\n\t}\n\tif (protocol.createSignaturePolicy !== void 0) env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n\tif (protocol.unsupportedStoredDocuments !== void 0) env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS = protocol.unsupportedStoredDocuments;\n\treturn env;\n}\n/** Project the reactor block onto the switchboard's env + options. */\nfunction projectReactorToSwitchboard(reactor) {\n\tconst env = protocolEnv(reactor?.protocol);\n\tconst backend = primaryBackend(reactor);\n\tconst options = {};\n\tif (backend?.storage) {\n\t\tconst s = backend.storage;\n\t\tconst dbUrl = s.kind === \"postgres\" ? s.url : s.dataDir;\n\t\tif (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;\n\t}\n\tif (backend?.readModel?.url) options.dbPath = backend.readModel.url;\n\tif (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = \"true\";\n\tif (reactor?.workflows !== void 0) env.PH_WORKFLOWS_ENABLED = reactor.workflows ? \"1\" : \"0\";\n\treturn {\n\t\tenv,\n\t\toptions\n\t};\n}\n/** Project the reactor block onto the Connect runtime config: protocol →\n* connect.reactor (same shape), backend kind → instance.reactorWorker,\n* workflows → app.workflowsEnabled. */\nfunction projectReactorToConnect(reactor) {\n\tconst connect = {};\n\tif (reactor?.protocol) connect.reactor = reactor.protocol;\n\tconst backend = primaryBackend(reactor);\n\tif (backend?.kind !== void 0) connect.instance = { reactorWorker: backend.kind === \"worker\" };\n\tif (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };\n\treturn { connect };\n}\n/**\n* The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n* the host's protocol block, fail loudly naming the var, the host value, and\n* the env value. An env var that merely matches, or is unset, is fine (phase-2\n* transition keeps an operator's explicit env as an escape hatch unless it\n* disagrees with the protocol — see the WBS precedence note).\n*/\nfunction assertProtocolConsistency(protocol, env, hostFile = \"the host file\") {\n\tif (!protocol) return;\n\tconst expected = protocolEnv(protocol);\n\tfor (const [varName, hostValue] of Object.entries(expected)) {\n\t\tconst envValue = env[varName];\n\t\tif (envValue !== void 0 && envValue !== hostValue) throw new Error(`reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`);\n\t}\n}\n//#endregion\n//#region src/plugins-resolve.ts\n/**\n* NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core\n* stays browser-safe for ConnectCore — R3). Resolves host.js entries from the\n* PROJECT dependency tree, exactly like runner modules.\n*/\nfunction isHostPluginShape(value) {\n\treturn value !== null && typeof value === \"object\" && typeof value.name === \"string\";\n}\n/**\n* Resolve host.js plugin entries into live plugins for one host boot:\n* verb-filter → module resolution from the project tree (default condition,\n* like runners) → factory/object contract → config validation → appliesTo.\n*/\nasync function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {\n\tconst normalized = normalizePluginEntries(entries, where);\n\tconst projectRequire = createRequire(pathToFileURL(path.join(projectRoot, \"package.json\")).href);\n\tconst resolved = [];\n\tfor (const entry of normalized) {\n\t\tif (!entryActiveForVerb(entry, verb)) continue;\n\t\tlet file;\n\t\ttry {\n\t\t\tfile = projectRequire.resolve(entry.module);\n\t\t} catch {\n\t\t\tthrow new PluginError(`${where}: cannot resolve plugin \"${entry.module}\" from ${projectRoot}.`, \"Plugins resolve from the project dependency tree, exactly like runner modules.\");\n\t\t}\n\t\tconst exported = (await import(pathToFileURL(file).href)).default;\n\t\tlet plugin;\n\t\tif (typeof exported === \"function\") plugin = exported(entry.config);\n\t\telse if (isHostPluginShape(exported)) {\n\t\t\tif (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin \"${entry.module}\" takes no config, but the entry passes one.`);\n\t\t\tplugin = exported;\n\t\t} else throw new PluginError(`${where}: \"${entry.module}\" does not default-export a plugin object or factory.`, \"Export `{ name, hooks?, contributions? }` or `(config) => plugin`.\");\n\t\tif (plugin.configSchema) {\n\t\t\tconst parsed = plugin.configSchema.safeParse(entry.config);\n\t\t\tif (!parsed.success) throw new PluginError(`${where}: config for plugin \"${plugin.name}\" is invalid:\\n` + z.prettifyError(parsed.error));\n\t\t}\n\t\tconst appliesTo = plugin.appliesTo ?? \"reactor\";\n\t\tif (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin \"${plugin.name}\" applies to \"${appliesTo}\" hosts, but this host is \"${hostType}\".`);\n\t\tresolved.push({\n\t\t\tentry,\n\t\t\tplugin,\n\t\t\tprovenance: \"dependency\"\n\t\t});\n\t}\n\treturn resolved;\n}\n//#endregion\nexport { HostLoadError, PluginError, RunnerError, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, childrenSchema, clearRunRecord, compoundHostSchema, defaultUserDataDir, driveDeclarationSchema, drivesSchema, emittedHostSchemas, entryActiveForVerb, explainDrivePlan, findNonStaticValue, getVerb, hostTypeSatisfies, isPidAlive, isStructuralMultiReactor, lintHostImports, listVerbs, loadHost, mergeContributions, mergeDefaultDrives, mergeDrivePlan, normalizePluginEntries, normalizePluginEntry, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, profileSchema, projectDriveId, projectDrivesIntoConnect, projectReactorToConnect, projectReactorToSwitchboard, protocolEnv, reactorBackendSchema, reactorHostSchema, reactorProtocolSchema, reactorSchema, readRunRecord, rebaseDriveUrl, registerHostType, remoteBackendUrls, resolveDriveDeclaration, resolveHostPlugins, resolveOrder, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runTransformHook, runnerBaseSchema, seedDrives, validateHost, writeRunRecord };\n\n//# sourceMappingURL=index.mjs.map"],"names":["z.prettifyError"],"mappings":";;;;;;;AAOA,SAAS,eAAe,MAAM,SAAS;CACtC,QAAQ,QAAQ,MAAhB;EACC,KAAK,OAAO,OAAO,EAAE,MAAM,MAAM;EACjC,KAAK,UAAU,OAAO,EAAE,MAAM,SAAS;EACvC,KAAK;GACJ,IAAI,CAAC,QAAQ,SAAS,MAAM,IAAI,MAAM,YAAY,KAAK,yCAAyC;GAChG,OAAO;IACN,MAAM;IACN,SAAS,QAAQ;GAClB;EACD,KAAK,YAAY,MAAM,IAAI,MAAM,YAAY,KAAK,uLAAuL;CAC1O;AACD;;;;AAIA,SAAS,oBAAoB,MAAM,SAAS,UAAU;CACrD,MAAM,aAAa;EAClB,MAAM,QAAQ,QAAQ;EACtB;CACD;CACA,IAAI,WAAW,SAAS,UAAU;EACjC,MAAM,MAAM,QAAQ,QAAQ;EAC5B,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,YAAY,KAAK,8GAA8G;EACzJ,WAAW,SAAS,EAAE,IAAI;EAC1B,OAAO;CACR;CACA,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