@powerhousedao/ph-cli 6.2.3-dev.89 → 6.2.3-dev.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{check-BhShHuOZ.mjs → check-BdeBTBzN.mjs} +7 -7
  2. package/dist/check-BdeBTBzN.mjs.map +1 -0
  3. package/dist/{cli-connect-override-Dm55uCjR.mjs → cli-connect-override-CY_Zf7wG.mjs} +4 -4
  4. package/dist/{cli-connect-override-Dm55uCjR.mjs.map → cli-connect-override-CY_Zf7wG.mjs.map} +1 -1
  5. package/dist/cli.mjs +4 -4
  6. package/dist/{compound-BZb3tR_c-CAf7DitW.mjs → compound-BSOW40st-CWIT2x84.mjs} +26 -141
  7. package/dist/compound-BSOW40st-CWIT2x84.mjs.map +1 -0
  8. package/dist/{connect-build-DMKUu9mw.mjs → connect-build-6OzCZczA.mjs} +73 -5
  9. package/dist/connect-build-6OzCZczA.mjs.map +1 -0
  10. package/dist/{connect-config-B4yKClFe.mjs → connect-config-nuwLOG8I.mjs} +4 -4
  11. package/dist/{connect-config-B4yKClFe.mjs.map → connect-config-nuwLOG8I.mjs.map} +1 -1
  12. package/dist/connect-preview-DBcsUnSB.mjs +48 -0
  13. package/dist/connect-preview-DBcsUnSB.mjs.map +1 -0
  14. package/dist/{connect-studio-DaaQOVBr.mjs → connect-studio-B3amPdLj.mjs} +4 -4
  15. package/dist/{connect-studio-DaaQOVBr.mjs.map → connect-studio-B3amPdLj.mjs.map} +1 -1
  16. package/dist/{connect-studio-CJ8ImldI.mjs → connect-studio-Mhhe7W5g.mjs} +3 -3
  17. package/dist/{dist-tZHpCFn_.mjs → dist-Dw0p_A5j.mjs} +12 -308
  18. package/dist/dist-Dw0p_A5j.mjs.map +1 -0
  19. package/dist/{explain-4PQGC1BH.mjs → explain-BS1cIzPW.mjs} +5 -5
  20. package/dist/{explain-4PQGC1BH.mjs.map → explain-BS1cIzPW.mjs.map} +1 -1
  21. package/dist/{export-BfSsraKe.mjs → export-BkYfEgBr.mjs} +4 -4
  22. package/dist/{export-BfSsraKe.mjs.map → export-BkYfEgBr.mjs.map} +1 -1
  23. package/dist/{generate-all-CoLL-TJu.mjs → generate-all-sPjxvgql.mjs} +4 -4
  24. package/dist/{generate-all-CoLL-TJu.mjs.map → generate-all-sPjxvgql.mjs.map} +1 -1
  25. package/dist/{generate-desktop-shell-DzEzNspp.mjs → generate-desktop-shell-DR5vuZu9.mjs} +11 -6
  26. package/dist/generate-desktop-shell-DR5vuZu9.mjs.map +1 -0
  27. package/dist/{get-version-DnU4hhms.mjs → get-version-CdS7U_Q8.mjs} +4 -4
  28. package/dist/{get-version-DnU4hhms.mjs.map → get-version-CdS7U_Q8.mjs.map} +1 -1
  29. package/dist/{index-V0t4klsV.d.mts → index-BCSl7lP0.d.mts} +9 -19
  30. package/dist/{index-V0t4klsV.d.mts.map → index-BCSl7lP0.d.mts.map} +1 -1
  31. package/dist/{mcp-LUXNRVj3.mjs → mcp-DnKGQZ10.mjs} +4 -4
  32. package/dist/{mcp-LUXNRVj3.mjs.map → mcp-DnKGQZ10.mjs.map} +1 -1
  33. package/dist/{migrate-CIJaE3iZ.mjs → migrate-B9F_cSCA.mjs} +4 -4
  34. package/dist/{migrate-CIJaE3iZ.mjs.map → migrate-B9F_cSCA.mjs.map} +1 -1
  35. package/dist/{ph-cli-commands-B0V_uMll.mjs → ph-cli-commands-DQ7kfVak.mjs} +19 -19
  36. package/dist/{ph-cli-commands-B0V_uMll.mjs.map → ph-cli-commands-DQ7kfVak.mjs.map} +1 -1
  37. package/dist/ph-cli-commands-oih3l80w.mjs +4 -0
  38. package/dist/{run-sugar-fbWJGtkS.mjs → run-sugar-5TYsoc3n.mjs} +4 -4
  39. package/dist/{run-sugar-fbWJGtkS.mjs.map → run-sugar-5TYsoc3n.mjs.map} +1 -1
  40. package/dist/runners/connect.d.mts +6 -1206
  41. package/dist/runners/connect.d.mts.map +1 -1
  42. package/dist/runners/connect.mjs +21 -255
  43. package/dist/runners/connect.mjs.map +1 -1
  44. package/dist/runners/switchboard.d.mts +4 -1752
  45. package/dist/runners/switchboard.d.mts.map +1 -1
  46. package/dist/runners/switchboard.mjs +10 -722
  47. package/dist/runners/switchboard.mjs.map +1 -1
  48. package/dist/utils-TO9lB8Xs.mjs +4 -0
  49. package/dist/{vetra-BRyjbepO.mjs → vetra-CwhVV4_U.mjs} +13 -29
  50. package/dist/vetra-CwhVV4_U.mjs.map +1 -0
  51. package/package.json +16 -15
  52. package/dist/check-BhShHuOZ.mjs.map +0 -1
  53. package/dist/compound-BZb3tR_c-CAf7DitW.mjs.map +0 -1
  54. package/dist/connect-build-DMKUu9mw.mjs.map +0 -1
  55. package/dist/connect-plugin-configs-DazgTR0p.mjs +0 -50
  56. package/dist/connect-plugin-configs-DazgTR0p.mjs.map +0 -1
  57. package/dist/connect-preview-Ckoqw_XU.mjs +0 -231
  58. package/dist/connect-preview-Ckoqw_XU.mjs.map +0 -1
  59. package/dist/dist-tZHpCFn_.mjs.map +0 -1
  60. package/dist/generate-desktop-shell-DzEzNspp.mjs.map +0 -1
  61. package/dist/member-config-DJUsoeHe.mjs +0 -155
  62. package/dist/member-config-DJUsoeHe.mjs.map +0 -1
  63. package/dist/ph-cli-commands-KQDLKJ7k.mjs +0 -4
  64. package/dist/precompress-P6cJDPVC.mjs +0 -77
  65. package/dist/precompress-P6cJDPVC.mjs.map +0 -1
  66. package/dist/start-run-x-6Ccna-.mjs +0 -124
  67. package/dist/start-run-x-6Ccna-.mjs.map +0 -1
  68. package/dist/superseded-config-CbSTFun2.mjs +0 -53
  69. package/dist/superseded-config-CbSTFun2.mjs.map +0 -1
  70. package/dist/switchboard-B6h7BNWB.mjs +0 -4
  71. package/dist/switchboard-JcKcWTaT.mjs +0 -170
  72. package/dist/switchboard-JcKcWTaT.mjs.map +0 -1
  73. package/dist/utils-DAux4Ga7.mjs +0 -4
  74. package/dist/vetra-BRyjbepO.mjs.map +0 -1
@@ -1,12 +1,12 @@
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]="136f8ad6-542a-557e-853e-cdc6d0991bbc")}catch(e){}}();
3
- import { n as checkHost } from "./dist-tZHpCFn_.mjs";
4
- import { s as rememberShellNames } from "./member-config-DJUsoeHe.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]="aa36e73f-e2cd-54c0-b83d-7dc2b160c9a1")}catch(e){}}();
3
+ import { t as checkHost } from "./dist-Dw0p_A5j.mjs";
5
4
  import path from "node:path";
6
- import { envNamesBeforeProjectEnv, loadProjectEnv } from "@powerhousedao/shared/clis/project-env";
7
- import dotenv from "dotenv";
8
5
  import { readFile } from "node:fs/promises";
9
6
  import { CALLER_CWD_ENV } from "@powerhousedao/shared/clis/command-names";
7
+ import { envNamesBeforeProjectEnv, loadProjectEnv } from "@powerhousedao/shared/clis/project-env";
8
+ import dotenv from "dotenv";
9
+ import { rememberShellNames } from "@powerhousedao/ph-run/member-config";
10
10
  //#region src/services/host/check.ts
11
11
  /** Without `envFile`: what `ph run` sees (project .env under process env). */
12
12
  async function checkEnv(projectRoot, envFile) {
@@ -61,5 +61,5 @@ async function runHostCheck(args) {
61
61
  //#endregion
62
62
  export { runHostCheck };
63
63
 
64
- //# sourceMappingURL=check-BhShHuOZ.mjs.map
65
- //# debugId=136f8ad6-542a-557e-853e-cdc6d0991bbc
64
+ //# sourceMappingURL=check-BdeBTBzN.mjs.map
65
+ //# debugId=aa36e73f-e2cd-54c0-b83d-7dc2b160c9a1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check-BdeBTBzN.mjs","sources":["../src/services/host/check.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { checkHost, type HostIssue } from \"@powerhousedao/host-core\";\nimport { CALLER_CWD_ENV } from \"@powerhousedao/shared/clis/command-names\";\nimport {\n envNamesBeforeProjectEnv,\n loadProjectEnv,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport dotenv from \"dotenv\";\nimport { rememberShellNames } from \"@powerhousedao/ph-run/member-config\";\n\nexport interface HostCheckArgs {\n host: string;\n envFile?: string;\n verb?: string;\n projectRoot?: string;\n}\n\n/** Without `envFile`: what `ph run` sees (project .env under process env). */\nasync function checkEnv(\n projectRoot: string,\n envFile: string | undefined,\n): Promise<Record<string, string | undefined>> {\n if (envFile === undefined) {\n loadProjectEnv(projectRoot);\n // A snapshot: a .env a runner's checkBoot loads later never reaches it.\n const env = { ...process.env };\n // The switchboard's checkBoot puts the .env's values under the host file.\n rememberShellNames(env, envNamesBeforeProjectEnv() ?? Object.keys(env));\n return env;\n }\n const from = process.env[CALLER_CWD_ENV] ?? process.cwd();\n try {\n return dotenv.parse(await readFile(path.resolve(from, envFile), \"utf8\"));\n } catch (error) {\n throw new Error(\n `Cannot read the env file ${envFile}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nfunction issueBlocks(\n found: readonly { label: string; issue: HostIssue }[],\n): string {\n const byFile = new Map<string, typeof found>();\n for (const entry of found) {\n byFile.set(entry.issue.file, [\n ...(byFile.get(entry.issue.file) ?? []),\n entry,\n ]);\n }\n const blocks = [...byFile].map(([at, entries]) => {\n const lines = entries.flatMap(({ label, issue }) => {\n const where = issue.path ? `${issue.path}: ` : \"\";\n const line = ` ${label} ${where}${issue.message.replaceAll(\"\\n\", \"\\n \")}`;\n return issue.hint ? [line, ` hint: ${issue.hint}`] : [line];\n });\n return [at, ...lines].join(\"\\n\");\n });\n return blocks.join(\"\\n\\n\");\n}\n\nexport function formatHostIssues(\n file: string,\n issues: readonly HostIssue[],\n deferred: number,\n warnings: readonly HostIssue[] = [],\n): string {\n const warned = warnings.map((issue) => ({ label: \"warning\", issue }));\n if (issues.length === 0) {\n const note =\n deferred > 0\n ? `\\n ${deferred} output token(s) checked declared-only`\n : \"\";\n const tail = warned.length > 0 ? `\\n\\n${issueBlocks(warned)}` : \"\";\n return `${file}: ok${note}${tail}`;\n }\n return issueBlocks([\n ...issues.map((issue) => ({ label: issue.stage, issue })),\n ...warned,\n ]);\n}\n\n/** `ph host check <host>`: exits 1 on any issue; warnings only print. */\nexport async function runHostCheck(\n args: HostCheckArgs,\n): Promise<{ output: string; exitCode: number }> {\n const projectRoot = args.projectRoot ?? process.cwd();\n const env = await checkEnv(projectRoot, args.envFile);\n const { issues, warnings, deferred } = await checkHost(args.host, {\n projectRoot,\n env,\n ...(args.verb !== undefined ? { verb: args.verb } : {}),\n });\n return {\n output: formatHostIssues(\n `hosts/${args.host}/host.js`,\n issues,\n deferred.length,\n warnings,\n ),\n exitCode: issues.length > 0 ? 1 : 0,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAmBA,eAAe,SACb,aACA,SAC6C;CAC7C,IAAI,YAAY,KAAA,GAAW;EACzB,eAAe,WAAW;EAE1B,MAAM,MAAM,EAAE,GAAG,QAAQ,IAAI;EAE7B,mBAAmB,KAAK,yBAAyB,KAAK,OAAO,KAAK,GAAG,CAAC;EACtE,OAAO;CACT;CACA,MAAM,OAAO,QAAQ,IAAI,mBAAmB,QAAQ,IAAI;CACxD,IAAI;EACF,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,QAAQ,MAAM,OAAO,GAAG,MAAM,CAAC;CACzE,SAAS,OAAO;EACd,MAAM,IAAI,MACR,4BAA4B,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC7F,EAAE,OAAO,MAAM,CACjB;CACF;AACF;AAEA,SAAS,YACP,OACQ;CACR,MAAM,yBAAS,IAAI,IAA0B;CAC7C,KAAK,MAAM,SAAS,OAClB,O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AAI,IAAI;CACpC;AACF","debug_id":"aa36e73f-e2cd-54c0-b83d-7dc2b160c9a1"}
@@ -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]="096016d0-3390-502c-ab77-df675068e641")}catch(e){}}();
3
- import { o as mergeDefaultDrives } from "./dist-tZHpCFn_.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]="ffd92da5-9109-5997-8f9a-5ac9e5a3857a")}catch(e){}}();
3
+ import { i as mergeDefaultDrives } from "./dist-Dw0p_A5j.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-Dm55uCjR.mjs.map
293
- //# debugId=096016d0-3390-502c-ab77-df675068e641
292
+ //# sourceMappingURL=cli-connect-override-CY_Zf7wG.mjs.map
293
+ //# debugId=ffd92da5-9109-5997-8f9a-5ac9e5a3857a
@@ -1 +1 @@
1
- {"version":3,"file":"cli-connect-override-Dm55uCjR.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 const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option). The home\n // screen is the generic plugin's, so this lands in connect.home.\n if (args.homeBackground !== undefined) {\n out.home = {\n background: args.homeBackground === \"\" ? null : args.homeBackground,\n };\n }\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,KAAqB;CAChD,OAAO,IAAI,WAAW,UAAU,IAAI,IAAI,MAAM,CAAiB,IAAI;AACrE;AAEA,SAAS,aAAa,QAA+C;CACnE,IAAI,CAAC,UAAU,OAAO,WAAW,GAAG,OAAO;CAC3C,OAAO,OACJ,KAAK,MAAM;EACV,MAAM,OAAO,EAAE,gBAAgB;EAC/B,MAAM,QAAQ,EAAE,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AAQ,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":"096016d0-3390-502c-ab77-df675068e641"}
1
+ {"version":3,"file":"cli-connect-override-CY_Zf7wG.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 const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option). The home\n // screen is the generic plugin's, so this lands in connect.home.\n if (args.homeBackground !== undefined) {\n out.home = {\n background: args.homeBackground === \"\" ? null : args.homeBackground,\n };\n }\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;;;;;;;;;;;;AA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D,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":"ffd92da5-9109-5997-8f9a-5ac9e5a3857a"}
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]="83ce31d0-0645-5039-b36b-b7427b013283")}catch(e){}}();
4
- import { t as getVersion } from "./get-version-DnU4hhms.mjs";
5
- import { n as phCliCommands } from "./ph-cli-commands-B0V_uMll.mjs";
4
+ import { t as getVersion } from "./get-version-CdS7U_Q8.mjs";
5
+ import { n as phCliCommands } from "./ph-cli-commands-DQ7kfVak.mjs";
6
6
  import { t as isUniformRunnersEnabled } from "./feature-flags-xwqcHEWC.mjs";
7
7
  import { initCliTelemetry } from "@powerhousedao/shared/clis/telemetry";
8
8
  import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
@@ -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-fbWJGtkS.mjs");
96
- const { phCliCommands } = await import("./ph-cli-commands-KQDLKJ7k.mjs");
95
+ const { applyRunSugar } = await import("./run-sugar-5TYsoc3n.mjs");
96
+ const { phCliCommands } = await import("./ph-cli-commands-oih3l80w.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,15 +1,15 @@
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]="243df33b-9829-5639-9637-d1f4bd4cc8b3")}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]="322fc979-162b-5463-9034-a74b20f8e448")}catch(e){}}();
3
3
  import { c as number, d as string, f as union, g as prettifyError, h as toJSONSchema, i as boolean, l as record, m as url, n as _enum, o as literal, p as unknown, r as array, s as looseObject, t as ZodType, u as strictObject } from "./schemas-ByfuhvAb.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
6
  import path from "node:path";
7
- import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
8
7
  import { createHash } from "node:crypto";
9
8
  import { pathToFileURL } from "node:url";
10
9
  import { TOKEN_ESCAPE_KEY, envTokenable, findToken, isToken, switchboardOfDrive, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
10
+ import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
11
11
  import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
12
- //#region ../../packages/host-core/dist/compound-BZb3tR_c.mjs
12
+ //#region ../../packages/host-core/dist/compound-BSOW40st.mjs
13
13
  /**
14
14
  * R1 — the host plugin framework (bridge-runners-to-plugins plan,
15
15
  * customization-references/host-core as the blueprint).
@@ -72,27 +72,6 @@ function entryActiveForVerb(entry, verb) {
72
72
  return entry.verbs === "*" || entry.verbs.includes(verb);
73
73
  }
74
74
  /**
75
- * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
76
- * "compound" is its own branch (plugins over the member set — e.g. the clint
77
- * proxy). Host runtimes register their id with a parent; compatibility walks
78
- * the parent chain.
79
- */
80
- const HOST_TYPE_PARENTS = {
81
- reactor: null,
82
- compound: null,
83
- connect: "reactor",
84
- switchboard: "reactor",
85
- mastra: "reactor"
86
- };
87
- function hostTypeSatisfies(hostType, appliesTo) {
88
- let current = hostType;
89
- while (current !== null) {
90
- if (current === appliesTo) return true;
91
- current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
92
- }
93
- return false;
94
- }
95
- /**
96
75
  * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
97
76
  * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
98
77
  * PROJECT dependency tree, exactly like runner modules.
@@ -101,44 +80,6 @@ function isHostPluginShape(value) {
101
80
  return value !== null && typeof value === "object" && typeof value.name === "string";
102
81
  }
103
82
  /**
104
- * Resolve host.js plugin entries into live plugins for one host boot:
105
- * verb-filter → module resolution from the project tree (default condition,
106
- * like runners) → factory/object contract → config validation → appliesTo.
107
- */
108
- async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
109
- const normalized = normalizePluginEntries(entries, where);
110
- const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
111
- const resolved = [];
112
- for (const entry of normalized) {
113
- if (!entryActiveForVerb(entry, verb)) continue;
114
- let file;
115
- try {
116
- file = projectRequire.resolve(entry.module);
117
- } catch {
118
- throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
119
- }
120
- const exported = (await import(pathToFileURL(file).href)).default;
121
- let plugin;
122
- if (typeof exported === "function") plugin = exported(entry.config);
123
- else if (isHostPluginShape(exported)) {
124
- if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
125
- plugin = exported;
126
- } else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
127
- if (plugin.configSchema) {
128
- const parsed = plugin.configSchema.safeParse(entry.config);
129
- if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + prettifyError(parsed.error));
130
- }
131
- const appliesTo = plugin.appliesTo ?? "reactor";
132
- if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
133
- resolved.push({
134
- entry,
135
- plugin,
136
- provenance: "dependency"
137
- });
138
- }
139
- return resolved;
140
- }
141
- /**
142
83
  * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
143
84
  * collects the drive contributions of the entries active for `verb`. Unlike
144
85
  * resolveHostPlugins it does not know the host type (so appliesTo is not
@@ -336,6 +277,8 @@ function buildDriveDeclarationSchema(urlField) {
336
277
  * only the id and keeps the declared slug (the classic Workflows drive:
337
278
  * `/d/workflows`, id `workflows-<hash>`). */
338
279
  projectHash: union([boolean(), literal("id")]).optional(),
280
+ /** What a missing drive is created as. Default powerhouse/document-drive. */
281
+ documentType: _enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
339
282
  name: string().min(1).optional(),
340
283
  icon: string().optional(),
341
284
  preferredEditor: string().optional(),
@@ -833,38 +776,6 @@ function buildHostSchemas(tokenField) {
833
776
  function makeHostSchemas(options) {
834
777
  return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
835
778
  }
836
- const CONNECT_PRIMARY_MESSAGE = "Connect doesn't use placement.primary. To choose where new drives go, use placement.newDrives.";
837
- /**
838
- * A Connect host's placement rules, in either form. The router's primary is
839
- * the browser reactor, else the `newDrives` switchboard, else the only one,
840
- * so `placement.primary` means nothing here, and a Connect with several
841
- * switchboards and no browser reactor must say where new drives go. Apply it
842
- * last to the Connect runner's schema: `.superRefine(refineConnectReactor)`.
843
- */
844
- function refineConnectReactor(host, ctx) {
845
- const reactor = host.reactor;
846
- if (!reactor) return;
847
- if (reactor.placement?.primary !== void 0) ctx.addIssue({
848
- code: "custom",
849
- path: [
850
- "reactor",
851
- "placement",
852
- "primary"
853
- ],
854
- message: CONNECT_PRIMARY_MESSAGE
855
- });
856
- const backends = Object.entries(reactor.backends ?? {});
857
- const remotes = backends.filter(([, backend]) => backend.kind === "remote").map(([name]) => name);
858
- if (remotes.length > 1 && remotes.length === backends.length && reactor.placement?.newDrives === void 0) ctx.addIssue({
859
- code: "custom",
860
- path: [
861
- "reactor",
862
- "placement",
863
- "newDrives"
864
- ],
865
- message: `This Connect keeps no reactor in the browser and links ${remotes.length} switchboards (${remotes.join(", ")}). Set placement.newDrives to the one new drives are created on.`
866
- });
867
- }
868
779
  /** Adds the host-level placement key check to a runner's declared schema. */
869
780
  function withPlacementKeys(schema) {
870
781
  if (!(schema instanceof ZodType)) return schema;
@@ -2040,11 +1951,6 @@ var RunnerError = class extends Error {
2040
1951
  this.name = "RunnerError";
2041
1952
  }
2042
1953
  };
2043
- /** Whether a value is zod-shaped (has a `safeParse` function): a runner's
2044
- * `outputsSchema`, a plugin's config schema. */
2045
- function isSchemaLike(value) {
2046
- return typeof value === "object" && value !== null && "safeParse" in value && typeof value.safeParse === "function";
2047
- }
2048
1954
  /** The Connect runner's specifier: compounds forward `cspRegistrySync` to
2049
1955
  * it, and `--explain` prints its dead-config warnings. */
2050
1956
  const CONNECT_RUNNER = "@powerhousedao/ph-cli/runners/connect";
@@ -2058,11 +1964,27 @@ const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
2058
1964
  "checkBoot",
2059
1965
  "default"
2060
1966
  ]);
1967
+ /** ph-cli's runners are ph-run's plus the verbs that build. A packaged app has
1968
+ * only ph-run, and its host files, generated against ph-cli's, name ph-cli's. */
1969
+ function runnerFallback(specifier) {
1970
+ const name = /^@powerhousedao\/ph-cli\/(runners\/.+)$/.exec(specifier)?.[1];
1971
+ return name ? `@powerhousedao/ph-run/${name}` : void 0;
1972
+ }
2061
1973
  async function resolveRunnerModule(projectRoot, specifier) {
2062
1974
  const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
1975
+ const resolveFirst = (candidates) => {
1976
+ const [first, ...rest] = candidates;
1977
+ try {
1978
+ return projectRequire.resolve(first);
1979
+ } catch (error) {
1980
+ if (rest.length === 0) throw error;
1981
+ return resolveFirst(rest);
1982
+ }
1983
+ };
2063
1984
  let resolved;
2064
1985
  try {
2065
- resolved = projectRequire.resolve(specifier);
1986
+ const fallback = runnerFallback(specifier);
1987
+ resolved = resolveFirst(fallback ? [specifier, fallback] : [specifier]);
2066
1988
  } catch {
2067
1989
  throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
2068
1990
  }
@@ -2645,17 +2567,6 @@ function readProjectName(projectDir) {
2645
2567
  } catch {}
2646
2568
  return path.basename(path.resolve(projectDir));
2647
2569
  }
2648
- function writeRunRecord(projectDir, record) {
2649
- const target = recordPath(projectDir, record.host);
2650
- const valid = runRecordSchema.parse(record);
2651
- fs.mkdirSync(path.dirname(target), { recursive: true });
2652
- fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\n`);
2653
- }
2654
- function clearRunRecord(projectDir, hostName, env = process.env) {
2655
- try {
2656
- fs.rmSync(recordPath(projectDir, hostName, env));
2657
- } catch {}
2658
- }
2659
2570
  function isPidAlive(pid) {
2660
2571
  try {
2661
2572
  process.kill(pid, 0);
@@ -2835,33 +2746,7 @@ function compoundOutputSource(members, started, compound, schemas) {
2835
2746
  };
2836
2747
  } };
2837
2748
  }
2838
- /** The data half of a handle, validated by the compound. `ready`/`shutdown`
2839
- * are functions and promises, so they are checked as TS fields, not here. */
2840
- const runnerHandleSchema = looseObject({ outputs: record(string(), unknown()).optional() });
2841
- function isRecord(value) {
2842
- return typeof value === "object" && value !== null;
2843
- }
2844
- function isPromiseLike(value) {
2845
- return isRecord(value) && typeof value.then === "function";
2846
- }
2847
- function isCallable(value) {
2848
- return typeof value === "function";
2849
- }
2850
- /** Normalize what a verb returned. `undefined` (a self-sustaining bridge)
2851
- * is an empty handle; anything else must match runnerHandleSchema. */
2852
- function toStartedHandle(value, where) {
2853
- if (value === void 0 || value === null) return { outputs: {} };
2854
- const parsed = runnerHandleSchema.safeParse(value);
2855
- if (!parsed.success) throw new Error(`${where} returned an invalid runner handle:\n${prettifyError(parsed.error)}`);
2856
- const live = isRecord(value) ? value : {};
2857
- const shutdown = live.shutdown;
2858
- return {
2859
- ...parsed.data,
2860
- outputs: parsed.data.outputs ?? {},
2861
- ...isPromiseLike(live.ready) ? { ready: live.ready } : {},
2862
- ...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}
2863
- };
2864
- }
2749
+ looseObject({ outputs: record(string(), unknown()).optional() });
2865
2750
  async function memberDraft(projectRoot, member) {
2866
2751
  return applyChildWrapper((await loadHost(projectRoot, member.host)).host, member);
2867
2752
  }
@@ -2897,7 +2782,7 @@ async function prepareMember(projectRoot, key, member) {
2897
2782
  };
2898
2783
  }
2899
2784
  //#endregion
2900
- export { substituteBuiltinEnv as $, loadProducers as A, processResolveEnv as B, hostSchemaIssues as C, isToken as D, isSchemaLike as E, outputSitesOf as F, refineConnectReactor as G, projectDriveIdWith as H, planCompound as I, resolveHostPlugins as J, renderTokens as K, prepareMember as L, memberVerbOf as M, normalizePluginEntries as N, kindShapeIssues as O, outputRefsOf as P, runnerOutputsSchema as Q, probeHostsFolder as R, getVerb as S, isPlainObject as T, readProjectName as U, producerOutputsSchemas as V, readRunRecord as W, resolveRunnerModule as X, resolvePluginContributions as Y, runRecordOutputSource as Z, entryActiveForVerb as _, TokenResolutionError as a, writeRunRecord as at, findRemovedForms as b, checkTokenSites as c, compoundOutputSource as d, takesCspRegistrySync as et, compoundStartVerb as f, drivesSchema as g, describeToken as h, PluginError as i, validateHost as it, memberForRef as j, loadHost as k, clearRunRecord as l, defineHostSchemas as m, HostLoadError as n, unsetEnvMessage as nt, applyChildWrapper as o, declaredHostSchemas as p, resolveHostOutputs as q, ONE_SHOT_VERBS as r, validateDeclaredHost as rt, checkOutputPaths as s, CONNECT_RUNNER as t, toStartedHandle as tt, collectTokenSites as u, envSitesOf as v, isBuiltinEnvName as w, formatPath as x, findDeadConnectConfig as y, probeRun as z };
2785
+ export { planCompound as A, resolvePluginContributions as B, kindShapeIssues as C, memberVerbOf as D, memberForRef as E, producerOutputsSchemas as F, takesCspRegistrySync as G, runRecordOutputSource as H, projectDriveIdWith as I, validateHost as J, unsetEnvMessage as K, readProjectName as L, probeHostsFolder as M, probeRun as N, outputRefsOf as O, processResolveEnv as P, renderTokens as R, isToken as S, loadProducers as T, runnerOutputsSchema as U, resolveRunnerModule as V, substituteBuiltinEnv as W, formatPath as _, applyChildWrapper as a, isBuiltinEnvName as b, collectTokenSites as c, declaredHostSchemas as d, describeToken as f, findRemovedForms as g, findDeadConnectConfig as h, TokenResolutionError as i, prepareMember as j, outputSitesOf as k, compoundOutputSource as l, envSitesOf as m, HostLoadError as n, checkOutputPaths as o, drivesSchema as p, validateDeclaredHost as q, ONE_SHOT_VERBS as r, checkTokenSites as s, CONNECT_RUNNER as t, compoundStartVerb as u, getVerb as v, loadHost as w, isPlainObject as x, hostSchemaIssues as y, resolveHostOutputs as z };
2901
2786
 
2902
- //# sourceMappingURL=compound-BZb3tR_c-CAf7DitW.mjs.map
2903
- //# debugId=243df33b-9829-5639-9637-d1f4bd4cc8b3
2787
+ //# sourceMappingURL=compound-BSOW40st-CWIT2x84.mjs.map
2788
+ //# debugId=322fc979-162b-5463-9034-a74b20f8e448