@powerhousedao/ph-cli 6.2.3-dev.2 → 6.2.3-dev.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-uQXq6_HU.mjs → build-BM7yZxAf.mjs} +68 -8
- package/dist/build-BM7yZxAf.mjs.map +1 -0
- package/dist/build-D4-3Ks7v.mjs +4 -0
- package/dist/{cli-connect-override-D3hh4aH_.mjs → cli-connect-override-BJ5mgqM1.mjs} +46 -9
- package/dist/cli-connect-override-BJ5mgqM1.mjs.map +1 -0
- package/dist/cli.mjs +172 -22
- package/dist/cli.mjs.map +1 -1
- package/dist/connect-build-DNQgVniR.mjs +149 -0
- package/dist/connect-build-DNQgVniR.mjs.map +1 -0
- package/dist/{connect-config-BWGiW3IB.mjs → connect-config-C3sDVZ59.mjs} +7 -6
- package/dist/connect-config-C3sDVZ59.mjs.map +1 -0
- package/dist/{connect-studio-D6rfWCNB.mjs → connect-studio-oKEsKMZg.mjs} +4 -4
- package/dist/{connect-studio-D6rfWCNB.mjs.map → connect-studio-oKEsKMZg.mjs.map} +1 -1
- package/dist/connect-studio-xE1Tr6KS.mjs +5 -0
- package/dist/generate-piece-B8Kbsshu.mjs +61 -0
- package/dist/generate-piece-B8Kbsshu.mjs.map +1 -0
- package/dist/generate-piece-action-DZ14j8Gi.mjs +26 -0
- package/dist/generate-piece-action-DZ14j8Gi.mjs.map +1 -0
- package/dist/generate-piece-trigger-CvzZOIPh.mjs +27 -0
- package/dist/generate-piece-trigger-CvzZOIPh.mjs.map +1 -0
- package/dist/{generate-processor-_WOx-mMe.mjs → generate-processor-BK7moaDe.mjs} +3 -3
- package/dist/{generate-processor-_WOx-mMe.mjs.map → generate-processor-BK7moaDe.mjs.map} +1 -1
- package/dist/{generate-subgraph-BsHUstpl.mjs → generate-subgraph-CCXHyg4b.mjs} +3 -3
- package/dist/{generate-subgraph-BsHUstpl.mjs.map → generate-subgraph-CCXHyg4b.mjs.map} +1 -1
- package/dist/{init-BZP6gvYd.mjs → init-B3Tp7X17.mjs} +4 -4
- package/dist/{init-BZP6gvYd.mjs.map → init-B3Tp7X17.mjs.map} +1 -1
- package/dist/{inspect-DXjbQEV_.mjs → inspect-B8eX-XPA.mjs} +11 -4
- package/dist/inspect-B8eX-XPA.mjs.map +1 -0
- package/dist/{migrate-jGKfE02L.mjs → migrate-CM_3Luws.mjs} +3 -3
- package/dist/{migrate-jGKfE02L.mjs.map → migrate-CM_3Luws.mjs.map} +1 -1
- package/dist/{registry-auth-DxEWCJu2.mjs → registry-auth-C9en-6FX.mjs} +3 -3
- package/dist/{registry-auth-DxEWCJu2.mjs.map → registry-auth-C9en-6FX.mjs.map} +1 -1
- package/dist/scripts/generate-commands-docs.ts +8 -0
- package/dist/{switchboard-CJMoMzWx.mjs → switchboard-Cabg_xYF.mjs} +3 -3
- package/dist/{switchboard-CJMoMzWx.mjs.map → switchboard-Cabg_xYF.mjs.map} +1 -1
- package/dist/switchboard-DTJkt8lG.mjs +4 -0
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs → switchboard-migrate-RN3lGK4Q.mjs} +3 -3
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs.map → switchboard-migrate-RN3lGK4Q.mjs.map} +1 -1
- package/dist/{switchboard-reset-BcQXlcVf.mjs → switchboard-reset-BWLfgYuv.mjs} +3 -3
- package/dist/{switchboard-reset-BcQXlcVf.mjs.map → switchboard-reset-BWLfgYuv.mjs.map} +1 -1
- package/dist/{utils-BzwczAW-.mjs → utils-B6flWWiG.mjs} +3 -3
- package/dist/{utils-C4isxXSO.mjs → utils-jTHrApMW.mjs} +3 -3
- package/dist/{utils-C4isxXSO.mjs.map → utils-jTHrApMW.mjs.map} +1 -1
- package/dist/{vetra-DkF6EJMY.mjs → vetra-DCD3t7Qh.mjs} +24 -14
- package/dist/vetra-DCD3t7Qh.mjs.map +1 -0
- package/package.json +12 -11
- package/dist/build-C-A5-ipO.mjs +0 -4
- package/dist/build-uQXq6_HU.mjs.map +0 -1
- package/dist/cli-connect-override-D3hh4aH_.mjs.map +0 -1
- package/dist/connect-build-WL4axo4z.mjs +0 -43
- package/dist/connect-build-WL4axo4z.mjs.map +0 -1
- package/dist/connect-config-BWGiW3IB.mjs.map +0 -1
- package/dist/connect-studio-BIQzyq5B.mjs +0 -5
- package/dist/inspect-DXjbQEV_.mjs.map +0 -1
- package/dist/switchboard-iRFugh8I.mjs +0 -4
- package/dist/vetra-DkF6EJMY.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
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]="
|
|
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]="13e0b9da-2fda-52d7-b20b-d13a8a635b3d")}catch(e){}}();
|
|
3
3
|
import { Kysely, PostgresDialect } from "kysely";
|
|
4
4
|
import { Pool } from "pg";
|
|
5
5
|
import { REACTOR_SCHEMA, getMigrationStatus, runMigrations } from "@powerhousedao/reactor";
|
|
@@ -49,5 +49,5 @@ async function runSwitchboardMigrations(options) {
|
|
|
49
49
|
//#endregion
|
|
50
50
|
export { runSwitchboardMigrations };
|
|
51
51
|
|
|
52
|
-
//# sourceMappingURL=switchboard-migrate-
|
|
53
|
-
//# debugId=
|
|
52
|
+
//# sourceMappingURL=switchboard-migrate-RN3lGK4Q.mjs.map
|
|
53
|
+
//# debugId=13e0b9da-2fda-52d7-b20b-d13a8a635b3d
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard-migrate-
|
|
1
|
+
{"version":3,"file":"switchboard-migrate-RN3lGK4Q.mjs","sources":["../src/services/switchboard-migrate.ts"],"sourcesContent":["import { Kysely, PostgresDialect } from \"kysely\";\nimport { Pool } from \"pg\";\nimport {\n runMigrations,\n getMigrationStatus,\n REACTOR_SCHEMA,\n} from \"@powerhousedao/reactor\";\n\ninterface MigrationOptions {\n dbPath?: string;\n statusOnly?: boolean;\n}\n\nfunction isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nexport async function runSwitchboardMigrations(\n options: MigrationOptions,\n): Promise<void> {\n const dbPath =\n options.dbPath ??\n process.env.PH_REACTOR_DATABASE_URL ??\n process.env.DATABASE_URL;\n\n if (!dbPath || !isPostgresUrl(dbPath)) {\n console.log(\"No PostgreSQL URL configured. Skipping migrations.\");\n console.log(\"(PGlite migrations are handled automatically on startup)\");\n return;\n }\n\n console.log(`Database: ${dbPath}`);\n\n const pool = new Pool({ connectionString: dbPath });\n\n const db = new Kysely<any>({\n dialect: new PostgresDialect({ pool }),\n });\n\n try {\n if (options.statusOnly) {\n console.log(\"\\nChecking migration status...\");\n const migrations = await getMigrationStatus(db, REACTOR_SCHEMA);\n\n console.log(\"\\nMigration Status:\");\n console.log(\"=================\");\n\n for (const migration of migrations) {\n const status = migration.executedAt\n ? `[OK] Executed at ${migration.executedAt.toISOString()}`\n : \"[--] Pending\";\n console.log(`${status} - ${migration.name}`);\n }\n } else {\n console.log(\"\\nRunning migrations...\");\n const result = await runMigrations(db, REACTOR_SCHEMA);\n\n if (!result.success) {\n console.error(\"Migration failed:\", result.error?.message);\n process.exit(1);\n }\n\n if (result.migrationsExecuted.length === 0) {\n console.log(\"No migrations to run - database is up to date\");\n } else {\n console.log(\n `Successfully executed ${result.migrationsExecuted.length} migration(s):`,\n );\n for (const name of result.migrationsExecuted) {\n console.log(` - ${name}`);\n }\n }\n }\n } catch (error) {\n console.error(\n \"Error:\",\n error instanceof Error ? error.message : String(error),\n );\n process.exit(1);\n } finally {\n await db.destroy();\n }\n}\n"],"names":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AQ,KAAK,EAAE;WACP;AACR,QAAM,GAAG,SAAS","debug_id":"13e0b9da-2fda-52d7-b20b-d13a8a635b3d"}
|
|
@@ -1,5 +1,5 @@
|
|
|
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]="
|
|
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]="3458acc6-5c28-5042-99a5-4fa8b596cb94")}catch(e){}}();
|
|
3
3
|
import { cyan, green, red, yellow } from "colorette";
|
|
4
4
|
import { promises } from "node:fs";
|
|
5
5
|
//#region src/services/switchboard-reset.ts
|
|
@@ -83,5 +83,5 @@ async function resetSwitchboardDatabase(options) {
|
|
|
83
83
|
//#endregion
|
|
84
84
|
export { resetSwitchboardDatabase };
|
|
85
85
|
|
|
86
|
-
//# sourceMappingURL=switchboard-reset-
|
|
87
|
-
//# debugId=
|
|
86
|
+
//# sourceMappingURL=switchboard-reset-BWLfgYuv.mjs.map
|
|
87
|
+
//# debugId=3458acc6-5c28-5042-99a5-4fa8b596cb94
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard-reset-
|
|
1
|
+
{"version":3,"file":"switchboard-reset-BWLfgYuv.mjs","sources":["../src/services/switchboard-reset.ts"],"sourcesContent":["import { yellow, red, green, cyan } from \"colorette\";\nimport { promises as fs } from \"node:fs\";\n\nexport interface ResetSwitchboardOptions {\n dbPath?: string;\n yes?: boolean;\n}\n\nexport interface ResolvedResetPaths {\n reactorDir: string | null;\n readModelDir: string | null;\n postgresUrl: string | null;\n}\n\nconst CONFIRMATION_TOKEN = \"reset\";\n\nexport function isPostgresUrl(url: string): boolean {\n return url.startsWith(\"postgresql://\") || url.startsWith(\"postgres://\");\n}\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\n/**\n * Resolves the on-disk PGlite directories that `--reset` would delete.\n * Mirrors the resolution in apps/switchboard/src/server.mts so we touch the\n * same paths the running switchboard uses. When a Postgres URL is configured\n * the corresponding directory is null and `postgresUrl` is populated so the\n * caller can refuse.\n */\nexport function resolveResetPaths(\n options: ResetSwitchboardOptions,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedResetPaths {\n const readModelDbPath =\n options.dbPath ?? env.DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL;\n const readModelPath = readModelDbPath || \".ph/read-storage\";\n const reactorDbUrl =\n options.dbPath ??\n env.PH_REACTOR_DATABASE_URL ??\n env.PH_SWITCHBOARD_DATABASE_URL;\n const reactorPath = reactorDbUrl || \"./.ph/reactor-storage\";\n\n const reactorIsPostgres = !!reactorDbUrl && isPostgresUrl(reactorDbUrl);\n const readModelIsPostgres =\n !!readModelDbPath && isPostgresUrl(readModelDbPath);\n\n let postgresUrl: string | null = null;\n if (reactorIsPostgres) postgresUrl = reactorDbUrl as string;\n else if (readModelIsPostgres) postgresUrl = readModelDbPath as string;\n\n return {\n reactorDir: reactorIsPostgres ? null : reactorPath,\n readModelDir: readModelIsPostgres ? null : readModelPath,\n postgresUrl,\n };\n}\n\nasync function promptForConfirmation(): Promise<boolean> {\n const enquirer = await import(\"enquirer\");\n try {\n const answer = await enquirer.default.prompt<{ confirmation: string }>({\n type: \"input\",\n name: \"confirmation\",\n message: `Type \"${CONFIRMATION_TOKEN}\" to confirm wiping the local switchboard databases:`,\n });\n return answer.confirmation.trim() === CONFIRMATION_TOKEN;\n } catch {\n return false;\n }\n}\n\nexport async function resetSwitchboardDatabase(\n options: ResetSwitchboardOptions,\n): Promise<void> {\n const paths = resolveResetPaths(options);\n\n if (paths.postgresUrl) {\n console.error(\n red(\n `Refusing to reset: a PostgreSQL URL is configured (${paths.postgresUrl}).`,\n ),\n );\n console.error(\n yellow(\n \"`ph switchboard --reset` only wipes the local PGlite stores. \" +\n \"To reset a Postgres-backed switchboard, drop/recreate the database manually.\",\n ),\n );\n process.exit(1);\n }\n\n const targets = [paths.reactorDir, paths.readModelDir].filter(\n (d): d is string => d !== null,\n );\n\n if (targets.length === 0) {\n console.error(red(\"No local PGlite directories resolved; nothing to do.\"));\n process.exit(1);\n }\n\n console.log(yellow(\"The following directories will be permanently deleted:\"));\n for (const dir of targets) {\n console.log(` - ${dir}`);\n }\n console.log(\n yellow(\n \"This will wipe all local switchboard state. Migrations will re-run on next `ph switchboard`.\",\n ),\n );\n\n let confirmed = false;\n if (options.yes) {\n confirmed = true;\n } else if (isInteractive()) {\n confirmed = await promptForConfirmation();\n } else {\n console.error(\n red(\n \"Refusing to reset in a non-interactive context without --yes. Re-run with --yes to confirm.\",\n ),\n );\n process.exit(1);\n }\n\n if (!confirmed) {\n console.error(red(\"Aborted: confirmation not provided.\"));\n process.exit(1);\n }\n\n for (const dir of targets) {\n await fs.rm(dir, { recursive: true, force: true });\n console.log(cyan(`Removed ${dir}`));\n }\n\n console.log(\n green(\n \"Switchboard local storage reset. Run `ph switchboard` to re-initialize.\",\n ),\n );\n}\n"],"names":["fs"],"mappings":";;;;;AAcA,MAAM,qBAAqB;AAE3B,SAAgB,cAAc,KAAsB;AAClD,QAAO,IAAI,WAAW,gBAAgB,IAAI,IAAI,WAAW,cAAc;;AAGzE,SAAS,gBAAyB;AAChC,QAAO,QAAQ,QAAQ,MAAM,MAAM,IAAI,CAAC,QAAQ,IAAI;;;;;;;;;AAUtD,SAAgB,kBACd,SACA,MAAyB,QAAQ,KACb;CACpB,MAAM,kBACJ,QAAQ,UAAU,IAAI,gBAAgB,IAAI;CAC5C,MAAM,gBAAgB,mBAAmB;CACzC,MAAM,eACJ,QAAQ,UACR,IAAI,2BACJ,IAAI;CACN,MAAM,cAAc,gBAAgB;CAEpC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,QAAMA,SAAG,GAAG,KAAK;GAAE,WAAW;GAAM,OAAO;GAAM,CAAC;AAClD,UAAQ,IAAI,KAAK,WAAW,MAAM,CAAC;;AAGrC,SAAQ,IACN,MACE,0EACD,CACF","debug_id":"3458acc6-5c28-5042-99a5-4fa8b596cb94"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-
|
|
1
|
+
import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-jTHrApMW.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]="
|
|
4
|
-
//# debugId=
|
|
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]="e014f3b0-c360-5354-80a5-89e5d65b199a")}catch(e){}}();
|
|
4
|
+
//# debugId=e014f3b0-c360-5354-80a5-89e5d65b199a
|
|
@@ -1,5 +1,5 @@
|
|
|
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]="
|
|
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]="3a02040d-5a16-5a00-844d-e22c162e4721")}catch(e){}}();
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path, { dirname } from "node:path";
|
|
5
5
|
import crypto from "node:crypto";
|
|
@@ -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-
|
|
165
|
-
//# debugId=
|
|
164
|
+
//# sourceMappingURL=utils-jTHrApMW.mjs.map
|
|
165
|
+
//# debugId=3a02040d-5a16-5a00-844d-e22c162e4721
|
|
@@ -1 +1 @@
|
|
|
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 (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n"],"names":[],"mappings":";;;;;;;AAKA,MAAa,yBAAyB;AACtC,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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
|
+
{"version":3,"file":"utils-jTHrApMW.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;E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MAAM,UAAU,kBAAkB,IAAI,KAAK;EAC3C,MAAM,cAAc,KAAK,KAAK,aAAa,QAAQ;EACnD,MAAM,kBAAkB,YAAY,QAAQ;AAG5C,MAAI,CAAC,GAAG,WAAW,YAAY,EAAE;AAC/B,WAAQ,KAAK,qCAAqC,UAAU;AAC5D;;AAIF,MAAI,cAAc,SAAS,gBAAgB,CACzC;EAIF,MAAM,cAAc,cACjB,MAAM,KAAK,CACX,QAAQ,SAAS,KAAK,MAAM,CAAC,WAAW,UAAU,CAAC;EACtD,MAAM,aAAa,YAAY,YAAY,SAAS;AAEpD,MAAI,WAEF,iBAAgB,cAAc,QAC5B,YACA,GAAG,WAAW,IAAI,kBACnB;MAGD,iBAAgB,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":"3a02040d-5a16-5a00-844d-e22c162e4721"}
|
|
@@ -1,13 +1,14 @@
|
|
|
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]="
|
|
3
|
-
import { a as parseDefaultDrivesUrl } from "./cli-connect-override-
|
|
4
|
-
import { t as runConnectStudio } from "./connect-studio-
|
|
5
|
-
import { a as generateProjectDriveId } from "./utils-
|
|
6
|
-
import { n as startSwitchboard$1 } from "./switchboard-
|
|
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]="3b8d15bb-6fbd-53fc-ad65-01cdd51a9f0b")}catch(e){}}();
|
|
3
|
+
import { a as parseDefaultDrivesUrl, i as wasFlagExplicitlyPassed, u as mergeDefaultDrives } from "./cli-connect-override-BJ5mgqM1.mjs";
|
|
4
|
+
import { t as runConnectStudio } from "./connect-studio-oKEsKMZg.mjs";
|
|
5
|
+
import { a as generateProjectDriveId } from "./utils-jTHrApMW.mjs";
|
|
6
|
+
import { n as startSwitchboard$1 } from "./switchboard-Cabg_xYF.mjs";
|
|
7
7
|
import { execSync } from "node:child_process";
|
|
8
8
|
import { blue, green, red, yellow } from "colorette";
|
|
9
9
|
import fs from "node:fs";
|
|
10
|
-
import path from "node:path";
|
|
10
|
+
import path, { join } from "node:path";
|
|
11
|
+
import { getConfig } from "@powerhousedao/shared/clis";
|
|
11
12
|
import { createLogger } from "vite";
|
|
12
13
|
import { createVetraDocument, getVetraDocuments, setPackageGithubUrl } from "@powerhousedao/common/utils";
|
|
13
14
|
import { isPortAvailable } from "@powerhousedao/switchboard/server";
|
|
@@ -539,19 +540,28 @@ async function startVetra(args) {
|
|
|
539
540
|
}
|
|
540
541
|
if (verbose) console.log("Starting Codegen Reactor...");
|
|
541
542
|
if (!disableConnect) {
|
|
543
|
+
const publicBase = args.drivesPublicBase;
|
|
544
|
+
const browserDriveUrl = publicBase ? rebaseDriveUrl(driveUrl, publicBase) : driveUrl;
|
|
545
|
+
const browserPreviewDriveUrl = previewDriveUrl && publicBase ? rebaseDriveUrl(previewDriveUrl, publicBase) : previewDriveUrl;
|
|
546
|
+
const resolvedDefaultDrives = mergeDefaultDrives([...browserDriveUrl ? [{
|
|
547
|
+
url: browserDriveUrl,
|
|
548
|
+
name: null,
|
|
549
|
+
icon: null
|
|
550
|
+
}] : [], ...browserPreviewDriveUrl ? [{
|
|
551
|
+
url: browserPreviewDriveUrl,
|
|
552
|
+
name: null,
|
|
553
|
+
icon: null
|
|
554
|
+
}] : []], getConfig(join(projectDir, "powerhouse.config.json")).connect?.drives?.defaultDrives ?? []);
|
|
542
555
|
if (verbose) {
|
|
543
556
|
console.log("Starting Connect...");
|
|
544
|
-
const
|
|
545
|
-
console.log(` ➜ Connect will use drives: ${
|
|
557
|
+
const printedDefaultDrives = mergeDefaultDrives(resolvedDefaultDrives, wasFlagExplicitlyPassed("default-drives-url") ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? "") : []);
|
|
558
|
+
console.log(` ➜ Connect will use default drives: ${printedDefaultDrives.map((d) => "url" in d ? d.url : `local:${d.id}`).join(", ")}`);
|
|
546
559
|
}
|
|
547
560
|
console.log();
|
|
548
561
|
console.log(green(`Vetra Connect: http://localhost:${connectPort}`));
|
|
549
562
|
const customViteLogger = createViteLogger(green);
|
|
550
|
-
const publicBase = args.drivesPublicBase;
|
|
551
|
-
const browserDriveUrl = publicBase ? rebaseDriveUrl(driveUrl, publicBase) : driveUrl;
|
|
552
|
-
const browserPreviewDriveUrl = previewDriveUrl && publicBase ? rebaseDriveUrl(previewDriveUrl, publicBase) : previewDriveUrl;
|
|
553
563
|
const vetraDrivesOverride = { drives: {
|
|
554
|
-
defaultDrives:
|
|
564
|
+
defaultDrives: resolvedDefaultDrives,
|
|
555
565
|
preserveStrategy: "preserve-all"
|
|
556
566
|
} };
|
|
557
567
|
await runConnectStudio({
|
|
@@ -575,5 +585,5 @@ async function startVetra(args) {
|
|
|
575
585
|
//#endregion
|
|
576
586
|
export { startVetra };
|
|
577
587
|
|
|
578
|
-
//# sourceMappingURL=vetra-
|
|
579
|
-
//# debugId=
|
|
588
|
+
//# sourceMappingURL=vetra-DCD3t7Qh.mjs.map
|
|
589
|
+
//# debugId=3b8d15bb-6fbd-53fc-ad65-01cdd51a9f0b
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vetra-DCD3t7Qh.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/utils/vetra-runtime.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 fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n mcpUrl: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst RECORD_REL = path.join(\".ph\", \"vetra-runtime.json\");\nconst READY_TIMEOUT_MS = 2000;\n\nconst recordPath = (projectDir: string) => path.join(projectDir, RECORD_REL);\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearVetraRuntime(projectDir: string): void {\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n if (!isPidAlive(record.pid) || !(await isReady(record.switchboardPort))) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return { status: \"live\", record };\n}\n\nconst MCP_FILES = [\".mcp.json\", path.join(\".cursor\", \"mcp.json\")];\n\n/**\n * Point every generated MCP config at `port`, returning the files changed.\n *\n * An MCP client resolves these files at session start and cannot read the\n * project config or `.env`, so when an override moves the port the literal\n * has to be corrected on disk. Rewrites in place rather than regenerating,\n * so any other servers or hand-added keys survive.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n\n let parsed: { mcpServers?: Record<string, { url?: string }> };\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as typeof parsed;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (!server?.url) continue;\n\n const wanted = `http://localhost:${port}/mcp`;\n if (server.url === wanted) continue;\n\n server.url = wanted;\n fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\\n`);\n changed.push(rel);\n }\n return changed;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { join } from \"node:path\";\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, POWERHOUSE_CONFIG_FILE } from \"../utils.js\";\nimport { wasFlagExplicitlyPassed } from \"../utils/cli-connect-override.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { mergeDefaultDrives } from \"../utils/merge-default-drives.js\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPort,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.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 // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n const probe = await probeVetraRuntime(projectDir, projectName);\n\n if (probe.status === \"live\") {\n console.log();\n console.log(green(\"Vetra is already running for this project.\"));\n console.log(\n green(` ➜ Connect: http://localhost:${probe.record.connectPort}`),\n );\n console.log(\n green(\n ` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`,\n ),\n );\n console.log(\n `Stop that instance (pid ${probe.record.pid}) if you need to restart it.`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\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 // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, {\n pid: process.pid,\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,\n startedAt: new Date().toISOString(),\n });\n const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);\n process.on(\"exit\", releaseRuntimeRecord);\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n // An MCP client resolved `.mcp.json` before this process started and\n // cannot re-read it, so a drifted literal means the agent is pointed at\n // the wrong port — possibly another project's reactor. Correct the file\n // and say so plainly; we cannot fix the already-open client ourselves.\n const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);\n if (driftedMcpFiles.length > 0) {\n console.log(\n yellow(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${actualSwitchboardPort}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n ),\n );\n }\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 // --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\n // The resolved default-drive list: vetra's own drives first (the\n // Vetra drive and, in watch mode, the preview drive), then the\n // project's configured `connect.drives.defaultDrives` from\n // powerhouse.config.json (issue #3023). A drive vetra also starts is\n // listed only once. An explicit `--default-drives-url` is appended on\n // top of this list by buildStudioConnectOverride — it never replaces\n // the vetra drives.\n const vetraDriveEntries = [\n ...(browserDriveUrl\n ? [{ url: browserDriveUrl, name: null, icon: null }]\n : []),\n ...(browserPreviewDriveUrl\n ? [{ url: browserPreviewDriveUrl, name: null, icon: null }]\n : []),\n ];\n const configuredDefaultDrives =\n getConfig(join(projectDir, POWERHOUSE_CONFIG_FILE)).connect?.drives\n ?.defaultDrives ?? [];\n const resolvedDefaultDrives = mergeDefaultDrives(\n vetraDriveEntries,\n configuredDefaultDrives,\n );\n\n if (verbose) {\n console.log(\"Starting Connect...\");\n // Mirror buildStudioConnectOverride: an explicit\n // --default-drives-url is appended to the resolved list.\n const flagDefaultDrives = wasFlagExplicitlyPassed(\"default-drives-url\")\n ? parseDefaultDrivesUrl(args.defaultDrivesUrl ?? \"\")\n : [];\n const printedDefaultDrives = mergeDefaultDrives(\n resolvedDefaultDrives,\n flagDefaultDrives,\n );\n console.log(\n ` ➜ Connect will use default drives: ${printedDefaultDrives\n .map((d) => (\"url\" in d ? d.url : `local:${d.id}`))\n .join(\", \")}`,\n );\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 const vetraDrivesOverride = {\n drives: {\n defaultDrives: resolvedDefaultDrives,\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;A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AED,OAAI,SAAS;AACX,YAAQ,IAAI,sBAAsB;IAMlC,MAAM,uBAAuB,mBAC3B,uBAJwB,wBAAwB,qBAAqB,GACnE,sBAAsB,KAAK,oBAAoB,GAAG,GAClD,EAAE,CAIL;AACD,YAAQ,IACN,yCAAyC,qBACtC,KAAK,MAAO,SAAS,IAAI,EAAE,MAAM,SAAS,EAAE,KAAM,CAClD,KAAK,KAAK,GACd;;AAEH,WAAQ,KAAK;AACb,WAAQ,IAAI,MAAM,mCAAmC,cAAc,CAAC;GAEpE,MAAM,mBAAmB,iBAAiB,MAAM;GAQhD,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe;IACf,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":"3b8d15bb-6fbd-53fc-ad65-01cdd51a9f0b"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/ph-cli",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.21",
|
|
4
4
|
"description": "",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -23,15 +23,15 @@
|
|
|
23
23
|
"keywords": [],
|
|
24
24
|
"author": "",
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@powerhousedao/builder-tools": "6.2.3-dev.
|
|
27
|
-
"@powerhousedao/codegen": "6.2.3-dev.
|
|
28
|
-
"@powerhousedao/common": "6.2.3-dev.
|
|
29
|
-
"@powerhousedao/config": "6.2.3-dev.
|
|
30
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
31
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
32
|
-
"@powerhousedao/switchboard": "6.2.3-dev.
|
|
33
|
-
"@powerhousedao/vetra": "6.2.3-dev.
|
|
34
|
-
"@renown/sdk": "6.2.3-dev.
|
|
26
|
+
"@powerhousedao/builder-tools": "6.2.3-dev.21",
|
|
27
|
+
"@powerhousedao/codegen": "6.2.3-dev.21",
|
|
28
|
+
"@powerhousedao/common": "6.2.3-dev.21",
|
|
29
|
+
"@powerhousedao/config": "6.2.3-dev.21",
|
|
30
|
+
"@powerhousedao/reactor": "6.2.3-dev.21",
|
|
31
|
+
"@powerhousedao/shared": "6.2.3-dev.21",
|
|
32
|
+
"@powerhousedao/switchboard": "6.2.3-dev.21",
|
|
33
|
+
"@powerhousedao/vetra": "6.2.3-dev.21",
|
|
34
|
+
"@renown/sdk": "6.2.3-dev.21",
|
|
35
35
|
"@sentry/node-core": "^10.52.0",
|
|
36
36
|
"@tsdown/css": "0.21.1",
|
|
37
37
|
"ajv": "^8.18.0",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"change-case": "5.4.4",
|
|
40
40
|
"cmd-ts": "0.15.0",
|
|
41
41
|
"colorette": "2.0.20",
|
|
42
|
-
"document-model": "6.2.3-dev.
|
|
42
|
+
"document-model": "6.2.3-dev.21",
|
|
43
43
|
"enquirer": "2.4.1",
|
|
44
44
|
"kysely": "0.28.16",
|
|
45
45
|
"package-manager-detector": "1.6.0",
|
|
@@ -63,6 +63,7 @@
|
|
|
63
63
|
"scripts": {
|
|
64
64
|
"tsc": "tsc",
|
|
65
65
|
"lint": "eslint",
|
|
66
|
+
"test": "vitest --run",
|
|
66
67
|
"generate-docs": "bun run scripts/generate-commands-docs.ts",
|
|
67
68
|
"build": "tsdown",
|
|
68
69
|
"postbuild": "bun generate-docs && bun copy-scripts",
|
package/dist/build-C-A5-ipO.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { n as runBuild } from "./build-uQXq6_HU.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]="07cbb8f4-54b7-5333-be22-8ce017cd9e53")}catch(e){}}();
|
|
4
|
-
//# debugId=07cbb8f4-54b7-5333-be22-8ce017cd9e53
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-uQXq6_HU.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 { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport type { BuildArgs } from \"../types.js\";\n\n/**\n * A Powerhouse package's `powerhouse.manifest.json` \"name\" must match its\n * `package.json` \"name\" — Connect and the registry resolve installed versions\n * by treating the manifest name as the npm package name, so a mismatch silently\n * breaks resolution. Fail the build early if they diverge. No-op when the\n * project has no manifest (nothing to compare).\n */\nexport async function assertManifestNameMatchesPackage(projectPath: string) {\n const manifestPath = join(projectPath, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n\n const { name: packageName } = await readPackage({ cwd: projectPath });\n\n let manifestName: unknown;\n try {\n manifestName = (\n JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { name?: unknown }\n ).name;\n } catch {\n throw new Error(\n `Failed to parse \"powerhouse.manifest.json\" at ${manifestPath}. Make sure it is valid JSON.`,\n );\n }\n\n if (manifestName !== packageName) {\n throw new Error(\n `Package name mismatch — \"package.json\" and \"powerhouse.manifest.json\" must have the same \"name\":\\n` +\n ` package.json \"name\": ${JSON.stringify(packageName)}\\n` +\n ` powerhouse.manifest.json \"name\": ${JSON.stringify(manifestName)}\\n\\n` +\n `Update one so they match, then run the build again.`,\n );\n }\n}\n\nexport async function runBuild(args: BuildArgs) {\n const { outDir } = args;\n\n // Fail fast if the manifest name and package.json name have drifted apart.\n await assertManifestNameMatchesPackage(process.cwd());\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":";;;;;;;;;;;;;;;;;AAmBA,eAAsB,iCAAiC,aAAqB;CAC1E,MAAM,eAAe,KAAK,aAAa,2BAA2B;AAClE,KAAI,CAAC,WAAW,aAAa,CAAE;CAE/B,MAAM,EAAE,MAAM,gBAAgB,MAAM,YAAY,EAAE,KAAK,aAAa,CAAC;CAErE,IAAI;AACJ,KAAI;AACF,iBACE,KAAK,MAAM,aAAa,cAAc,QAAQ,CAAC,CAC/C;SACI;AACN,QAAM,IAAI,MACR,iDAAiD,aAAa,+BAC/D;;AAGH,KAAI,iBAAiB,YACnB,OAAM,IAAI,MACR,wIACwC,KAAK,UAAU,YAAY,CAAC,uCAC5B,KAAK,UAAU,aAAa,CAAC,yDAEtE;;AAIL,eAAsB,SAAS,MAAiB;CAC9C,MAAM,EAAE,WAAW;AAGnB,OAAM,iCAAiC,QAAQ,KAAK,CAAC;AAErD,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":"a81d56d6-7b6c-5288-ac91-899d56570def"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli-connect-override-D3hh4aH_.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 renownSwitchboardUrl?: 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 setIfDefined(renown, \"switchboardUrl\", args.renownSwitchboardUrl);\n if (Object.keys(renown).length > 0) out.renown = renown;\n\n const packages: PlainObject = {};\n setIfDefined(packages, \"externalEnabled\", args.externalPackages);\n if (Object.keys(packages).length > 0) out.packages = packages;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option).\n const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (args.homeBackground !== undefined) {\n branding.homeBackground =\n args.homeBackground === \"\" ? null : args.homeBackground;\n }\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --sentry-dsn: empty string is the explicit \"set null\" form (disables\n // Sentry). Same pattern as --home-background.\n const sentry: PlainObject = {};\n if (args.sentryDsn !== undefined) {\n sentry.dsn = args.sentryDsn === \"\" ? null : args.sentryDsn;\n }\n setIfDefined(sentry, \"env\", args.sentryEnv);\n setIfDefined(sentry, \"tracing\", args.sentryTracingEnabled);\n if (Object.keys(sentry).length > 0) out.sentry = sentry;\n\n const drives: PlainObject = {};\n setIfDefined(drives, \"allowAddDrive\", args.allowAddDrive);\n setIfDefined(drives, \"preserveStrategy\", args.drivesPreserveStrategy);\n if (args.defaultDrivesUrl !== undefined && args.defaultDrivesUrl !== \"\") {\n drives.defaultDrives = parseDefaultDrivesUrl(args.defaultDrivesUrl);\n }\n\n const remote: PlainObject = {};\n setIfDefined(remote, \"enabled\", args.remoteDrivesEnabled);\n setIfDefined(remote, \"allowAdd\", args.remoteDrivesAllowAdd);\n setIfDefined(remote, \"allowDelete\", args.remoteDrivesAllowDelete);\n\n const local: PlainObject = {};\n setIfDefined(local, \"enabled\", args.localDrivesEnabled);\n setIfDefined(local, \"allowAdd\", args.localDrivesAllowAdd);\n setIfDefined(local, \"allowDelete\", args.localDrivesAllowDelete);\n\n const sections: PlainObject = {};\n if (Object.keys(remote).length > 0) sections.remote = remote;\n if (Object.keys(local).length > 0) sections.local = local;\n if (Object.keys(sections).length > 0) drives.sections = sections;\n if (Object.keys(drives).length > 0) out.drives = drives;\n\n return out;\n}\n\n/**\n * Combine `--json` and the individual flag values into the two override\n * inputs `ph connect build` forwards to the Vite plugin:\n *\n * - `connectOverride`: a partial `connect.*` patch (deep-merged at the top\n * of the runtime-config precedence ladder).\n * - `packageRegistryUrl`: a separate top-level override; mirrors the\n * source-config top-level field (the SPA reads it directly).\n *\n * `--packages-registry` and `--json` containing a top-level\n * `packageRegistryUrl` both flow into `packageRegistryUrl`; the flag wins on\n * collision. Returns `undefined` for whichever override was not supplied.\n *\n * The 4 commonArgs flags (`--base`, `--log-level`, `--default-drives-url`,\n * `--drive-preserve-strategy`) are gated through `wasFlagExplicitlyPassed`\n * because they carry cmd-ts defaults that would otherwise leak into the\n * override on every build.\n */\nexport function buildCliConnectOverride(args: ConnectBuildArgs): {\n connectOverride: PHConnectRuntimeConfig | undefined;\n packageRegistryUrl: string | undefined;\n} {\n const fromJson = parseJsonOverride(args.json);\n\n const input: ConnectFlagInput = {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\n renownNamespace: args.renownNamespace,\n renownSwitchboardUrl: args.renownSwitchboardUrl,\n allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\n 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) => deepMerge(acc, o), {} as PHConnectRuntimeConfig);\n}\n"],"names":[],"mappings":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A,QAAQ,KAAK,MAAM,UAAU,KAAK,EAAE,EAAE,EAAE,CAA2B","debug_id":"1cfb2ec9-21ac-545a-a4fa-c392fd478bc4"}
|
|
@@ -1,43 +0,0 @@
|
|
|
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]="c94ac33b-8632-5676-a303-70e76012eaa6")}catch(e){}}();
|
|
3
|
-
import { n as runBuild } from "./build-uQXq6_HU.mjs";
|
|
4
|
-
import { t as buildCliConnectOverride } from "./cli-connect-override-D3hh4aH_.mjs";
|
|
5
|
-
import { existsSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
7
|
-
import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
|
|
8
|
-
import { getConfig } from "@powerhousedao/shared/clis";
|
|
9
|
-
import { build, mergeConfig } from "vite";
|
|
10
|
-
//#region src/services/connect-build.ts
|
|
11
|
-
async function runConnectBuild(args) {
|
|
12
|
-
const { outDir, debug, dynamicBase, favicon } = args;
|
|
13
|
-
const mode = "production";
|
|
14
|
-
const dirname = process.cwd();
|
|
15
|
-
if (args.keyPositional !== void 0 && args.valuePositional === void 0) throw new Error("ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.");
|
|
16
|
-
assertLocalPackagesInstalled(dirname);
|
|
17
|
-
const { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);
|
|
18
|
-
await runBuild({
|
|
19
|
-
outDir: "dist",
|
|
20
|
-
debug
|
|
21
|
-
});
|
|
22
|
-
await build(mergeConfig(getConnectBaseViteConfig({
|
|
23
|
-
mode,
|
|
24
|
-
dirname,
|
|
25
|
-
cliConnectOverride: connectOverride,
|
|
26
|
-
cliPackageRegistryUrl: packageRegistryUrl,
|
|
27
|
-
dynamicBase,
|
|
28
|
-
favicon
|
|
29
|
-
}), { build: { outDir } }));
|
|
30
|
-
}
|
|
31
|
-
function assertLocalPackagesInstalled(projectPath) {
|
|
32
|
-
const localPackages = (getConfig(join(projectPath, "powerhouse.config.json")).packages ?? []).filter((p) => p.provider === "local");
|
|
33
|
-
if (localPackages.length === 0) return;
|
|
34
|
-
const missing = localPackages.filter((p) => !existsSync(join(projectPath, "node_modules", p.packageName, "package.json")));
|
|
35
|
-
if (missing.length === 0) return;
|
|
36
|
-
const names = missing.map((p) => p.packageName);
|
|
37
|
-
throw new Error(`ph connect build requires these packages to be installed in node_modules (they are declared with provider: "local" in powerhouse.config.json):\n` + names.map((n) => ` - ${n}`).join("\n") + `\n\nInstall them with:\n ph install --local ${names.join(" ")}`);
|
|
38
|
-
}
|
|
39
|
-
//#endregion
|
|
40
|
-
export { runConnectBuild };
|
|
41
|
-
|
|
42
|
-
//# sourceMappingURL=connect-build-WL4axo4z.mjs.map
|
|
43
|
-
//# debugId=c94ac33b-8632-5676-a303-70e76012eaa6
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect-build-WL4axo4z.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\n\n await runBuild({\n outDir: \"dist\",\n debug,\n });\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AAUA,eAAsB,gBAAgB,MAAwB;CAC5D,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,KAAK;AAK7B,KAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,EAC/D,OAAM,IAAI,MACR,6LACD;AAKH,8BAA6B,QAAQ;CAOrC,MAAM,EAAE,iBAAiB,uBAAuB,wBAAwB,KAAK;AAE7E,OAAM,SAAS;EACb,QAAQ;EACR;EACD,CAAC;AAmBF,OAAM,MAFS,YAfI,yBAAyB;EAC1C;EACA;EACA,oBAAoB;EACpB,uBAAuB;EACvB;EACA;EACD,CAAC,EAEgC,EAChC,OAAO,EACL,QACD,EACF,CAEkD,CAEhC;;AAGrB,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,yBAAyB,CAAC,CACvC,YAAY,EAAE,EAAE,QAC3C,MAAM,EAAE,aAAa,QACvB;AACD,KAAI,cAAc,WAAW,EAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,eAAe,CACjE,CACJ;AACD,KAAI,QAAQ,WAAW,EAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,YAAY;AAC/C,OAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,KAAK,GACvC,gDAAgD,MAAM,KAAK,IAAI,GAClE","debug_id":"c94ac33b-8632-5676-a303-70e76012eaa6"}
|