@powerhousedao/ph-cli 6.2.2-dev.4 → 6.2.2-dev.41

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 (29) hide show
  1. package/dist/build-C-A5-ipO.mjs +4 -0
  2. package/dist/{build-B5LEeRPm.mjs → build-uQXq6_HU.mjs} +26 -4
  3. package/dist/build-uQXq6_HU.mjs.map +1 -0
  4. package/dist/{cli-connect-override-CFsTgKB6.mjs → cli-connect-override-D3hh4aH_.mjs} +5 -3
  5. package/dist/cli-connect-override-D3hh4aH_.mjs.map +1 -0
  6. package/dist/cli.mjs +29 -19
  7. package/dist/cli.mjs.map +1 -1
  8. package/dist/{connect-build-BtaMnrYu.mjs → connect-build-WL4axo4z.mjs} +6 -6
  9. package/dist/{connect-build-BtaMnrYu.mjs.map → connect-build-WL4axo4z.mjs.map} +1 -1
  10. package/dist/{connect-config-O3qXExg9.mjs → connect-config-BWGiW3IB.mjs} +7 -5
  11. package/dist/connect-config-BWGiW3IB.mjs.map +1 -0
  12. package/dist/connect-studio-BIQzyq5B.mjs +5 -0
  13. package/dist/{connect-studio-sRLuTabi.mjs → connect-studio-D6rfWCNB.mjs} +4 -4
  14. package/dist/{connect-studio-sRLuTabi.mjs.map → connect-studio-D6rfWCNB.mjs.map} +1 -1
  15. package/dist/{inspect-CKdafPbC.mjs → inspect-DXjbQEV_.mjs} +4 -4
  16. package/dist/{inspect-CKdafPbC.mjs.map → inspect-DXjbQEV_.mjs.map} +1 -1
  17. package/dist/{migrate-BJQvY88v.mjs → migrate-jGKfE02L.mjs} +4 -4
  18. package/dist/{migrate-BJQvY88v.mjs.map → migrate-jGKfE02L.mjs.map} +1 -1
  19. package/dist/{utils-DPGwKNam.mjs → utils-BzwczAW-.mjs} +3 -3
  20. package/dist/{utils-BaTZlyL3.mjs → utils-C4isxXSO.mjs} +4 -4
  21. package/dist/{utils-BaTZlyL3.mjs.map → utils-C4isxXSO.mjs.map} +1 -1
  22. package/dist/{vetra-D9MTB556.mjs → vetra-J6x1YaOp.mjs} +6 -6
  23. package/dist/{vetra-D9MTB556.mjs.map → vetra-J6x1YaOp.mjs.map} +1 -1
  24. package/package.json +11 -11
  25. package/dist/build-B5LEeRPm.mjs.map +0 -1
  26. package/dist/build-CMgv-erS.mjs +0 -4
  27. package/dist/cli-connect-override-CFsTgKB6.mjs.map +0 -1
  28. package/dist/connect-config-O3qXExg9.mjs.map +0 -1
  29. package/dist/connect-studio-DQ6dRWlL.mjs +0 -5
@@ -1 +1 @@
1
- {"version":3,"file":"inspect-CKdafPbC.mjs","sources":["../src/services/inspect.ts"],"sourcesContent":["import type { Manifest } from \"@powerhousedao/shared/document-model\";\nimport fs from \"node:fs\";\nimport type { InspectArgs } from \"../types.js\";\nimport { getProjectInfo } from \"../utils.js\";\nexport function startInspect(args: InspectArgs) {\n if (args.debug) {\n console.log(\">>> command arguments\", args);\n }\n\n const projectInfo = getProjectInfo(args.debug);\n const { packageName } = args;\n\n if (args.debug) {\n console.log(\"\\n>>> projectInfo\", projectInfo);\n }\n\n try {\n const loadManifest = (path: string) =>\n JSON.parse(fs.readFileSync(path, \"utf-8\")) as Manifest;\n const manifest = loadManifest(\n `${process.cwd()}/node_modules/${packageName}/dist/powerhouse.manifest.json`,\n );\n\n console.log(manifest.name);\n if (manifest.documentModels) {\n console.log(\"\\nDocument Models:\");\n manifest.documentModels.forEach((model) => {\n console.log(`- ${model.name} (${model.id})`);\n });\n }\n\n if (manifest.editors) {\n console.log(\"\\nEditors:\");\n manifest.editors.forEach((editor) => {\n console.log(`- ${editor.name} (${editor.id})`);\n });\n }\n\n if (manifest.processors) {\n console.log(\"\\nProcessors:\");\n manifest.processors.forEach((processor) => {\n console.log(`- ${processor.name} (${processor.id})`);\n });\n }\n\n if (manifest.subgraphs) {\n console.log(\"\\nSubgraphs:\");\n manifest.subgraphs.forEach((subgraph) => {\n console.log(`- ${subgraph.name} (${subgraph.id})`);\n });\n }\n } catch (e) {\n if (args.debug) {\n console.error(e);\n } else {\n console.log(\"No manifest found in the package\");\n }\n }\n}\n"],"names":[],"mappings":";;;;;AAIA,SAAgB,aAAa,MAAmB;AAC9C,KAAI,KAAK,MACP,SAAQ,IAAI,yBAAyB,KAAK;CAG5C,MAAM,cAAc,eAAe,KAAK,MAAM;CAC9C,MAAM,EAAE,gBAAgB;AAExB,KAAI,KAAK,MACP,SAAQ,IAAI,qBAAqB,YAAY;AAG/C,KAAI;EACF,MAAM,gBAAgB,SACpB,KAAK,MAAM,GAAG,aAAa,MAAM,QAAQ,CAAC;EAC5C,MAAM,WAAW,aACf,GAAG,QAAQ,KAAK,CAAC,gBAAgB,YAAY,gCAC9C;AAED,UAAQ,IAAI,SAAS,KAAK;AAC1B,MAAI,SAAS,gBAAgB;AAC3B,WAAQ,IAAI,qBAAqB;AACjC,YAAS,eAAe,SAAS,UAAU;AACzC,YAAQ,IAAI,KAAK,MAAM,KAAK,IAAI,MAAM,GAAG,GAAG;KAC5C;;AAGJ,MAAI,SAAS,SAAS;AACpB,WAAQ,IAAI,aAAa;AACzB,YAAS,QAAQ,SAAS,WAAW;AACnC,YAAQ,IAAI,KAAK,OAAO,KAAK,IAAI,OAAO,GAAG,GAAG;KAC9C;;AAGJ,MAAI,SAAS,YAAY;AACvB,WAAQ,IAAI,gBAAgB;AAC5B,YAAS,WAAW,SAAS,cAAc;AACzC,YAAQ,IAAI,KAAK,UAAU,KAAK,IAAI,UAAU,GAAG,GAAG;KACpD;;AAGJ,MAAI,SAAS,WAAW;AACtB,WAAQ,IAAI,eAAe;AAC3B,YAAS,UAAU,SAAS,aAAa;AACvC,YAAQ,IAAI,KAAK,SAAS,KAAK,IAAI,SAAS,GAAG,GAAG;KAClD;;UAEG,GAAG;AACV,MAAI,KAAK,MACP,SAAQ,MAAM,EAAE;MAEhB,SAAQ,IAAI,mCAAmC","debug_id":"b2a9ca8c-b055-504d-90d5-d0bbacda0201"}
1
+ {"version":3,"file":"inspect-DXjbQEV_.mjs","sources":["../src/services/inspect.ts"],"sourcesContent":["import type { Manifest } from \"@powerhousedao/shared/document-model\";\nimport fs from \"node:fs\";\nimport type { InspectArgs } from \"../types.js\";\nimport { getProjectInfo } from \"../utils.js\";\nexport function startInspect(args: InspectArgs) {\n if (args.debug) {\n console.log(\">>> command arguments\", args);\n }\n\n const projectInfo = getProjectInfo(args.debug);\n const { packageName } = args;\n\n if (args.debug) {\n console.log(\"\\n>>> projectInfo\", projectInfo);\n }\n\n try {\n const loadManifest = (path: string) =>\n JSON.parse(fs.readFileSync(path, \"utf-8\")) as Manifest;\n const manifest = loadManifest(\n `${process.cwd()}/node_modules/${packageName}/dist/powerhouse.manifest.json`,\n );\n\n console.log(manifest.name);\n if (manifest.documentModels) {\n console.log(\"\\nDocument Models:\");\n manifest.documentModels.forEach((model) => {\n console.log(`- ${model.name} (${model.id})`);\n });\n }\n\n if (manifest.editors) {\n console.log(\"\\nEditors:\");\n manifest.editors.forEach((editor) => {\n console.log(`- ${editor.name} (${editor.id})`);\n });\n }\n\n if (manifest.processors) {\n console.log(\"\\nProcessors:\");\n manifest.processors.forEach((processor) => {\n console.log(`- ${processor.name} (${processor.id})`);\n });\n }\n\n if (manifest.subgraphs) {\n console.log(\"\\nSubgraphs:\");\n manifest.subgraphs.forEach((subgraph) => {\n console.log(`- ${subgraph.name} (${subgraph.id})`);\n });\n }\n } catch (e) {\n if (args.debug) {\n console.error(e);\n } else {\n console.log(\"No manifest found in the package\");\n }\n }\n}\n"],"names":[],"mappings":";;;;;AAIA,SAAgB,aAAa,MAAmB;AAC9C,KAAI,KAAK,MACP,SAAQ,IAAI,yBAAyB,KAAK;CAG5C,MAAM,cAAc,eAAe,KAAK,MAAM;CAC9C,MAAM,EAAE,gBAAgB;AAExB,KAAI,KAAK,MACP,SAAQ,IAAI,qBAAqB,YAAY;AAG/C,KAAI;EACF,MAAM,gBAAgB,SACpB,KAAK,MAAM,GAAG,aAAa,MAAM,QAAQ,CAAC;EAC5C,MAAM,WAAW,aACf,GAAG,QAAQ,KAAK,CAAC,gBAAgB,YAAY,gCAC9C;AAED,UAAQ,IAAI,SAAS,KAAK;AAC1B,MAAI,SAAS,gBAAgB;AAC3B,WAAQ,IAAI,qBAAqB;AACjC,YAAS,eAAe,SAAS,UAAU;AACzC,YAAQ,IAAI,KAAK,MAAM,KAAK,IAAI,MAAM,GAAG,GAAG;KAC5C;;AAGJ,MAAI,SAAS,SAAS;AACpB,WAAQ,IAAI,aAAa;AACzB,YAAS,QAAQ,SAAS,WAAW;AACnC,YAAQ,IAAI,KAAK,OAAO,KAAK,IAAI,OAAO,GAAG,GAAG;KAC9C;;AAGJ,MAAI,SAAS,YAAY;AACvB,WAAQ,IAAI,gBAAgB;AAC5B,YAAS,WAAW,SAAS,cAAc;AACzC,YAAQ,IAAI,KAAK,UAAU,KAAK,IAAI,UAAU,GAAG,GAAG;KACpD;;AAGJ,MAAI,SAAS,WAAW;AACtB,WAAQ,IAAI,eAAe;AAC3B,YAAS,UAAU,SAAS,aAAa;AACvC,YAAQ,IAAI,KAAK,SAAS,KAAK,IAAI,SAAS,GAAG,GAAG;KAClD;;UAEG,GAAG;AACV,MAAI,KAAK,MACP,SAAQ,MAAM,EAAE;MAEhB,SAAQ,IAAI,mCAAmC","debug_id":"e71cc752-7835-5af2-bae0-1a7629056456"}
@@ -1,10 +1,10 @@
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]="5cc924ff-7015-5b6b-ac8d-a2c87fcac122")}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]="5917a8da-bcbd-52a8-af0d-9c6d60ae5475")}catch(e){}}();
3
3
  import { execSync } from "node:child_process";
4
+ import { readFileSync } from "node:fs";
4
5
  import { dirname, join } from "node:path";
5
6
  import { detect, resolveCommand } from "package-manager-detector";
6
7
  import { fetchPackageVersionFromNpmRegistry, injectPnpmAllowBuilds } from "@powerhousedao/shared/clis";
7
- import { readFileSync } from "node:fs";
8
8
  import { fileURLToPath } from "node:url";
9
9
  //#region src/services/migrate.ts
10
10
  function getBundledPhCliVersion() {
@@ -79,5 +79,5 @@ async function startMigrate({ versionPositional, version, force, debug }) {
79
79
  //#endregion
80
80
  export { startMigrate };
81
81
 
82
- //# sourceMappingURL=migrate-BJQvY88v.mjs.map
83
- //# debugId=5cc924ff-7015-5b6b-ac8d-a2c87fcac122
82
+ //# sourceMappingURL=migrate-jGKfE02L.mjs.map
83
+ //# debugId=5917a8da-bcbd-52a8-af0d-9c6d60ae5475
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-BJQvY88v.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n} from \"@powerhousedao/shared/clis\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport type { MigrateArgs } from \"../types.js\";\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const requested = versionPositional ?? version;\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, { stdio: \"inherit\" });\n}\n"],"names":[],"mappings":";;;;;;;;;AAWA,SAAS,yBAA6C;CACpD,IAAI,MAAM,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AACjD,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,MAAI;GACF,MAAM,MAAM,KAAK,MACf,aAAa,KAAK,KAAK,eAAe,EAAE,OAAO,CAChD;AACD,OAAI,IAAI,SAAS,wBAAyB,QAAO,IAAI;UAC/C;AAGR,QAAM,QAAQ,IAAI;;;AAItB,SAAgB,sBACd,YACoB;CACpB,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,WAAW,YAAY;EAChC,MAAM,IAAK,QAA0B;AACrC,MAAI,OAAO,MAAM,SAAU,QAAO;;;AAKtC,SAAgB,4BAA4B,MAInC;CACP,MAAM,EAAE,gBAAgB,gBAAgB,UAAU;AAClD,KAAI,MAAO;AACX,KAAI,CAAC,eACH,OAAM,IAAI,MACR,sJAED;AAEH,KAAI,kBAAkB,mBAAmB,eACvC,OAAM,IAAI,MACR,0BAA0B,eAAe,yBAAyB,eAAe,wDAElF;;AAIL,eAAsB,aAAa,EACjC,mBACA,SACA,OACA,SACc;CACd,MAAM,YAAY,qBAAqB;AACvC,KAAI,MAAO,SAAQ,IAAI,gCAAgC,YAAY;CAEnE,IAAI;AACJ,KAAI;AACF,kB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esContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n} from \"@powerhousedao/shared/clis\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport type { MigrateArgs } from \"../types.js\";\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const requested = versionPositional ?? version;\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, { stdio: \"inherit\" });\n}\n"],"names":[],"mappings":";;;;;;;;;AAWA,SAAS,yBAA6C;CACpD,IAAI,MAAM,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AACjD,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,MAAI;GACF,MAAM,MAAM,KAAK,MACf,aAAa,KAAK,K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+C,kBAAkB,YAClE;AACD,QAAM,WAAW,QAAQ,iBAAiB,UAAU;AACpD;;CAGF,MAAM,SAAS,MAAM,QAAQ,GAAG,SAAS;CACzC,MAAM,WAAW,eAAe,OAAO,WAAW;EAChD,yBAAyB;EACzB;EACA;EACA;EACA,GAAI,QAAQ,CAAC,UAAU,GAAG,EAAE;EAC7B,CAAC;AACF,KAAI,CAAC,SACH,OAAM,IAAI,MACR,0DAA0D,MAAM,IACjE;AAGH,uBAAsB,OAAO,SAAS;CAEtC,MAAM,UAAU,GAAG,SAAS,QAAQ,GAAG,SAAS,KAAK,KAAK,IAAI;AAC9D,KAAI,OAAO;AACT,UAAQ,IAAI,uCAAuC,QAAQ;AAC3D,UAAQ,IAAI,2BAA2B,UAAU;;AAEnD,UAAS,SAAS,EAAE,OAAO,WAAW,CAAC","debug_id":"5917a8da-bcbd-52a8-af0d-9c6d60ae5475"}
@@ -1,4 +1,4 @@
1
- import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-BaTZlyL3.mjs";
1
+ import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-C4isxXSO.mjs";
2
2
  export { removeStylesImports, updateConfigFile, updateStylesFile };
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]="08292df2-191b-515a-94a1-4ba124a2296c")}catch(e){}}();
4
- //# debugId=08292df2-191b-515a-94a1-4ba124a2296c
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]="33804f1d-c6ad-5650-aedb-dd51a31d17aa")}catch(e){}}();
4
+ //# debugId=33804f1d-c6ad-5650-aedb-dd51a31d17aa
@@ -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]="78c06d69-a52c-5bea-96c7-df0b42c3115e")}catch(e){}}();
3
- import path, { dirname } from "node:path";
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]="73159d3c-22a7-5dc6-8bd4-7b15f3b94c79")}catch(e){}}();
4
3
  import fs from "node:fs";
4
+ import path, { dirname } from "node:path";
5
5
  import crypto from "node:crypto";
6
6
  import { homedir } from "node:os";
7
7
  //#region src/utils.ts
@@ -161,5 +161,5 @@ function removeStylesImports(dependencies, projectPath) {
161
161
  //#endregion
162
162
  export { generateProjectDriveId as a, isPowerhouseProject as c, updateConfigFile as d, updatePackagesArray as f, findNodeProjectRoot as i, packageManagers as l, POWERHOUSE_GLOBAL_DIR as n, getPackageManagerFromLockfile as o, updateStylesFile as p, defaultPathValidation as r, getProjectInfo as s, POWERHOUSE_CONFIG_FILE as t, removeStylesImports as u };
163
163
 
164
- //# sourceMappingURL=utils-BaTZlyL3.mjs.map
165
- //# debugId=78c06d69-a52c-5bea-96c7-df0b42c3115e
164
+ //# sourceMappingURL=utils-C4isxXSO.mjs.map
165
+ //# debugId=73159d3c-22a7-5dc6-8bd4-7b15f3b94c79
@@ -1 +1 @@
1
- {"version":3,"file":"utils-BaTZlyL3.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path, { dirname } from \"node:path\";\nexport const POWERHOUSE_CONFIG_FILE = \"powerhouse.config.json\";\nexport const POWERHOUSE_GLOBAL_DIR = path.join(homedir(), \".ph\");\nexport const SUPPORTED_PACKAGE_MANAGERS = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n\nexport const packageManagers = {\n bun: {\n globalPathRegexp: /[\\\\/].bun[\\\\/]/,\n installCommand: \"bun add {{dependency}}\",\n uninstallCommand: \"bun remove {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"bun.lock\",\n updateCommand: \"bun update {{dependency}}\",\n buildAffected: \"bun run build:affected\",\n },\n pnpm: {\n globalPathRegexp: /[\\\\/]pnpm[\\\\/]/,\n installCommand: \"pnpm add {{dependency}}\",\n uninstallCommand: \"pnpm remove {{dependency}}\",\n workspaceOption: \"--workspace-root\",\n lockfile: \"pnpm-lock.yaml\",\n updateCommand: \"pnpm update {{dependency}}\",\n buildAffected: \"pnpm run build:affected\",\n },\n yarn: {\n globalPathRegexp: /[\\\\/]yarn[\\\\/]/,\n installCommand: \"yarn add {{dependency}}\",\n uninstallCommand: \"yarn remove {{dependency}}\",\n workspaceOption: \"-W\",\n lockfile: \"yarn.lock\",\n updateCommand: \"yarn upgrade {{dependency}}\",\n buildAffected: \"yarn run build:affected\",\n },\n npm: {\n installCommand: \"npm install {{dependency}}\",\n uninstallCommand: \"npm uninstall {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"package-lock.json\",\n updateCommand: \"npm update {{dependency}} --save\",\n buildAffected: \"npm run build:affected\",\n },\n};\n\ntype PathValidation = (dir: string) => boolean;\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\";\n\nexport type ProjectInfo = {\n isGlobal: boolean;\n path: string;\n packageManager: PackageManager;\n};\n\nexport function defaultPathValidation() {\n return true;\n}\n\nexport function isPowerhouseProject(dir: string) {\n const powerhouseConfigPath = path.join(dir, POWERHOUSE_CONFIG_FILE);\n\n return fs.existsSync(powerhouseConfigPath);\n}\n\nexport function findNodeProjectRoot(\n dir: string,\n pathValidation: PathValidation = defaultPathValidation,\n) {\n const packageJsonPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(packageJsonPath) && pathValidation(dir)) {\n return dir;\n }\n\n const parentDir = dirname(dir);\n\n if (parentDir === dir) {\n return null;\n }\n\n return findNodeProjectRoot(parentDir, pathValidation);\n}\n\nexport function getProjectInfo(debug?: boolean): ProjectInfo {\n const currentPath = process.cwd();\n\n if (debug) {\n console.log(\">>> currentPath\", currentPath);\n }\n\n const projectPath = findNodeProjectRoot(currentPath, isPowerhouseProject);\n\n if (!projectPath) {\n return {\n isGlobal: true,\n path: POWERHOUSE_GLOBAL_DIR,\n packageManager: getPackageManagerFromLockfile(POWERHOUSE_GLOBAL_DIR),\n };\n }\n\n return {\n isGlobal: false,\n path: projectPath,\n packageManager: getPackageManagerFromLockfile(projectPath),\n };\n}\n\n/**\n * Generates a unique drive ID based on the project path.\n * The same project path will always generate the same ID.\n * @param name - The name prefix for the drive ID (e.g., \"vetra\", \"powerhouse\")\n * @returns A unique drive ID in the format \"{name}-{hash}\"\n */\nexport function generateProjectDriveId(name: string): string {\n const projectInfo = getProjectInfo();\n const hash = crypto\n .createHash(\"sha256\")\n .update(projectInfo.path)\n .digest(\"hex\");\n const shortHash = hash.substring(0, 8);\n return `${name}-${shortHash}`;\n}\n\nexport function getPackageManagerFromLockfile(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, packageManagers.pnpm.lockfile))) {\n return \"pnpm\";\n } else if (fs.existsSync(path.join(dir, packageManagers.yarn.lockfile))) {\n return \"yarn\";\n } else if (fs.existsSync(path.join(dir, packageManagers.bun.lockfile))) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport function updatePackagesArray(\n currentPackages: PowerhouseConfig[\"packages\"] = [],\n dependencies: { name: string; version: string | undefined }[],\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n): PowerhouseConfig[\"packages\"] {\n const isInstall = task === \"install\";\n const mappedPackages = dependencies.map((dep) => ({\n packageName: dep.name,\n version: dep.version,\n provider,\n }));\n\n if (isInstall) {\n // Overwrite existing package if version is different\n const filteredPackages = currentPackages.filter(\n (pkg) => !dependencies.find((dep) => dep.name === pkg.packageName),\n );\n return [...filteredPackages, ...mappedPackages];\n }\n\n return currentPackages.filter(\n (pkg) => !dependencies.map((dep) => dep.name).includes(pkg.packageName),\n );\n}\n\n// Modify updateConfigFile to use the new function\nexport function updateConfigFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n registryUrl?: string,\n registryUrlExplicit = false,\n) {\n const configPath = path.join(projectPath, POWERHOUSE_CONFIG_FILE);\n\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `powerhouse.config.json file not found. projectPath: ${projectPath}`,\n );\n }\n\n const config = JSON.parse(\n fs.readFileSync(configPath, \"utf-8\"),\n ) as PowerhouseConfig;\n\n const updatedConfig: PowerhouseConfig = {\n ...config,\n packages: updatePackagesArray(\n config.packages,\n dependencies,\n task,\n provider,\n ),\n };\n\n if (\n task === \"install\" &&\n registryUrl &&\n (registryUrlExplicit || !config.packageRegistryUrl) &&\n dependencies.length > 0\n ) {\n updatedConfig.packageRegistryUrl = registryUrl;\n }\n\n fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));\n}\n\n/**\n * Recursively searches for a specific file by traversing up the directory tree.\n * Starting from the given path, it checks each parent directory until it finds\n * the target file or reaches the root directory.\n *\n * @param startPath - The absolute path of the directory to start searching from\n * @param targetFile - The name of the file to search for (e.g., 'package.json', 'pnpm-workspace.yaml')\n * @returns The absolute path of the directory containing the target file, or null if not found\n *\n * @example\n * // Find the workspace root directory\n * const workspaceRoot = findContainerDirectory('/path/to/project/src', 'pnpm-workspace.yaml');\n *\n * // Find the nearest package.json\n * const packageDir = findContainerDirectory('/path/to/project/src/components', 'package.json');\n */\nexport const findContainerDirectory = (\n startPath: string,\n targetFile: string,\n): string | null => {\n const filePath = path.join(startPath, targetFile);\n\n if (fs.existsSync(filePath)) {\n return startPath;\n }\n\n const parentDir = path.dirname(startPath);\n\n //reached the root directory and haven't found the file\n if (parentDir === startPath) {\n return null;\n }\n\n return findContainerDirectory(parentDir, targetFile);\n};\n\n/**\n * Updates the styles.css file to include imports for newly installed packages\n * @param dependencies - Array of dependencies that were installed\n * @param projectPath - Path to the project root\n */\nexport function updateStylesFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const fullCssPath = path.join(projectPath, cssPath);\n const importStatement = `@import '${cssPath}';`;\n\n // Check if the CSS file exists\n if (!fs.existsSync(fullCssPath)) {\n console.warn(`⚠️ Warning: CSS file not found at ${cssPath}`);\n continue;\n }\n\n // Check if import already exists\n if (currentStyles.includes(importStatement)) {\n continue;\n }\n\n // Find the last @import statement\n const importLines = currentStyles\n .split(\"\\n\")\n .filter((line) => line.trim().startsWith(\"@import\"));\n const lastImport = importLines[importLines.length - 1];\n\n if (lastImport) {\n // Insert new import after the last existing import\n updatedStyles = currentStyles.replace(\n lastImport,\n `${lastImport}\\n${importStatement}`,\n );\n } else {\n // If no imports exist, add at the top of the file\n updatedStyles = `${importStatement}\\n${currentStyles}`;\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n\n/**\n * Removes CSS imports for uninstalled packages from styles.css\n */\nexport function removeStylesImports(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const importStatement = `@import '${cssPath}';`;\n\n // Remove the import line if it exists\n const lines = updatedStyles.split(\"\\n\");\n const filteredLines = lines.filter(\n (line) => !line.trim().includes(importStatement),\n );\n\n if (filteredLines.length !== lines.length) {\n updatedStyles = filteredLines.join(\"\\n\");\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n"],"names":[],"mappings":";;;;;;;AAKA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB,KAAK,KAAK,SAAS,EAAE,MAAM;AAGhE,MAAa,kBAAkB;CAC7B,KAAK;EACH,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,MAAM;EACJ,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,MAAM;EACJ,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,KAAK;EACH,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACF;AAYD,SAAgB,wBAAwB;AACtC,QAAO;;AAGT,SAAgB,oBAAoB,KAAa;CAC/C,MAAM,uBAAuB,KAAK,KAAK,KAAK,uBAAuB;AAEnE,QAAO,GAAG,WAAW,qBAAqB;;AAG5C,SAAgB,oBACd,KACA,iBAAiC,uBACjC;CACA,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAEtD,KAAI,GAAG,WAAW,gBAAgB,IAAI,eAAe,IAAI,CACvD,QA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BAAgB,GAAG,gBAAgB,IAAI;;AAK3C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc;;;;;AAO/C,SAAgB,oBACd,cACA,aACA;CACA,MAAM,aAAa,KAAK,KAAK,aAAa,YAAY;AAGtD,KAAI,CAAC,GAAG,WAAW,WAAW,EAAE;AAC9B,UAAQ,KAAK,uDAAuD;AACpE;;CAGF,MAAM,gBAAgB,GAAG,aAAa,YAAY,QAAQ;CAC1D,IAAI,gBAAgB;AAEpB,MAAK,MAAM,OAAO,cAAc;EAE9B,MAAM,kBAAkB,YADR,kBAAkB,IAAI,KAAK,iBACC;EAG5C,MAAM,QAAQ,cAAc,MAAM,KAAK;EACvC,MAAM,gBAAgB,MAAM,QACzB,SAAS,CAAC,KAAK,MAAM,CAAC,SAAS,gBAAgB,CACjD;AAED,MAAI,cAAc,WAAW,MAAM,OACjC,iBAAgB,cAAc,KAAK,KAAK;;AAK5C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc","debug_id":"78c06d69-a52c-5bea-96c7-df0b42c3115e"}
1
+ {"version":3,"file":"utils-C4isxXSO.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path, { dirname } from \"node:path\";\nexport const POWERHOUSE_CONFIG_FILE = \"powerhouse.config.json\";\nexport const POWERHOUSE_GLOBAL_DIR = path.join(homedir(), \".ph\");\nexport const SUPPORTED_PACKAGE_MANAGERS = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n\nexport const packageManagers = {\n bun: {\n globalPathRegexp: /[\\\\/].bun[\\\\/]/,\n installCommand: \"bun add {{dependency}}\",\n uninstallCommand: \"bun remove {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"bun.lock\",\n updateCommand: \"bun update {{dependency}}\",\n buildAffected: \"bun run build:affected\",\n },\n pnpm: {\n globalPathRegexp: /[\\\\/]pnpm[\\\\/]/,\n installCommand: \"pnpm add {{dependency}}\",\n uninstallCommand: \"pnpm remove {{dependency}}\",\n workspaceOption: \"--workspace-root\",\n lockfile: \"pnpm-lock.yaml\",\n updateCommand: \"pnpm update {{dependency}}\",\n buildAffected: \"pnpm run build:affected\",\n },\n yarn: {\n globalPathRegexp: /[\\\\/]yarn[\\\\/]/,\n installCommand: \"yarn add {{dependency}}\",\n uninstallCommand: \"yarn remove {{dependency}}\",\n workspaceOption: \"-W\",\n lockfile: \"yarn.lock\",\n updateCommand: \"yarn upgrade {{dependency}}\",\n buildAffected: \"yarn run build:affected\",\n },\n npm: {\n installCommand: \"npm install {{dependency}}\",\n uninstallCommand: \"npm uninstall {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"package-lock.json\",\n updateCommand: \"npm update {{dependency}} --save\",\n buildAffected: \"npm run build:affected\",\n },\n};\n\ntype PathValidation = (dir: string) => boolean;\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\";\n\nexport type ProjectInfo = {\n isGlobal: boolean;\n path: string;\n packageManager: PackageManager;\n};\n\nexport function defaultPathValidation() {\n return true;\n}\n\nexport function isPowerhouseProject(dir: string) {\n const powerhouseConfigPath = path.join(dir, POWERHOUSE_CONFIG_FILE);\n\n return fs.existsSync(powerhouseConfigPath);\n}\n\nexport function findNodeProjectRoot(\n dir: string,\n pathValidation: PathValidation = defaultPathValidation,\n) {\n const packageJsonPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(packageJsonPath) && pathValidation(dir)) {\n return dir;\n }\n\n const parentDir = dirname(dir);\n\n if (parentDir === dir) {\n return null;\n }\n\n return findNodeProjectRoot(parentDir, pathValidation);\n}\n\nexport function getProjectInfo(debug?: boolean): ProjectInfo {\n const currentPath = process.cwd();\n\n if (debug) {\n console.log(\">>> currentPath\", currentPath);\n }\n\n const projectPath = findNodeProjectRoot(currentPath, isPowerhouseProject);\n\n if (!projectPath) {\n return {\n isGlobal: true,\n path: POWERHOUSE_GLOBAL_DIR,\n packageManager: getPackageManagerFromLockfile(POWERHOUSE_GLOBAL_DIR),\n };\n }\n\n return {\n isGlobal: false,\n path: projectPath,\n packageManager: getPackageManagerFromLockfile(projectPath),\n };\n}\n\n/**\n * Generates a unique drive ID based on the project path.\n * The same project path will always generate the same ID.\n * @param name - The name prefix for the drive ID (e.g., \"vetra\", \"powerhouse\")\n * @returns A unique drive ID in the format \"{name}-{hash}\"\n */\nexport function generateProjectDriveId(name: string): string {\n const projectInfo = getProjectInfo();\n const hash = crypto\n .createHash(\"sha256\")\n .update(projectInfo.path)\n .digest(\"hex\");\n const shortHash = hash.substring(0, 8);\n return `${name}-${shortHash}`;\n}\n\nexport function getPackageManagerFromLockfile(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, packageManagers.pnpm.lockfile))) {\n return \"pnpm\";\n } else if (fs.existsSync(path.join(dir, packageManagers.yarn.lockfile))) {\n return \"yarn\";\n } else if (fs.existsSync(path.join(dir, packageManagers.bun.lockfile))) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport function updatePackagesArray(\n currentPackages: PowerhouseConfig[\"packages\"] = [],\n dependencies: { name: string; version: string | undefined }[],\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n): PowerhouseConfig[\"packages\"] {\n const isInstall = task === \"install\";\n const mappedPackages = dependencies.map((dep) => ({\n packageName: dep.name,\n version: dep.version,\n provider,\n }));\n\n if (isInstall) {\n // Overwrite existing package if version is different\n const filteredPackages = currentPackages.filter(\n (pkg) => !dependencies.find((dep) => dep.name === pkg.packageName),\n );\n return [...filteredPackages, ...mappedPackages];\n }\n\n return currentPackages.filter(\n (pkg) => !dependencies.map((dep) => dep.name).includes(pkg.packageName),\n );\n}\n\n// Modify updateConfigFile to use the new function\nexport function updateConfigFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n registryUrl?: string,\n registryUrlExplicit = false,\n) {\n const configPath = path.join(projectPath, POWERHOUSE_CONFIG_FILE);\n\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `powerhouse.config.json file not found. projectPath: ${projectPath}`,\n );\n }\n\n const config = JSON.parse(\n fs.readFileSync(configPath, \"utf-8\"),\n ) as PowerhouseConfig;\n\n const updatedConfig: PowerhouseConfig = {\n ...config,\n packages: updatePackagesArray(\n config.packages,\n dependencies,\n task,\n provider,\n ),\n };\n\n if (\n task === \"install\" &&\n registryUrl &&\n (registryUrlExplicit || !config.packageRegistryUrl) &&\n dependencies.length > 0\n ) {\n updatedConfig.packageRegistryUrl = registryUrl;\n }\n\n fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));\n}\n\n/**\n * Recursively searches for a specific file by traversing up the directory tree.\n * Starting from the given path, it checks each parent directory until it finds\n * the target file or reaches the root directory.\n *\n * @param startPath - The absolute path of the directory to start searching from\n * @param targetFile - The name of the file to search for (e.g., 'package.json', 'pnpm-workspace.yaml')\n * @returns The absolute path of the directory containing the target file, or null if not found\n *\n * @example\n * // Find the workspace root directory\n * const workspaceRoot = findContainerDirectory('/path/to/project/src', 'pnpm-workspace.yaml');\n *\n * // Find the nearest package.json\n * const packageDir = findContainerDirectory('/path/to/project/src/components', 'package.json');\n */\nexport const findContainerDirectory = (\n startPath: string,\n targetFile: string,\n): string | null => {\n const filePath = path.join(startPath, targetFile);\n\n if (fs.existsSync(filePath)) {\n return startPath;\n }\n\n const parentDir = path.dirname(startPath);\n\n //reached the root directory and haven't found the file\n if (parentDir === startPath) {\n return null;\n }\n\n return findContainerDirectory(parentDir, targetFile);\n};\n\n/**\n * Updates the styles.css file to include imports for newly installed packages\n * @param dependencies - Array of dependencies that were installed\n * @param projectPath - Path to the project root\n */\nexport function updateStylesFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const fullCssPath = path.join(projectPath, cssPath);\n const importStatement = `@import '${cssPath}';`;\n\n // Check if the CSS file exists\n if (!fs.existsSync(fullCssPath)) {\n console.warn(`⚠️ Warning: CSS file not found at ${cssPath}`);\n continue;\n }\n\n // Check if import already exists\n if (currentStyles.includes(importStatement)) {\n continue;\n }\n\n // Find the last @import statement\n const importLines = currentStyles\n .split(\"\\n\")\n .filter((line) => line.trim().startsWith(\"@import\"));\n const lastImport = importLines[importLines.length - 1];\n\n if (lastImport) {\n // Insert new import after the last existing import\n updatedStyles = currentStyles.replace(\n lastImport,\n `${lastImport}\\n${importStatement}`,\n );\n } else {\n // If no imports exist, add at the top of the file\n updatedStyles = `${importStatement}\\n${currentStyles}`;\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n\n/**\n * Removes CSS imports for uninstalled packages from styles.css\n */\nexport function removeStylesImports(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const importStatement = `@import '${cssPath}';`;\n\n // Remove the import line if it exists\n const lines = updatedStyles.split(\"\\n\");\n const filteredLines = lines.filter(\n (line) => !line.trim().includes(importStatement),\n );\n\n if (filteredLines.length !== lines.length) {\n updatedStyles = filteredLines.join(\"\\n\");\n }\n }\n\n // Only write if changes were made\n if (updatedSt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AAkB,YADR,kBAAkB,IAAI,KAAK,iBACC;EAG5C,MAAM,QAAQ,cAAc,MAAM,KAAK;EACvC,MAAM,gBAAgB,MAAM,QACzB,SAAS,CAAC,KAAK,MAAM,CAAC,SAAS,gBAAgB,CACjD;AAED,MAAI,cAAc,WAAW,MAAM,OACjC,iBAAgB,cAAc,KAAK,KAAK;;AAK5C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc","debug_id":"73159d3c-22a7-5dc6-8bd4-7b15f3b94c79"}
@@ -1,8 +1,8 @@
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]="9bbf7fa0-0432-5c47-b876-f2b249aa5528")}catch(e){}}();
3
- import { a as parseDefaultDrivesUrl } from "./cli-connect-override-CFsTgKB6.mjs";
4
- import { t as runConnectStudio } from "./connect-studio-sRLuTabi.mjs";
5
- import { a as generateProjectDriveId } from "./utils-BaTZlyL3.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]="6525cfae-b45d-5517-82e5-5cd0225cb336")}catch(e){}}();
3
+ import { a as parseDefaultDrivesUrl } from "./cli-connect-override-D3hh4aH_.mjs";
4
+ import { t as runConnectStudio } from "./connect-studio-D6rfWCNB.mjs";
5
+ import { a as generateProjectDriveId } from "./utils-C4isxXSO.mjs";
6
6
  import { n as startSwitchboard$1 } from "./switchboard-CJMoMzWx.mjs";
7
7
  import { execSync } from "node:child_process";
8
8
  import { blue, green, red, yellow } from "colorette";
@@ -440,5 +440,5 @@ async function startVetra(args) {
440
440
  //#endregion
441
441
  export { startVetra };
442
442
 
443
- //# sourceMappingURL=vetra-D9MTB556.mjs.map
444
- //# debugId=9bbf7fa0-0432-5c47-b876-f2b249aa5528
443
+ //# sourceMappingURL=vetra-J6x1YaOp.mjs.map
444
+ //# debugId=6525cfae-b45d-5517-82e5-5cd0225cb336
@@ -1 +1 @@
1
- {"version":3,"file":"vetra-D9MTB556.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId } from \"../utils.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// Rebase a local drive URL onto --drives-public-base: keeps the /d/<slug>\n// path, swaps the loopback origin for the public base. Browser clients\n// behind a reverse proxy can't reach http://localhost:<port>. Non-loopback\n// URLs (e.g. a remote drive) are already public and pass through unchanged.\nconst rebaseDriveUrl = (driveUrl: string, publicBase: string): string => {\n // Unparseable URLs pass through unchanged, like non-loopback ones.\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n};\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: \"https://azure-elderly-tortoise-212.mypinata.cloud/ipfs/bafkreifddkbopiyvcirf7vaqar74th424r5phlxkdxniirdyg3qgu2ajha\",\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n if (verbose) {\n console.log(\"Starting Connect...\");\n const drives = previewDriveUrl\n ? `${driveUrl}, ${previewDriveUrl}`\n : driveUrl;\n console.log(` ➜ Connect will use drives: ${drives}`);\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: parseDefaultDrivesUrl(\n browserPreviewDriveUrl\n ? [browserDriveUrl, browserPreviewDriveUrl].join(\",\")\n : browserDriveUrl,\n ),\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch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,iBAAiB,uBAAuB,CAAC,KAAK,IAAI,GACnD,gBACL;IACD,kBAAkB;IACnB,EACF;AAED,SAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;IACf,EACD,kBACA,oBACD;;UAEI,OAAO;AACd,UAAQ,MAAM,MAAM","debug_id":"9bbf7fa0-0432-5c47-b876-f2b249aa5528"}
1
+ {"version":3,"file":"vetra-J6x1YaOp.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId } from \"../utils.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// Rebase a local drive URL onto --drives-public-base: keeps the /d/<slug>\n// path, swaps the loopback origin for the public base. Browser clients\n// behind a reverse proxy can't reach http://localhost:<port>. Non-loopback\n// URLs (e.g. a remote drive) are already public and pass through unchanged.\nconst rebaseDriveUrl = (driveUrl: string, publicBase: string): string => {\n // Unparseable URLs pass through unchanged, like non-loopback ones.\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n};\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: \"https://azure-elderly-tortoise-212.mypinata.cloud/ipfs/bafkreifddkbopiyvcirf7vaqar74th424r5phlxkdxniirdyg3qgu2ajha\",\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n if (verbose) {\n console.log(\"Starting Connect...\");\n const drives = previewDriveUrl\n ? `${driveUrl}, ${previewDriveUrl}`\n : driveUrl;\n console.log(` ➜ Connect will use drives: ${drives}`);\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: parseDefaultDrivesUrl(\n browserPreviewDriveUrl\n ? [browserDriveUrl, browserPreviewDriveUrl].join(\",\")\n : browserDriveUrl,\n ),\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":["startSwitchboard"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAiC;AACxC,KAAI;AAKF,SAJY,SAAS,6BAA6B;GAChD,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;IAAO;GAChC,CAAC,CAAC,MAAM,IACK;SACR;AACN,SAAO;;;;;;AAOX,eAAe,qBAA6C;AAC1D,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;AAEF,UAAQ,OAAO,MAAM,gDAAgD;AAErE,KAAG,GAAG,SAAS,WAAmB;AAChC,MAAG,OAAO;AAEV,WADY,OAAO,MAAM,IACV,KAAK;IACpB;GACF;;;;;AAMJ,eAAe,YAAY,UAAoC;AAC7D,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;AAEF,UAAQ,OAAO,MAAM,KAAK,SAAS,UAAU;AAE7C,KAAG,GAAG,SAAS,WAAmB;AAChC,MAAG,OAAO;GACV,MAAM,WAAW,OAAO,MAAM,CAAC,aAAa;AAC5C,WAAQ,aAAa,OAAO,aAAa,MAAM;IAC/C;GACF;;;;;;;AAQJ,eAAe,mBACb,cACwB;AACxB,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gBAAgB;GACzB,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;AAEF,UAAQ,IAAI,OAAO,IAAI,OAAO,GAAG,CAAC;AAClC,UAAQ,IAAI,iCAAiC;AAC7C,UAAQ,IAAI,IAAI,OAAO,GAAG,CAAC;AAC3B,UAAQ,IACN,+FACD;AACD,UAAQ,IAAI,oDAAoD;A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mBAAmB,aACf,eAAe,iBAAiB,WAAW,GAC3C;GACN,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe,sBACb,yBACI,CAAC,iBAAiB,uBAAuB,CAAC,KAAK,IAAI,GACnD,gBACL;IACD,kBAAkB;IACnB,EACF;AAED,SAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;IACf,EACD,kBACA,oBACD;;UAEI,OAAO;AACd,UAAQ,MAAM,MAAM","debug_id":"6525cfae-b45d-5517-82e5-5cd0225cb336"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.2-dev.4",
3
+ "version": "6.2.2-dev.41",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -40,16 +40,16 @@
40
40
  "semver": "7.7.4",
41
41
  "tsdown": "0.21.1",
42
42
  "vite": "8.0.10",
43
- "@powerhousedao/reactor": "6.2.2-dev.4",
44
- "@powerhousedao/builder-tools": "6.2.2-dev.4",
45
- "@powerhousedao/codegen": "6.2.2-dev.4",
46
- "@powerhousedao/common": "6.2.2-dev.4",
47
- "@powerhousedao/config": "6.2.2-dev.4",
48
- "@powerhousedao/shared": "6.2.2-dev.4",
49
- "@renown/sdk": "6.2.2-dev.4",
50
- "document-model": "6.2.2-dev.4",
51
- "@powerhousedao/vetra": "6.2.2-dev.4",
52
- "@powerhousedao/switchboard": "6.2.2-dev.4"
43
+ "@powerhousedao/builder-tools": "6.2.2-dev.41",
44
+ "@powerhousedao/codegen": "6.2.2-dev.41",
45
+ "@powerhousedao/common": "6.2.2-dev.41",
46
+ "@powerhousedao/config": "6.2.2-dev.41",
47
+ "@powerhousedao/reactor": "6.2.2-dev.41",
48
+ "@powerhousedao/switchboard": "6.2.2-dev.41",
49
+ "@powerhousedao/shared": "6.2.2-dev.41",
50
+ "@powerhousedao/vetra": "6.2.2-dev.41",
51
+ "@renown/sdk": "6.2.2-dev.41",
52
+ "document-model": "6.2.2-dev.41"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "25.2.3",
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-B5LEeRPm.mjs","sources":["../src/services/build.ts"],"sourcesContent":["import {\n browserBuildConfig,\n nodeBuildConfig,\n} from \"@powerhousedao/shared/build-config\";\nimport { execSync } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport type { BuildArgs } from \"../types.js\";\n\nexport async function runBuild(args: BuildArgs) {\n const { outDir } = args;\n\n await tsdownBuild({\n ...browserBuildConfig,\n outDir: join(outDir, \"browser\"),\n });\n\n await tsdownBuild({\n ...nodeBuildConfig,\n outDir: join(outDir, \"node\"),\n });\n\n const detectResult = await detect();\n const agent = detectResult?.agent ?? \"npm\";\n\n // Emit types with tsc\n const tscCommand = resolveCommand(agent, \"execute-local\", [\"tsc\", \"--build\"]);\n if (tscCommand === null) {\n console.error(\n \"You need to have typescript installed to use the `build` command.\",\n );\n process.exit(1);\n }\n console.log(\"\\n▶ Emitting types via tsc...\");\n try {\n execSync(`${tscCommand.command} ${tscCommand.args.join(\" \")}`, {\n stdio: \"inherit\",\n });\n console.log(\"✔ Types emitted to\", join(outDir, \"types\"));\n } catch {\n console.warn(\n \"✘ tsc reported errors above; declarations were still written. Fix the errors to keep types accurate.\",\n );\n }\n\n const executeLocalCommand = resolveCommand(agent, \"execute-local\", [\n \"tailwindcss\",\n \"-i\",\n \"./style.css\",\n \"-o\",\n \"./dist/style.css\",\n ]);\n if (executeLocalCommand === null) {\n console.error(\n \"You need to have tailwindcss installed to use the `build` command.\",\n );\n process.exit(1);\n }\n execSync(\n `${executeLocalCommand.command} ${executeLocalCommand.args.join(\" \")}`,\n );\n}\n"],"names":["tsdownBuild"],"mappings":";;;;;;;;AAUA,eAAsB,SAAS,MAAiB;CAC9C,MAAM,EAAE,WAAW;AAEnB,OAAMA,MAAY;EAChB,GAAG;EACH,QAAQ,KAAK,QAAQ,UAAU;EAChC,CAAC;AAEF,OAAMA,MAAY;EAChB,GAAG;EACH,QAAQ,KAAK,QAAQ,OAAO;EAC7B,CAAC;CAGF,MAAM,SADe,MAAM,QAAQ,GACP,SAAS;CAGrC,MAAM,aAAa,eAAe,OAAO,iBAAiB,CAAC,OAAO,UAAU,CAAC;AAC7E,KAAI,eAAe,MAAM;AACvB,UAAQ,MACN,oEACD;AACD,UAAQ,KAAK,EAAE;;AAEjB,SAAQ,IAAI,gCAAgC;AAC5C,KAAI;AACF,WAAS,GAAG,WAAW,QAAQ,GAAG,WAAW,KAAK,KAAK,IAAI,IAAI,EAC7D,OAAO,WACR,CAAC;AACF,UAAQ,IAAI,sBAAsB,KAAK,QAAQ,QAAQ,CAAC;SAClD;AACN,UAAQ,KACN,uGACD;;CAGH,MAAM,sBAAsB,eAAe,OAAO,iBAAiB;EACjE;EACA;EACA;EACA;EACA;EACD,CAAC;AACF,KAAI,wBAAwB,MAAM;AAChC,UAAQ,MACN,qEACD;AACD,UAAQ,KAAK,EAAE;;AAEjB,UACE,GAAG,oBAAoB,QAAQ,GAAG,oBAAoB,KAAK,KAAK,IAAI,GACrE","debug_id":"53802aa9-82a4-5f73-8876-9bf4310ea58e"}
@@ -1,4 +0,0 @@
1
- import { t as runBuild } from "./build-B5LEeRPm.mjs";
2
- export { runBuild };
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]="03c7575f-6904-5af5-be74-46221d2b3a6f")}catch(e){}}();
4
- //# debugId=03c7575f-6904-5af5-be74-46221d2b3a6f
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli-connect-override-CFsTgKB6.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 = { instancePath?: string; message?: string };\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 return ` ${path} ${e.message ?? \"\"}`.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 */\nexport function validateConnectPatch(raw: string): ConnectPartial & {\n packageRegistryUrl?: unknown;\n} {\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 `ph connect config --json: 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 `ph connect config --json: payload must be a JSON object, got ${typeof parsed}.`,\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 `ph connect config --json: validation failed:\\n${formatErrors(validateConnect.errors)}`,\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 { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { deepMerge } from \"@powerhousedao/shared/connect\";\nimport type { ConnectBuildArgs, ConnectStudioArgs } from \"../types.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\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 allowAddDrive?: boolean | undefined;\n externalPackages?: 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/**\n * Parse the `--json` payload (if any). Throws on malformed JSON or on a\n * non-object root with a clear, command-line-visible error.\n */\nfunction parseJsonOverride(raw: string | undefined): PlainObject {\n if (raw === undefined || raw === \"\") return {};\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 `--json: invalid JSON (${msg}). Expected a partial 'connect.*' blob, e.g. --json '{\"renown\":{\"url\":\"...\"}}'.`,\n { cause: e },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n `--json: payload must be a JSON object, got ${typeof parsed}.`,\n );\n }\n return parsed as PlainObject;\n}\n\n/**\n * Re-exported for `runConnectConfig` so the same JSON validation runs for\n * both `build --json` and `config --json`.\n */\nexport function parseConnectJsonArg(raw: string | undefined): PlainObject {\n return parseJsonOverride(raw);\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 19 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 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 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 allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\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, but an explicitly passed flag (e.g. `--default-drives-url`)\n * always wins.\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 return [callerOverride, flagOverride, studioOverride]\n .filter(\n (o): o is PHConnectRuntimeConfig =>\n o !== undefined && Object.keys(o).length > 0,\n )\n .reduce((acc, o) => deepM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AK,MAAM,UAAU,KAAK,EAAE,EAAE,EAAE,CAA2B","debug_id":"df149280-e157-531d-9c3a-5cab603ab4c2"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-config-O3qXExg9.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 { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n ConfigLoader,\n DEFAULT_CONNECT_CONFIG,\n JsonConfigAdapter,\n deepMerge,\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.connect. Doesn't go through env or dist — list mode shows what the\n * source declares + defaults, which is what the next build will produce as a\n * 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 deepMerge(DEFAULT_CONNECT_CONFIG, sourceConnect);\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 allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\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 19) 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;AACnB,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,QAAQ,QAAQ,OAAO,QAAQ,SAAU,QAAO,KAAA;AACpD,QAAO,IAAgC,OAAO,IAAI;;AAEpD,QAAO;;;;ACuCT,MAAM,cAAc;AACpB,MAAM,uBAAuB;AAE7B,SAAS,kBAAkB,KAAqB;AAC9C,QAAO,KAAK,KAAK,YAAY;;AAG/B,SAAS,gBAAgB,KAAa,YAAwC;CAC5E,MAAM,UAAU;CAChB,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,MAAM,WAAW,WAAW;AAElC,QAAO,KADK,WAAW,IAAI,GAAG,MAAM,QAAQ,KAAK,IAAI,EACpC,YAAY;;;;;;;AAQ/B,eAAe,cAAc,MAAgD;AAC3E,KAAI,CAAC,WAAW,KAAK,CAAE,QAAO,EAAE;CAEhC,MAAM,MAAM,MADI,IAAI,kBAAkB,EAAE,MAAM,CAAC,CACrB,MAAM;AAChC,QAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,IAAI,GACvD,MACD,EAAE;;AAGR,eAAe,eACb,MACA,MACe;CACf,MAAM,UAAU,IAAI,kBAAkB,EAAE,MAAM,CAAC;CAE/C,MAAM,QAAQ;EACZ,GAAG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,SACpB,OAAM,IAAI,MACR,+DAA+D,OAAO,OAAO,IAC9E;AAEH,sBAAmB;AACnB,WAAQ,EAAE;QAEV,SAAQ,wBACN,YACA,KAAK,gBACN;YAEM,SAAS;EAClB,MAAM,YAAY,qBAAqB,KAAK,KAAM;AAIlD,MAAI,OAAO,UAAU,uBAAuB,SAC1C,oBAAmB,oBAAoB,UAAU;EAEnD,MAAM,cAAc,EAAE,GAAG,WAAW;AACpC,SAAO,YAAY;AACnB,UAAQ;OAER,SAAQ,sBAAsB,UAAU;AAG1C,KAAI,OAAO,KAAK,MAAM,CAAC,WAAW,KAAK,qBAAqB,KAAA,EAC1D,OAAM,IAAI,MACR,gIACD;CAWH,MAAM,cAAc,UALlB,OAAO,WACP,OAAO,OAAO,YAAY,YAC1B,CAAC,MAAM,QAAQ,OAAO,QAAQ,GACzB,OAAO,UACP,EAAE,EAGP,MACD;CACD,MAAM,aAAsC;EAC1C,GAAG;EACH,SAAS;EACV;AACD,KAAI,qBAAqB,KAAA,EACvB,YAAW,qBAAqB;AAGlC,OAAM,eAAe,YAAY,WAAW;AAI5C,KAAI,WAAW,SAAS,EAAE;EACxB,MAAM,aAAa,IAAI,aACrB,IAAI,kBAAkB,EAAE,MAAM,UAAU,CAAC,CAC1C;EACD,MAAM,YAAqC,EAAE,SAAS,OAAO;AAC7D,MAAI,qBAAqB,KAAA,EACvB,WAAU,qBAAqB;AAEjC,QAAM,WAAW,MAAM,UAAU;;AAGnC,SAAQ,OAAO,MACb,4BAA4B,aAAa,WAAW,SAAS,GAAG,QAAQ,aAAa,GAAG,IACzF","debug_id":"bdeba91a-33bc-543e-87f8-cc51074d0b17"}
@@ -1,5 +0,0 @@
1
- import "./cli-connect-override-CFsTgKB6.mjs";
2
- import { t as runConnectStudio } from "./connect-studio-sRLuTabi.mjs";
3
- export { runConnectStudio };
4
- !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]="428c7e07-1ff4-5d55-ba49-2b6a1255f63b")}catch(e){}}();
5
- //# debugId=428c7e07-1ff4-5d55-ba49-2b6a1255f63b