@powerhousedao/ph-cli 6.2.3-dev.8 → 6.2.3-dev.81
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/{auth-AR3VxAIk.mjs → auth-BFUq7CvE.mjs} +3 -3
- package/dist/{auth-AR3VxAIk.mjs.map → auth-BFUq7CvE.mjs.map} +1 -1
- package/dist/auth-CNhbN5UM.mjs +4 -0
- package/dist/build-t5pFQx0f.mjs +304 -0
- package/dist/build-t5pFQx0f.mjs.map +1 -0
- package/dist/build-wvc_NiGr.mjs +4 -0
- package/dist/check-ecwBLzrg.mjs +56 -0
- package/dist/check-ecwBLzrg.mjs.map +1 -0
- package/dist/{cli-connect-override-D3hh4aH_.mjs → cli-connect-override-DW7OYAGx.mjs} +39 -27
- package/dist/cli-connect-override-DW7OYAGx.mjs.map +1 -0
- package/dist/cli.d.mts +2 -1
- package/dist/cli.mjs +35 -1179
- package/dist/cli.mjs.map +1 -1
- package/dist/compound-C7GuPnTP-Ba4ce2Xa.mjs +2813 -0
- package/dist/compound-C7GuPnTP-Ba4ce2Xa.mjs.map +1 -0
- package/dist/connect-build-7nmQw9c5.mjs +253 -0
- package/dist/connect-build-7nmQw9c5.mjs.map +1 -0
- package/dist/{connect-config-BWGiW3IB.mjs → connect-config-CfQwxG8G.mjs} +19 -12
- package/dist/connect-config-CfQwxG8G.mjs.map +1 -0
- package/dist/connect-plugin-configs-CXN8_KL0.mjs +50 -0
- package/dist/connect-plugin-configs-CXN8_KL0.mjs.map +1 -0
- package/dist/connect-preview-Ckoqw_XU.mjs +231 -0
- package/dist/connect-preview-Ckoqw_XU.mjs.map +1 -0
- package/dist/connect-studio-Cac3eE_U.mjs +81 -0
- package/dist/connect-studio-Cac3eE_U.mjs.map +1 -0
- package/dist/connect-studio-Cf6UZvOo.mjs +4 -0
- package/dist/dist-DcARVrSg.mjs +643 -0
- package/dist/dist-DcARVrSg.mjs.map +1 -0
- package/dist/explain-Rx7JW1OU.mjs +230 -0
- package/dist/explain-Rx7JW1OU.mjs.map +1 -0
- package/dist/export-ZnJeAtLS.mjs +42 -0
- package/dist/export-ZnJeAtLS.mjs.map +1 -0
- package/dist/feature-flags-xwqcHEWC.mjs +4 -0
- package/dist/{generate-all-DrT4ZxHX.mjs → generate-all-5Om0CB4N.mjs} +9 -3
- package/dist/generate-all-5Om0CB4N.mjs.map +1 -0
- package/dist/generate-app-hm6CJ_4O.mjs +72 -0
- package/dist/generate-app-hm6CJ_4O.mjs.map +1 -0
- package/dist/generate-desktop-shell-DzEzNspp.mjs +318 -0
- package/dist/generate-desktop-shell-DzEzNspp.mjs.map +1 -0
- package/dist/generate-document-model-CiW13Vf7.mjs +60 -0
- package/dist/generate-document-model-CiW13Vf7.mjs.map +1 -0
- package/dist/generate-editor-kTiUOmDW.mjs +64 -0
- package/dist/generate-editor-kTiUOmDW.mjs.map +1 -0
- package/dist/generate-hosts-BFmPIW2X.mjs +18 -0
- package/dist/generate-hosts-BFmPIW2X.mjs.map +1 -0
- package/dist/generate-hosts-RWj7WPHZ.mjs +4 -0
- package/dist/generate-migration-file-yK8uA70U.mjs +20 -0
- package/dist/generate-migration-file-yK8uA70U.mjs.map +1 -0
- package/dist/generate-piece-C6ymlErL.mjs +73 -0
- package/dist/generate-piece-C6ymlErL.mjs.map +1 -0
- package/dist/generate-piece-action-DqR8BcoO.mjs +31 -0
- package/dist/generate-piece-action-DqR8BcoO.mjs.map +1 -0
- package/dist/generate-piece-trigger-CZaDD-cc.mjs +30 -0
- package/dist/generate-piece-trigger-CZaDD-cc.mjs.map +1 -0
- package/dist/generate-processor-BVjOsfjJ.mjs +58 -0
- package/dist/generate-processor-BVjOsfjJ.mjs.map +1 -0
- package/dist/generate-subgraph-CrHbYK91.mjs +64 -0
- package/dist/generate-subgraph-CrHbYK91.mjs.map +1 -0
- package/dist/get-version-CJulKHJ0.mjs +11 -0
- package/dist/get-version-CJulKHJ0.mjs.map +1 -0
- package/dist/index-CJN_BRkc.d.mts +4459 -0
- package/dist/index-CJN_BRkc.d.mts.map +1 -0
- package/dist/{init-BZP6gvYd.mjs → init-Ch1rCksS.mjs} +16 -12
- package/dist/init-Ch1rCksS.mjs.map +1 -0
- package/dist/{inspect-DXjbQEV_.mjs → inspect-zWJnBDMJ.mjs} +11 -4
- package/dist/inspect-zWJnBDMJ.mjs.map +1 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs +18 -0
- package/dist/install-added-dependencies-DnZFR3aE.mjs.map +1 -0
- package/dist/mcp-Cz9CubZa.mjs +262 -0
- package/dist/mcp-Cz9CubZa.mjs.map +1 -0
- package/dist/member-config-0tHtiVN_.mjs +154 -0
- package/dist/member-config-0tHtiVN_.mjs.map +1 -0
- package/dist/migrate-CIJaE3iZ.mjs +177 -0
- package/dist/migrate-CIJaE3iZ.mjs.map +1 -0
- package/dist/module-dir-1avCXsBi.mjs +17 -0
- package/dist/module-dir-1avCXsBi.mjs.map +1 -0
- package/dist/offered-routes-imports-CQInWI6y.mjs +4 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs +96 -0
- package/dist/offered-routes-imports-CalXK9dh.mjs.map +1 -0
- package/dist/ph-cli-commands-C4gwBRyw.mjs +4 -0
- package/dist/ph-cli-commands-DFmTGL-H.mjs +1610 -0
- package/dist/ph-cli-commands-DFmTGL-H.mjs.map +1 -0
- package/dist/precompress-P6cJDPVC.mjs +77 -0
- package/dist/precompress-P6cJDPVC.mjs.map +1 -0
- package/dist/{registry-auth-DxEWCJu2.mjs → registry-auth-Bm5AR-fB.mjs} +4 -4
- package/dist/{registry-auth-DxEWCJu2.mjs.map → registry-auth-Bm5AR-fB.mjs.map} +1 -1
- package/dist/run-sugar-CRzZsmVo.mjs +39 -0
- package/dist/run-sugar-CRzZsmVo.mjs.map +1 -0
- package/dist/runners/connect.d.mts +1153 -0
- package/dist/runners/connect.d.mts.map +1 -0
- package/dist/runners/connect.mjs +300 -0
- package/dist/runners/connect.mjs.map +1 -0
- package/dist/runners/switchboard.d.mts +1481 -0
- package/dist/runners/switchboard.d.mts.map +1 -0
- package/dist/runners/switchboard.mjs +550 -0
- package/dist/runners/switchboard.mjs.map +1 -0
- package/dist/schemas-ByfuhvAb.mjs +5752 -0
- package/dist/schemas-ByfuhvAb.mjs.map +1 -0
- package/dist/scripts/emit-runner-schemas.ts +24 -0
- package/dist/scripts/generate-commands-docs.ts +12 -0
- package/dist/scripts/manage-environment +0 -0
- package/dist/scripts/setup.sh +0 -0
- package/dist/start-run-CRVBqQ8L.mjs +124 -0
- package/dist/start-run-CRVBqQ8L.mjs.map +1 -0
- package/dist/superseded-config-CbSTFun2.mjs +53 -0
- package/dist/superseded-config-CbSTFun2.mjs.map +1 -0
- package/dist/switchboard-B7mvNWcd.mjs +4 -0
- package/dist/switchboard-Cqs5IBNF.mjs +168 -0
- package/dist/switchboard-Cqs5IBNF.mjs.map +1 -0
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs → switchboard-migrate-Docb8Cjv.mjs} +6 -5
- package/dist/{switchboard-migrate-NQ7LHWSi.mjs.map → switchboard-migrate-Docb8Cjv.mjs.map} +1 -1
- package/dist/switchboard-proxy-CGfMtENM.mjs +37 -0
- package/dist/switchboard-proxy-CGfMtENM.mjs.map +1 -0
- package/dist/{switchboard-reset-BcQXlcVf.mjs → switchboard-reset-MtTB_GAI.mjs} +8 -6
- package/dist/switchboard-reset-MtTB_GAI.mjs.map +1 -0
- package/dist/sync-connect-routes-BtAsFPXN.mjs +4 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs +25 -0
- package/dist/sync-connect-routes-t0Slg-P6.mjs.map +1 -0
- package/dist/{utils-C4isxXSO.mjs → utils-9KyRM0mf.mjs} +6 -34
- package/dist/{utils-C4isxXSO.mjs.map → utils-9KyRM0mf.mjs.map} +1 -1
- package/dist/utils-DAux4Ga7.mjs +4 -0
- package/dist/{vetra-DkF6EJMY.mjs → vetra-DZYtcHqV.mjs} +130 -147
- package/dist/vetra-DZYtcHqV.mjs.map +1 -0
- package/dist/vetra-launch-DQDZxGTV.mjs +343 -0
- package/dist/vetra-launch-DQDZxGTV.mjs.map +1 -0
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +19 -0
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +1 -0
- package/package.json +42 -18
- package/dist/auth-BNkN6kS9.mjs +0 -4
- package/dist/build-C-A5-ipO.mjs +0 -4
- package/dist/build-uQXq6_HU.mjs +0 -71
- 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-preview-D7ypzFDc.mjs +0 -28
- package/dist/connect-preview-D7ypzFDc.mjs.map +0 -1
- package/dist/connect-studio-BIQzyq5B.mjs +0 -5
- package/dist/connect-studio-D6rfWCNB.mjs +0 -31
- package/dist/connect-studio-D6rfWCNB.mjs.map +0 -1
- package/dist/generate-all-DrT4ZxHX.mjs.map +0 -1
- package/dist/generate-app-DNNqA-H3.mjs +0 -48
- package/dist/generate-app-DNNqA-H3.mjs.map +0 -1
- package/dist/generate-document-model-BJXyODfm.mjs +0 -34
- package/dist/generate-document-model-BJXyODfm.mjs.map +0 -1
- package/dist/generate-editor-BejvaVVT.mjs +0 -48
- package/dist/generate-editor-BejvaVVT.mjs.map +0 -1
- package/dist/generate-processor-_WOx-mMe.mjs +0 -40
- package/dist/generate-processor-_WOx-mMe.mjs.map +0 -1
- package/dist/generate-subgraph-BsHUstpl.mjs +0 -38
- package/dist/generate-subgraph-BsHUstpl.mjs.map +0 -1
- package/dist/init-BZP6gvYd.mjs.map +0 -1
- package/dist/inspect-DXjbQEV_.mjs.map +0 -1
- package/dist/migrate-jGKfE02L.mjs +0 -83
- package/dist/migrate-jGKfE02L.mjs.map +0 -1
- package/dist/switchboard-CJMoMzWx.mjs +0 -75
- package/dist/switchboard-CJMoMzWx.mjs.map +0 -1
- package/dist/switchboard-iRFugh8I.mjs +0 -4
- package/dist/switchboard-reset-BcQXlcVf.mjs.map +0 -1
- package/dist/utils-BzwczAW-.mjs +0 -4
- package/dist/vetra-DkF6EJMY.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-Cz9CubZa.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n currentPhCliVetraCommand,\n ensureVetra,\n restartVetra,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to this ph-cli's `vetra`. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? currentPhCliVetraCommand(),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuCA,MAAM,kBAAk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SAAS;IACnC;GACF;GACA,MACG,iBAAiB;IAChB,QAAQ;IACR,QAAQ;KAAE,eAAe;KAAO,UAAU,EAAE;KAAU;IAAQ;GAChE,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EACnB;EACA,IAAI;GACF,IAAI,QAAQ,OAAO,SAAA,gBAA6B;IAC9C,MAAM,OAAO,UAAU,MAAM,SAAS,QAAQ,UAAU,CAAC;IACzD,OAAO;KACL,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"fd2c2d3a-6588-5c71-8571-69b7fadc671c"}
|
|
@@ -0,0 +1,154 @@
|
|
|
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]="aace5880-83b0-57a2-a55e-eaf0fe6c890a")}catch(e){}}();
|
|
3
|
+
import { c as primaryBackend, f as protocolEnv, p as reactorBlockToSwitchboardConfig, t as assertProtocolConsistency } from "./dist-DcARVrSg.mjs";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { mergeSwitchboardConfig, switchboardConfigLayerSchema } from "@powerhousedao/switchboard/config";
|
|
7
|
+
import { envNamesBeforeProjectEnv, isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
|
|
8
|
+
import dotenv from "dotenv";
|
|
9
|
+
//#region src/runners/member-config.ts
|
|
10
|
+
function readDotenv(cwd) {
|
|
11
|
+
try {
|
|
12
|
+
return dotenv.parse(fs.readFileSync(path.join(cwd, ".env")));
|
|
13
|
+
} catch {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const shellNamesByEnv = /* @__PURE__ */ new WeakMap();
|
|
18
|
+
/** Records which names of `env` the shell set, before a `.env` loads into it. */
|
|
19
|
+
function rememberShellNames(env, names) {
|
|
20
|
+
shellNamesByEnv.set(env, new Set(names));
|
|
21
|
+
}
|
|
22
|
+
function shellNamesOf(env) {
|
|
23
|
+
let names = shellNamesByEnv.get(env);
|
|
24
|
+
if (!names) {
|
|
25
|
+
names = (env === process.env ? envNamesBeforeProjectEnv() : void 0) ?? new Set(Object.keys(env));
|
|
26
|
+
shellNamesByEnv.set(env, names);
|
|
27
|
+
}
|
|
28
|
+
return names;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Splits `env` into the shell's values and the `.env` the switchboard server
|
|
32
|
+
* loads from `cwd` (the same file). A name the shell set stays the shell's,
|
|
33
|
+
* whatever the file says.
|
|
34
|
+
*/
|
|
35
|
+
function memberEnvOf(env, cwd = process.cwd()) {
|
|
36
|
+
const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);
|
|
37
|
+
const shellNames = shellNamesOf(env);
|
|
38
|
+
const shell = {};
|
|
39
|
+
for (const [name, value] of Object.entries(env)) if (file[name] === void 0 || shellNames.has(name)) shell[name] = value;
|
|
40
|
+
const fromFile = {};
|
|
41
|
+
for (const [name, value] of Object.entries(file)) if (!shellNames.has(name)) fromFile[name] = value;
|
|
42
|
+
return {
|
|
43
|
+
shell,
|
|
44
|
+
dotenv: fromFile
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The env vars the block sets, which a `.env` value does not override. */
|
|
48
|
+
function blockEnvNames(reactor) {
|
|
49
|
+
const block = reactorBlockToSwitchboardConfig(reactor);
|
|
50
|
+
return [
|
|
51
|
+
...Object.keys(protocolEnv(reactor?.protocol)),
|
|
52
|
+
...block.packages?.dynamic ? ["DYNAMIC_MODEL_LOADING"] : [],
|
|
53
|
+
...block.features ? ["PH_WORKFLOWS_ENABLED"] : []
|
|
54
|
+
];
|
|
55
|
+
}
|
|
56
|
+
/** `config.switchboard`: a member's own switchboard config. The omitted keys
|
|
57
|
+
* live in the reactor block (storage, protocol, dynamic packages) or the
|
|
58
|
+
* runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */
|
|
59
|
+
const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([
|
|
60
|
+
"logLevel",
|
|
61
|
+
"server.port",
|
|
62
|
+
"server.dev",
|
|
63
|
+
"storage.reactor",
|
|
64
|
+
"storage.readModel",
|
|
65
|
+
"protocol",
|
|
66
|
+
"packages.dynamic",
|
|
67
|
+
"drive",
|
|
68
|
+
"remoteDrives",
|
|
69
|
+
"features.pluginHost",
|
|
70
|
+
"processorConfig"
|
|
71
|
+
]);
|
|
72
|
+
function isPlainObject(value) {
|
|
73
|
+
return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
|
|
74
|
+
}
|
|
75
|
+
/** The dotted keys both layers set. */
|
|
76
|
+
function overlappingKeys(a, b, path = "") {
|
|
77
|
+
return Object.entries(b).flatMap(([key, value]) => {
|
|
78
|
+
const other = a[key];
|
|
79
|
+
if (value === void 0 || other === void 0) return [];
|
|
80
|
+
const at = path ? `${path}.${key}` : key;
|
|
81
|
+
return isPlainObject(value) && isPlainObject(other) ? overlappingKeys(other, value, at) : [at];
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Each `config.switchboard` key the reactor block already sets. */
|
|
85
|
+
function reactorBlockConflicts(member) {
|
|
86
|
+
const own = member.config?.switchboard;
|
|
87
|
+
if (!own) return [];
|
|
88
|
+
return overlappingKeys(reactorBlockToSwitchboardConfig(member.reactor), own).map((key) => `config.switchboard.${key} is also set by the reactor block; set it in one place.`);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The deprecation notice for a block whose `readModel.url` still names the
|
|
92
|
+
* reactor store too: nothing else names the store, as it did when
|
|
93
|
+
* readModel.url rode `dbPath`.
|
|
94
|
+
*/
|
|
95
|
+
function readModelAsReactorStore(reactor, env, hostFileLabel) {
|
|
96
|
+
const storage = reactorBlockToSwitchboardConfig(reactor).storage;
|
|
97
|
+
const url = storage?.readModel?.url;
|
|
98
|
+
if (!url || storage.reactor || env.PH_REACTOR_DATABASE_URL !== void 0 || env.PH_SWITCHBOARD_DATABASE_URL !== void 0) return;
|
|
99
|
+
return {
|
|
100
|
+
url,
|
|
101
|
+
warning: `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).`
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The member's switchboard config under the runner's own arguments: its
|
|
106
|
+
* reactor block, then `config.switchboard`, then the env over both, mapped
|
|
107
|
+
* once as the server read it (the shell over the `.env`, whose values for the
|
|
108
|
+
* block's own vars are dropped). The block keeps the precedence it had as
|
|
109
|
+
* set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL
|
|
110
|
+
* overrides its store, and no env var overrides its read model. Writes nothing.
|
|
111
|
+
*/
|
|
112
|
+
async function memberSwitchboardConfig(member, env, options) {
|
|
113
|
+
const { switchboardConfigFromEnv } = await import("@powerhousedao/switchboard/config/env");
|
|
114
|
+
const block = reactorBlockToSwitchboardConfig(member.reactor);
|
|
115
|
+
const legacy = readModelAsReactorStore(member.reactor, env.shell, "");
|
|
116
|
+
if (legacy) block.storage = {
|
|
117
|
+
...block.storage,
|
|
118
|
+
reactor: { url: legacy.url }
|
|
119
|
+
};
|
|
120
|
+
const dotenvValues = { ...env.dotenv };
|
|
121
|
+
for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];
|
|
122
|
+
const fromEnv = switchboardConfigFromEnv({
|
|
123
|
+
...dotenvValues,
|
|
124
|
+
...env.shell
|
|
125
|
+
}, { logger: options.logger });
|
|
126
|
+
const storage = { ...fromEnv.storage };
|
|
127
|
+
if (block.storage?.reactor && env.shell.PH_REACTOR_DATABASE_URL === void 0) delete storage.reactor;
|
|
128
|
+
if (block.storage?.readModel) delete storage.readModel;
|
|
129
|
+
return mergeSwitchboardConfig(options.defaults ?? {}, block, member.config?.switchboard ?? {}, {
|
|
130
|
+
...fromEnv,
|
|
131
|
+
storage
|
|
132
|
+
}, options.pluginHost ? { features: { pluginHost: true } } : {});
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Fails when the operator's env contradicts the member's protocol block, then
|
|
136
|
+
* creates the block's path-storage dir (the server's own mkdir is not
|
|
137
|
+
* recursive).
|
|
138
|
+
*/
|
|
139
|
+
function prepareMemberStorage(reactor, env, hostFileLabel) {
|
|
140
|
+
assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);
|
|
141
|
+
const storage = primaryBackend(reactor)?.storage;
|
|
142
|
+
if (storage?.kind !== "path" || !storage.dataDir) return;
|
|
143
|
+
if (/\$\{(userData|projectRoot)\}/.test(storage.dataDir)) throw new Error(`${hostFileLabel}: storage.dataDir "${storage.dataDir}" was not resolved; resolve the host (resolveHostOutputs) before starting it.`);
|
|
144
|
+
fs.mkdirSync(storage.dataDir, { recursive: true });
|
|
145
|
+
}
|
|
146
|
+
/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */
|
|
147
|
+
function switchboardDevMode(devVerb, runner) {
|
|
148
|
+
return devVerb || runner.dev === true;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
export { reactorBlockConflicts as a, switchboardDevMode as c, prepareMemberStorage as i, memberSwitchboardConfig as n, readModelAsReactorStore as o, memberSwitchboardConfigSchema as r, rememberShellNames as s, memberEnvOf as t };
|
|
152
|
+
|
|
153
|
+
//# sourceMappingURL=member-config-0tHtiVN_.mjs.map
|
|
154
|
+
//# debugId=aace5880-83b0-57a2-a55e-eaf0fe6c890a
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"member-config-0tHtiVN_.mjs","sources":["../src/runners/member-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n assertProtocolConsistency,\n primaryBackend,\n protocolEnv,\n reactorBlockToSwitchboardConfig,\n type ReactorConfig,\n} from \"@powerhousedao/host-core\";\nimport {\n mergeSwitchboardConfig,\n switchboardConfigLayerSchema,\n type SwitchboardConfigInput,\n} from \"@powerhousedao/switchboard/config\";\nimport {\n envNamesBeforeProjectEnv,\n isDotenvDisabled,\n} from \"@powerhousedao/shared/clis/project-env\";\nimport type { ILogger } from \"document-model\";\nimport dotenv from \"dotenv\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** The operator's env, split by where each value came from. */\nexport interface MemberEnv {\n /** Set by the shell: wins over the host file. */\n shell: Env;\n /** Only in the project `.env`: the host file's keys win over these. */\n dotenv: Env;\n}\n\n// The server's dotenv.config() ignores a file it cannot read.\nfunction readDotenv(cwd: string): Record<string, string> {\n try {\n return dotenv.parse(fs.readFileSync(path.join(cwd, \".env\")));\n } catch {\n return {};\n }\n}\n\nconst shellNamesByEnv = new WeakMap<object, ReadonlySet<string>>();\n\n/** Records which names of `env` the shell set, before a `.env` loads into it. */\nexport function rememberShellNames(env: Env, names: Iterable<string>): void {\n shellNamesByEnv.set(env, new Set(names));\n}\n\n// Taken the first time an env is seen: before the first member's server\n// import loads the .env into it, and reused for every later member.\nfunction shellNamesOf(env: Env): ReadonlySet<string> {\n let names = shellNamesByEnv.get(env);\n if (!names) {\n names =\n (env === process.env ? envNamesBeforeProjectEnv() : undefined) ??\n new Set(Object.keys(env));\n shellNamesByEnv.set(env, names);\n }\n return names;\n}\n\n/**\n * Splits `env` into the shell's values and the `.env` the switchboard server\n * loads from `cwd` (the same file). A name the shell set stays the shell's,\n * whatever the file says.\n */\nexport function memberEnvOf(env: Env, cwd: string = process.cwd()): MemberEnv {\n const file = isDotenvDisabled({ ...env }) ? {} : readDotenv(cwd);\n const shellNames = shellNamesOf(env);\n const shell: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (file[name] === undefined || shellNames.has(name)) shell[name] = value;\n }\n const fromFile: Record<string, string> = {};\n for (const [name, value] of Object.entries(file)) {\n if (!shellNames.has(name)) fromFile[name] = value;\n }\n return { shell, dotenv: fromFile };\n}\n\n/** The env vars the block sets, which a `.env` value does not override. */\nfunction blockEnvNames(reactor: ReactorConfig | undefined): string[] {\n const block = reactorBlockToSwitchboardConfig(reactor);\n return [\n ...Object.keys(protocolEnv(reactor?.protocol)),\n ...(block.packages?.dynamic ? [\"DYNAMIC_MODEL_LOADING\"] : []),\n ...(block.features ? [\"PH_WORKFLOWS_ENABLED\"] : []),\n ];\n}\n\n/** `config.switchboard`: a member's own switchboard config. The omitted keys\n * live in the reactor block (storage, protocol, dynamic packages) or the\n * runner (port, dev verb, drives, plugins), or are process-wide or not JSON. */\nexport const memberSwitchboardConfigSchema = switchboardConfigLayerSchema([\n \"logLevel\",\n \"server.port\",\n \"server.dev\",\n \"storage.reactor\",\n \"storage.readModel\",\n \"protocol\",\n \"packages.dynamic\",\n \"drive\",\n \"remoteDrives\",\n \"features.pluginHost\",\n \"processorConfig\",\n]);\n\nexport interface SwitchboardMember {\n reactor?: ReactorConfig;\n config?: { switchboard?: SwitchboardConfigInput };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** The dotted keys both layers set. */\nexport function overlappingKeys(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n path = \"\",\n): string[] {\n return Object.entries(b).flatMap(([key, value]) => {\n const other = a[key];\n if (value === undefined || other === undefined) return [];\n const at = path ? `${path}.${key}` : key;\n return isPlainObject(value) && isPlainObject(other)\n ? overlappingKeys(other, value, at)\n : [at];\n });\n}\n\n/** Each `config.switchboard` key the reactor block already sets. */\nexport function reactorBlockConflicts(member: SwitchboardMember): string[] {\n const own = member.config?.switchboard;\n if (!own) return [];\n return overlappingKeys(\n reactorBlockToSwitchboardConfig(member.reactor) as Record<string, unknown>,\n own as Record<string, unknown>,\n ).map(\n (key) =>\n `config.switchboard.${key} is also set by the reactor block; set it in one place.`,\n );\n}\n\n/**\n * The deprecation notice for a block whose `readModel.url` still names the\n * reactor store too: nothing else names the store, as it did when\n * readModel.url rode `dbPath`.\n */\nexport function readModelAsReactorStore(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): { url: string; warning: string } | undefined {\n const storage = reactorBlockToSwitchboardConfig(reactor).storage;\n const url = storage?.readModel?.url;\n if (\n !url ||\n storage.reactor ||\n env.PH_REACTOR_DATABASE_URL !== undefined ||\n env.PH_SWITCHBOARD_DATABASE_URL !== undefined\n ) {\n return undefined;\n }\n return {\n url,\n warning:\n `${hostFileLabel}: reactor readModel.url (${url}) also holds the reactor store, because no storage names one. ` +\n \"This is deprecated: set the backend's storage explicitly (the same Postgres url, or a path dataDir).\",\n };\n}\n\n/**\n * The member's switchboard config under the runner's own arguments: its\n * reactor block, then `config.switchboard`, then the env over both, mapped\n * once as the server read it (the shell over the `.env`, whose values for the\n * block's own vars are dropped). The block keeps the precedence it had as\n * set-if-absent env and `dbPath`: only a shell PH_REACTOR_DATABASE_URL\n * overrides its store, and no env var overrides its read model. Writes nothing.\n */\nexport async function memberSwitchboardConfig(\n member: SwitchboardMember,\n env: MemberEnv,\n options: {\n pluginHost: boolean;\n logger?: ILogger;\n /** Under everything else: values no flag or host file set. */\n defaults?: SwitchboardConfigInput;\n },\n): Promise<SwitchboardConfigInput> {\n // Lazy: the env mapping loads reactor-api, which the runner module must not.\n const { switchboardConfigFromEnv } =\n await import(\"@powerhousedao/switchboard/config/env\");\n const block = reactorBlockToSwitchboardConfig(member.reactor);\n const legacy = readModelAsReactorStore(member.reactor, env.shell, \"\");\n if (legacy) {\n block.storage = { ...block.storage, reactor: { url: legacy.url } };\n }\n // One env, as the server read it: the .env under the block's own vars,\n // the shell over both.\n const dotenvValues: Record<string, string | undefined> = { ...env.dotenv };\n for (const name of blockEnvNames(member.reactor)) delete dotenvValues[name];\n const fromEnv = switchboardConfigFromEnv(\n { ...dotenvValues, ...env.shell },\n { logger: options.logger },\n );\n const storage = { ...fromEnv.storage };\n if (\n block.storage?.reactor &&\n env.shell.PH_REACTOR_DATABASE_URL === undefined\n ) {\n delete storage.reactor;\n }\n if (block.storage?.readModel) delete storage.readModel;\n return mergeSwitchboardConfig(\n options.defaults ?? {},\n block,\n member.config?.switchboard ?? {},\n { ...fromEnv, storage },\n // A declared composition turns the plugin host on, whatever the env says.\n options.pluginHost ? { features: { pluginHost: true } } : {},\n );\n}\n\n/**\n * Fails when the operator's env contradicts the member's protocol block, then\n * creates the block's path-storage dir (the server's own mkdir is not\n * recursive).\n */\nexport function prepareMemberStorage(\n reactor: ReactorConfig | undefined,\n env: Env,\n hostFileLabel: string,\n): void {\n assertProtocolConsistency(reactor?.protocol, { ...env }, hostFileLabel);\n const storage = primaryBackend(reactor)?.storage;\n if (storage?.kind !== \"path\" || !storage.dataDir) return;\n // `ph run` resolves `$env` and the `${userData}` sugar before the verb;\n // an unresolved one here would mkdir a literal \"${userData}\" folder.\n if (/\\$\\{(userData|projectRoot)\\}/.test(storage.dataDir)) {\n throw new Error(\n `${hostFileLabel}: storage.dataDir \"${storage.dataDir}\" was not resolved; resolve the host (resolveHostOutputs) before starting it.`,\n );\n }\n fs.mkdirSync(storage.dataDir, { recursive: true });\n}\n\n/** The verb owns dev mode; `runner.dev` is the host-file spelling of it. */\nexport function switchboardDevMode(\n devVerb: boolean,\n runner: { dev?: bo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="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]="24b73717-4ab0-54a3-b789-6259175ab4c3")}catch(e){}}();
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { execSync } from "node:child_process";
|
|
6
|
+
import { fetchPackageVersionFromNpmRegistry, injectPnpmAllowBuilds, spawnAsync } from "@powerhousedao/shared/clis";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { detect, resolveCommand } from "package-manager-detector";
|
|
9
|
+
import { compare, minVersion, prerelease, rcompare, valid } from "semver";
|
|
10
|
+
import { ALL_POWERHOUSE_DEPENDENCIES } from "@powerhousedao/shared/constants";
|
|
11
|
+
//#region src/services/migrate.ts
|
|
12
|
+
const PRERELEASE_TAGS = [
|
|
13
|
+
"dev",
|
|
14
|
+
"staging",
|
|
15
|
+
"rc"
|
|
16
|
+
];
|
|
17
|
+
const VERSION_CHECKED_ENV = "PH_MIGRATE_VERSION_CHECKED";
|
|
18
|
+
function readProjectPackageJson(projectDir) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(readFileSync(join(projectDir, "package.json"), "utf8"));
|
|
21
|
+
} catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The newest Powerhouse package version the project's package.json pins */
|
|
26
|
+
function newestPowerhouseVersion(packageJson) {
|
|
27
|
+
return [
|
|
28
|
+
packageJson.dependencies,
|
|
29
|
+
packageJson.devDependencies,
|
|
30
|
+
packageJson.peerDependencies
|
|
31
|
+
].flatMap((deps) => Object.entries(deps ?? {}).flatMap(([name, range]) => {
|
|
32
|
+
if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];
|
|
33
|
+
try {
|
|
34
|
+
const version = minVersion(range)?.version;
|
|
35
|
+
return version ? [{
|
|
36
|
+
name,
|
|
37
|
+
version
|
|
38
|
+
}] : [];
|
|
39
|
+
} catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
})).sort((a, b) => rcompare(a.version, b.version)).at(0);
|
|
43
|
+
}
|
|
44
|
+
/** The dist-tag of the channel the project is on, and why */
|
|
45
|
+
function inferReleaseTag(packageJson) {
|
|
46
|
+
const newest = newestPowerhouseVersion(packageJson);
|
|
47
|
+
if (!newest) return {
|
|
48
|
+
tag: "latest",
|
|
49
|
+
reason: "no Powerhouse package version is pinned"
|
|
50
|
+
};
|
|
51
|
+
const channel = prerelease(newest.version)?.[0];
|
|
52
|
+
const pinned = `${newest.name}@${newest.version}`;
|
|
53
|
+
if (typeof channel === "string" && PRERELEASE_TAGS.includes(channel)) return {
|
|
54
|
+
tag: channel,
|
|
55
|
+
reason: `the project is on ${pinned}`
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
tag: "latest",
|
|
59
|
+
reason: `the project is on ${pinned}, ${channel === void 0 ? "a stable release" : "not on a dev, staging or rc channel"}`
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Whether `target` is an older release than `installed`: lower by semver, or
|
|
63
|
+
* published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */
|
|
64
|
+
function isOlderRelease(installed, target, publishTimes = {}) {
|
|
65
|
+
if (!valid(installed) || !valid(target)) return false;
|
|
66
|
+
if (compare(target, installed) < 0) return true;
|
|
67
|
+
const installedAt = publishTimes[installed];
|
|
68
|
+
const targetAt = publishTimes[target];
|
|
69
|
+
if (!installedAt || !targetAt) return false;
|
|
70
|
+
return Date.parse(targetAt) < Date.parse(installedAt);
|
|
71
|
+
}
|
|
72
|
+
async function fetchPublishTimes(packageName) {
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(await spawnAsync("npm", [
|
|
75
|
+
"view",
|
|
76
|
+
packageName,
|
|
77
|
+
"time",
|
|
78
|
+
"--json"
|
|
79
|
+
]));
|
|
80
|
+
} catch {
|
|
81
|
+
return {};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function warnIfOlderRelease(packageJson, targetVersion) {
|
|
85
|
+
const newest = newestPowerhouseVersion(packageJson);
|
|
86
|
+
if (!newest) return;
|
|
87
|
+
const publishTimes = await fetchPublishTimes("@powerhousedao/ph-cli");
|
|
88
|
+
if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;
|
|
89
|
+
console.warn(`⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \`ph migrate dev\`) to stay on yours.`);
|
|
90
|
+
}
|
|
91
|
+
function getBundledPhCliVersion() {
|
|
92
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
93
|
+
for (let i = 0; i < 5; i++) {
|
|
94
|
+
try {
|
|
95
|
+
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
96
|
+
if (pkg.name === "@powerhousedao/ph-cli") return pkg.version;
|
|
97
|
+
} catch {}
|
|
98
|
+
dir = dirname(dir);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function resolveCodegenVersion(codegenMod) {
|
|
102
|
+
const getter = codegenMod.getCodegenVersion;
|
|
103
|
+
if (typeof getter === "function") {
|
|
104
|
+
const v = getter();
|
|
105
|
+
if (typeof v === "string") return v;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function assertCodegenMatchesBundled(args) {
|
|
109
|
+
const { codegenVersion, bundledVersion, force } = args;
|
|
110
|
+
if (force) return;
|
|
111
|
+
if (!codegenVersion) throw new Error("@powerhousedao/codegen is older than this ph-cli expects (no version export). Reinstall ph-cli to bring a matching codegen, or re-run with --force.");
|
|
112
|
+
if (bundledVersion && codegenVersion !== bundledVersion) throw new Error(`@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. Reinstall to align versions, or re-run with --force.`);
|
|
113
|
+
}
|
|
114
|
+
async function startMigrate({ versionPositional, version, force, debug }) {
|
|
115
|
+
const packageJson = readProjectPackageJson(process.cwd());
|
|
116
|
+
let requested = versionPositional ?? version;
|
|
117
|
+
if (requested === void 0) {
|
|
118
|
+
const inferred = inferReleaseTag(packageJson);
|
|
119
|
+
requested = inferred.tag;
|
|
120
|
+
console.log(`No version given; migrating to "${inferred.tag}" because ${inferred.reason}.`);
|
|
121
|
+
}
|
|
122
|
+
if (debug) console.log(`[migrate] requested version: ${requested}`);
|
|
123
|
+
let targetVersion;
|
|
124
|
+
try {
|
|
125
|
+
targetVersion = await fetchPackageVersionFromNpmRegistry(`@powerhousedao/ph-cli@${requested}`);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
128
|
+
if (!force) throw new Error(`Failed to resolve "${requested}" from the npm registry: ${reason}\nRe-run with --force to migrate using the installed version.`, { cause: error });
|
|
129
|
+
if (debug) console.log(`[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`);
|
|
130
|
+
}
|
|
131
|
+
if (targetVersion && !process.env[VERSION_CHECKED_ENV]) await warnIfOlderRelease(packageJson, targetVersion);
|
|
132
|
+
const bundledVersion = getBundledPhCliVersion();
|
|
133
|
+
if (debug) {
|
|
134
|
+
console.log(`[migrate] resolved target version: ${targetVersion ?? "(unknown)"}`);
|
|
135
|
+
console.log(`[migrate] current ph-cli version: ${bundledVersion ?? "(unknown)"}`);
|
|
136
|
+
}
|
|
137
|
+
if (!targetVersion || force || targetVersion === bundledVersion) {
|
|
138
|
+
if (debug) console.log(`[migrate] running migrate from bundled codegen`);
|
|
139
|
+
const codegenMod = await import("@powerhousedao/codegen");
|
|
140
|
+
const codegenVersion = resolveCodegenVersion(codegenMod);
|
|
141
|
+
assertCodegenMatchesBundled({
|
|
142
|
+
codegenVersion,
|
|
143
|
+
bundledVersion,
|
|
144
|
+
force: Boolean(force)
|
|
145
|
+
});
|
|
146
|
+
console.log(`Running migrate with @powerhousedao/codegen@${codegenVersion ?? "unknown"}`);
|
|
147
|
+
await codegenMod.migrate(targetVersion ?? requested);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const agent = (await detect())?.agent ?? "npm";
|
|
151
|
+
const resolved = resolveCommand(agent, "execute", [
|
|
152
|
+
`@powerhousedao/ph-cli@${targetVersion}`,
|
|
153
|
+
"migrate",
|
|
154
|
+
"--version",
|
|
155
|
+
targetVersion,
|
|
156
|
+
...debug ? ["--debug"] : []
|
|
157
|
+
]);
|
|
158
|
+
if (!resolved) throw new Error(`Failed to resolve execute command for package manager "${agent}".`);
|
|
159
|
+
injectPnpmAllowBuilds(agent, resolved);
|
|
160
|
+
const command = `${resolved.command} ${resolved.args.join(" ")}`;
|
|
161
|
+
if (debug) {
|
|
162
|
+
console.log(`[migrate] detected package manager: ${agent}`);
|
|
163
|
+
console.log(`[migrate] re-executing: ${command}`);
|
|
164
|
+
}
|
|
165
|
+
execSync(command, {
|
|
166
|
+
stdio: "inherit",
|
|
167
|
+
env: {
|
|
168
|
+
...process.env,
|
|
169
|
+
[VERSION_CHECKED_ENV]: "1"
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
export { startMigrate };
|
|
175
|
+
|
|
176
|
+
//# sourceMappingURL=migrate-CIJaE3iZ.mjs.map
|
|
177
|
+
//# debugId=24b73717-4ab0-54a3-b789-6259175ab4c3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate-CIJaE3iZ.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n spawnAsync,\n} from \"@powerhousedao/shared/clis\";\nimport { ALL_POWERHOUSE_DEPENDENCIES } from \"@powerhousedao/shared/constants\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { compare, minVersion, prerelease, rcompare, valid } from \"semver\";\nimport type { MigrateArgs } from \"../types.js\";\n\n// Dist-tags a prerelease version can name its channel by.\nconst PRERELEASE_TAGS = [\"dev\", \"staging\", \"rc\"];\n\n// Set on the re-executed migrate, so the version check runs once.\nconst VERSION_CHECKED_ENV = \"PH_MIGRATE_VERSION_CHECKED\";\n\ntype ProjectPackageJson = Partial<\n Record<\n \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n Record<string, string>\n >\n>;\n\nfunction readProjectPackageJson(projectDir: string): ProjectPackageJson {\n try {\n return JSON.parse(\n readFileSync(join(projectDir, \"package.json\"), \"utf8\"),\n ) as ProjectPackageJson;\n } catch {\n return {};\n }\n}\n\n/** The newest Powerhouse package version the project's package.json pins */\nexport function newestPowerhouseVersion(packageJson: ProjectPackageJson) {\n const pinned = [\n packageJson.dependencies,\n packageJson.devDependencies,\n packageJson.peerDependencies,\n ].flatMap((deps) =>\n Object.entries(deps ?? {}).flatMap(([name, range]) => {\n if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];\n try {\n const version = minVersion(range)?.version;\n return version ? [{ name, version }] : [];\n } catch {\n // workspace:, catalog: and other non-semver specifiers\n return [];\n }\n }),\n );\n return pinned.sort((a, b) => rcompare(a.version, b.version)).at(0);\n}\n\n/** The dist-tag of the channel the project is on, and why */\nexport function inferReleaseTag(packageJson: ProjectPackageJson): {\n tag: string;\n reason: string;\n} {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) {\n return { tag: \"latest\", reason: \"no Powerhouse package version is pinned\" };\n }\n const channel = prerelease(newest.version)?.[0];\n const pinned = `${newest.name}@${newest.version}`;\n if (typeof channel === \"string\" && PRERELEASE_TAGS.includes(channel)) {\n return { tag: channel, reason: `the project is on ${pinned}` };\n }\n return {\n tag: \"latest\",\n reason: `the project is on ${pinned}, ${channel === undefined ? \"a stable release\" : \"not on a dev, staging or rc channel\"}`,\n };\n}\n\n/** Whether `target` is an older release than `installed`: lower by semver, or\n * published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */\nexport function isOlderRelease(\n installed: string,\n target: string,\n publishTimes: Partial<Record<string, string>> = {},\n): boolean {\n if (!valid(installed) || !valid(target)) return false;\n if (compare(target, installed) < 0) return true;\n const installedAt = publishTimes[installed];\n const targetAt = publishTimes[target];\n if (!installedAt || !targetAt) return false;\n return Date.parse(targetAt) < Date.parse(installedAt);\n}\n\nasync function fetchPublishTimes(\n packageName: string,\n): Promise<Partial<Record<string, string>>> {\n try {\n return JSON.parse(\n await spawnAsync(\"npm\", [\"view\", packageName, \"time\", \"--json\"]),\n ) as Partial<Record<string, string>>;\n } catch {\n return {};\n }\n}\n\nasync function warnIfOlderRelease(\n packageJson: ProjectPackageJson,\n targetVersion: string,\n) {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) return;\n const publishTimes = await fetchPublishTimes(\"@powerhousedao/ph-cli\");\n if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;\n console.warn(\n `⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \\`ph migrate dev\\`) to stay on yours.`,\n );\n}\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const packageJson = readProjectPackageJson(process.cwd());\n let requested = versionPositional ?? version;\n if (requested === undefined) {\n const inferred = inferReleaseTag(packageJson);\n requested = inferred.tag;\n console.log(\n `No version given; migrating to \"${inferred.tag}\" because ${inferred.reason}.`,\n );\n }\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n if (targetVersion && !process.env[VERSION_CHECKED_ENV]) {\n await warnIfOlderRelease(packageJson, targetVersion);\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, {\n stdio: \"inherit\",\n env: { ...process.env, [VERSION_CHECKED_ENV]: \"1\" },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAeA,MAAM,kBAAkB;CAAC;CAAO;CAAW;AAAI;AAG/C,MAAM,sBAAsB;AAS5B,SAAS,uBAAuB,YAAwC;CACtE,IAAI;EACF,OAAO,KAAK,MACV,aAAa,KAAK,YAAY,cAAc,GAAG,MAAM,CACvD;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,wBAAwB,aAAiC;CAiBvE,OAhBe;EACb,YAAY;EACZ,YAAY;EACZ,YAAY;CACd,CAAC,CAAC,SAAS,SACT,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,WAAW;EACpD,IAAI,CAAC,4BAA4B,SAAS,IAAI,GAAG,OAAO,CAAC;EACzD,IAAI;GACF,MAAM,UAAU,WAAW,KAAK,CAAC,EAAE;GACnC,OAAO,UAAU,CAAC;IAAE;IAAM;GAAQ,CAAC,IAAI,CAAC;EAC1C,QAAQ;GAEN,OAAO,CAAC;EACV;CACF,CAAC,CAES,CAAC,CAAC,MAAM,GAAG,MAAM,S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IAAI,OACF,QAAQ,IACN,gGAAgG,QAClG;CAEJ;CAEA,IAAI,iBAAiB,CAAC,QAAQ,IAAI,sBAChC,MAAM,mBAAmB,aAAa,aAAa;CAGrD,MAAM,iBAAiB,uBAAuB;CAC9C,IAAI,OAAO;EACT,QAAQ,IACN,sCAAsC,iBAAiB,aACzD;EACA,QAAQ,IACN,qCAAqC,kBAAkB,aACzD;CACF;CAEA,IAAI,CAAC,iBAAiB,SAAS,kBAAkB,gBAAgB;EAC/D,IAAI,OAAO,QAAQ,IAAI,gDAAgD;EACvE,MAAM,aAAa,MAAM,OAAO;EAChC,MAAM,iBAAiB,sBACrB,UACF;EACA,4BAA4B;GAC1B;GACA;GACA,OAAO,QAAQ,KAAK;EACtB,CAAC;EACD,QAAQ,IACN,+CAA+C,kBAAkB,WACnE;EACA,MAAM,WAAW,QAAQ,iBAAiB,SAAS;EACnD;CACF;CAEA,MAAM,SAAS,MAAM,OAAO,EAAA,EAAI,SAAS;CACzC,MAAM,WAAW,eAAe,OAAO,WAAW;EAChD,yBAAyB;EACzB;EACA;EACA;EACA,GAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;CAC7B,CAAC;CACD,IAAI,CAAC,UACH,MAAM,IAAI,MACR,0DAA0D,MAAM,GAClE;CAGF,sBAAsB,OAAO,QAAQ;CAErC,MAAM,UAAU,GAAG,SAAS,QAAQ,GAAG,SAAS,KAAK,KAAK,GAAG;CAC7D,IAAI,OAAO;EACT,QAAQ,IAAI,uCAAuC,OAAO;EAC1D,QAAQ,IAAI,2BAA2B,SAAS;CAClD;CACA,SAAS,SAAS;EAChB,OAAO;EACP,KAAK;GAAE,GAAG,QAAQ;IAAM,sBAAsB;EAAI;CACpD,CAAC;AACH","debug_id":"24b73717-4ab0-54a3-b789-6259175ab4c3"}
|
|
@@ -0,0 +1,17 @@
|
|
|
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]="b019bb65-d519-5dd7-bf0e-4c90f1c91ce5")}catch(e){}}();
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
5
|
+
//#region src/utils/module-dir.ts
|
|
6
|
+
/** The directory in `<modulesDir>/` that `--dir` names, by name or by a path to it or a file in it */
|
|
7
|
+
function resolveModuleDirName(projectDir, modulesDir, dir, example) {
|
|
8
|
+
const modulesPath = join(projectDir, modulesDir);
|
|
9
|
+
const moduleDir = [resolve(projectDir, dir), join(modulesPath, dir)].filter((candidate) => existsSync(candidate)).map((candidate) => statSync(candidate).isDirectory() ? candidate : dirname(candidate)).find((candidate) => dirname(candidate) === modulesPath);
|
|
10
|
+
if (!moduleDir) throw new Error(`No directory in ${modulesDir}/ for --dir "${dir}": expected its name ("${example}") or its path ("${modulesDir}/${example}").`);
|
|
11
|
+
return basename(moduleDir);
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { resolveModuleDirName as t };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=module-dir-1avCXsBi.mjs.map
|
|
17
|
+
//# debugId=b019bb65-d519-5dd7-bf0e-4c90f1c91ce5
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module-dir-1avCXsBi.mjs","sources":["../src/utils/module-dir.ts"],"sourcesContent":["import { existsSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\n\n/** The directory in `<modulesDir>/` that `--dir` names, by name or by a path to it or a file in it */\nexport function resolveModuleDirName(\n projectDir: string,\n modulesDir:\n | \"document-models\"\n | \"editors\"\n | \"pieces\"\n | \"processors\"\n | \"subgraphs\",\n dir: string,\n example: string,\n) {\n const modulesPath = join(projectDir, modulesDir);\n const moduleDir = [resolve(projectDir, dir), join(modulesPath, dir)]\n .filter((candidate) => existsSync(candidate))\n .map((candidate) =>\n statSync(candidate).isDirectory() ? candidate : dirname(candidate),\n )\n .find((candidate) => dirname(candidate) === modulesPath);\n if (!moduleDir) {\n throw new Error(\n `No directory in ${modulesDir}/ for --dir \"${dir}\": expected its name (\"${example}\") or its path (\"${modulesDir}/${example}\").`,\n );\n }\n return basename(moduleDir);\n}\n"],"names":[],"mappings":";;;;;;AAIA,SAAgB,qBACd,YACA,YAMA,KACA,SACA;CACA,MAAM,cAAc,KAAK,YAAY,UAAU;CAC/C,MAAM,YAAY,CAAC,QAAQ,YAAY,GAAG,GAAG,KAAK,aAAa,GAAG,CAAC,CAAC,CACjE,QAAQ,cAAc,WAAW,SAAS,CAAC,CAAC,CAC5C,KAAK,cACJ,SAAS,SAAS,CAAC,CAAC,YAAY,IAAI,YAAY,QAAQ,SAAS,CACnE,CAAC,CACA,MAAM,cAAc,QAAQ,SAAS,MAAM,WAAW;CACzD,IAAI,CAAC,WACH,MAAM,IAAI,MACR,mBAAmB,WAAW,eAAe,IAAI,yBAAyB,QAAQ,mBAAmB,WAAW,GAAG,QAAQ,IAC7H;CAEF,OAAO,SAAS,SAAS;AAC3B","debug_id":"b019bb65-d519-5dd7-bf0e-4c90f1c91ce5"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { n as checkOfferedRoutesImports } from "./offered-routes-imports-CalXK9dh.mjs";
|
|
2
|
+
export { checkOfferedRoutesImports };
|
|
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]="98fd0401-72de-5587-ae2a-f8145c1170c8")}catch(e){}}();
|
|
4
|
+
//# debugId=98fd0401-72de-5587-ae2a-f8145c1170c8
|
|
@@ -0,0 +1,96 @@
|
|
|
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]="a3aeccc2-72fd-5986-9fd9-071f527658da")}catch(e){}}();
|
|
3
|
+
import { n as OFFERED_ROUTES_MODULE, t as HOST_ROUTES_DIR } from "./sync-connect-routes-t0Slg-P6.mjs";
|
|
4
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
//#region src/utils/offered-routes-imports.ts
|
|
7
|
+
const CONNECT_IMPORT = /^@powerhousedao\/connect(\/|$)/;
|
|
8
|
+
const GUARD = "ph-offered-routes-imports";
|
|
9
|
+
const CONNECT_IMPORT_HINT = "Routes a package offers other Connects import @powerhousedao/connect-core instead (ContentOutlet, ModalDialog, useConnectChrome, useDriveRouteData, useNavRoutes and useSidebarMode from @powerhousedao/connect-core/router, SidebarItem from @powerhousedao/design-system/connect); only its own host's _app.tsx and overrides may use @powerhousedao/connect.";
|
|
10
|
+
function reachableFrom(graph, entry) {
|
|
11
|
+
const reached = /* @__PURE__ */ new Set();
|
|
12
|
+
const pending = [entry];
|
|
13
|
+
for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
|
|
14
|
+
if (reached.has(id)) continue;
|
|
15
|
+
reached.add(id);
|
|
16
|
+
const info = graph.getModuleInfo(id);
|
|
17
|
+
if (info) pending.push(...info.importedIds, ...info.dynamicallyImportedIds);
|
|
18
|
+
}
|
|
19
|
+
return reached;
|
|
20
|
+
}
|
|
21
|
+
/** Fails the build on an import of Connect that the offered routes reach, as
|
|
22
|
+
* other Connects don't share Connect with the package; warns on one from the
|
|
23
|
+
* rest of the package, which bundles a copy of the Connect modules it uses. */
|
|
24
|
+
function noConnectImports(routesEntry, routesDir) {
|
|
25
|
+
const imports = /* @__PURE__ */ new Map();
|
|
26
|
+
const slash = (path) => path.replaceAll("\\", "/");
|
|
27
|
+
const isRoute = (id) => slash(id) === slash(routesEntry) || slash(id).startsWith(`${slash(routesDir)}/`);
|
|
28
|
+
return {
|
|
29
|
+
name: GUARD,
|
|
30
|
+
resolveId(source, importer) {
|
|
31
|
+
if (!importer || !CONNECT_IMPORT.test(source)) return null;
|
|
32
|
+
if (isRoute(importer)) throw new Error(`${importer} imports "${source}". ${CONNECT_IMPORT_HINT}`);
|
|
33
|
+
const sources = imports.get(importer) ?? /* @__PURE__ */ new Set();
|
|
34
|
+
imports.set(importer, sources.add(source));
|
|
35
|
+
return null;
|
|
36
|
+
},
|
|
37
|
+
buildEnd(error) {
|
|
38
|
+
if (error || !imports.size) return;
|
|
39
|
+
const entry = this.getModuleInfo(routesEntry) ? routesEntry : slash(routesEntry);
|
|
40
|
+
const reached = reachableFrom(this, entry);
|
|
41
|
+
const described = ([importer, sources]) => `${importer} imports ${[...sources].map((s) => `"${s}"`).join(", ")}`;
|
|
42
|
+
const offered = [...imports].filter(([id]) => reached.has(id));
|
|
43
|
+
if (offered.length) this.error(`${offered.map(described).join("\n")}\n${CONNECT_IMPORT_HINT}`);
|
|
44
|
+
console.warn(`⚠ ${[...imports].map(described).join("\n")}\nConnect isn't shared with the packages it loads, so the build bundles a copy of these modules, apart from the app's state. Import @powerhousedao/connect-core instead; a later version fails the build.`);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
49
|
+
const SCRIPT = /\.[cm]?[jt]sx?$/;
|
|
50
|
+
const projectModulesOnly = {
|
|
51
|
+
name: "ph-offered-routes-project-modules",
|
|
52
|
+
async resolveId(source, importer, options) {
|
|
53
|
+
if (!importer) return null;
|
|
54
|
+
const resolved = await this.resolve(source, importer, {
|
|
55
|
+
...options,
|
|
56
|
+
skipSelf: true
|
|
57
|
+
});
|
|
58
|
+
if (!resolved || resolved.external) return {
|
|
59
|
+
id: source,
|
|
60
|
+
external: true
|
|
61
|
+
};
|
|
62
|
+
if (IN_NODE_MODULES.test(resolved.id) || !SCRIPT.test(resolved.id)) return {
|
|
63
|
+
id: resolved.id,
|
|
64
|
+
external: true
|
|
65
|
+
};
|
|
66
|
+
return resolved;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/** Fails as `ph build` does when the routes the package offers reach an
|
|
70
|
+
* import of Connect; bundles the project's modules in memory, writing nothing. */
|
|
71
|
+
async function checkOfferedRoutesImports(projectDir) {
|
|
72
|
+
const projectRoot = realpathSync(projectDir);
|
|
73
|
+
const entry = join(projectRoot, OFFERED_ROUTES_MODULE);
|
|
74
|
+
if (!existsSync(entry)) return;
|
|
75
|
+
const { rolldown } = await import("rolldown");
|
|
76
|
+
const bundle = await rolldown({
|
|
77
|
+
input: entry,
|
|
78
|
+
cwd: projectRoot,
|
|
79
|
+
tsconfig: true,
|
|
80
|
+
logLevel: "silent",
|
|
81
|
+
plugins: [noConnectImports(entry, join(projectRoot, HOST_ROUTES_DIR)), projectModulesOnly]
|
|
82
|
+
});
|
|
83
|
+
try {
|
|
84
|
+
await bundle.generate({});
|
|
85
|
+
} catch (error) {
|
|
86
|
+
const found = (error.errors ?? []).filter((e) => e.plugin === GUARD);
|
|
87
|
+
if (found.length) throw new Error(found.map((e) => e.message).join("\n"), { cause: error });
|
|
88
|
+
} finally {
|
|
89
|
+
await bundle.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
export { checkOfferedRoutesImports as n, noConnectImports as r, CONNECT_IMPORT_HINT as t };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=offered-routes-imports-CalXK9dh.mjs.map
|
|
96
|
+
//# debugId=a3aeccc2-72fd-5986-9fd9-071f527658da
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"offered-routes-imports-CalXK9dh.mjs","sources":["../src/utils/offered-routes-imports.ts"],"sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Plugin } from \"rolldown\";\nimport {\n HOST_ROUTES_DIR,\n OFFERED_ROUTES_MODULE,\n} from \"./sync-connect-routes.js\";\n\nconst CONNECT_IMPORT = /^@powerhousedao\\/connect(\\/|$)/;\n\nconst GUARD = \"ph-offered-routes-imports\";\n\nexport const CONNECT_IMPORT_HINT =\n \"Routes a package offers other Connects import @powerhousedao/connect-core instead (ContentOutlet, ModalDialog, useConnectChrome, useDriveRouteData, useNavRoutes and useSidebarMode from @powerhousedao/connect-core/router, SidebarItem from @powerhousedao/design-system/connect); only its own host's _app.tsx and overrides may use @powerhousedao/connect.\";\n\ntype ModuleGraph = {\n getModuleInfo(id: string): {\n importedIds: readonly string[];\n dynamicallyImportedIds: readonly string[];\n } | null;\n error(message: string): never;\n};\n\nfunction reachableFrom(graph: ModuleGraph, entry: string) {\n const reached = new Set<string>();\n const pending = [entry];\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (reached.has(id)) continue;\n reached.add(id);\n const info = graph.getModuleInfo(id);\n if (info) pending.push(...info.importedIds, ...info.dynamicallyImportedIds);\n }\n return reached;\n}\n\n/** Fails the build on an import of Connect that the offered routes reach, as\n * other Connects don't share Connect with the package; warns on one from the\n * rest of the package, which bundles a copy of the Connect modules it uses. */\nexport function noConnectImports(routesEntry: string, routesDir: string) {\n const imports = new Map<string, Set<string>>();\n // Module ids may spell a Windows path with either separator.\n const slash = (path: string) => path.replaceAll(\"\\\\\", \"/\");\n const isRoute = (id: string) =>\n slash(id) === slash(routesEntry) ||\n slash(id).startsWith(`${slash(routesDir)}/`);\n return {\n name: GUARD,\n resolveId(source: string, importer: string | undefined) {\n if (!importer || !CONNECT_IMPORT.test(source)) return null;\n // Before resolving it: a route file's import fails even unresolved.\n if (isRoute(importer)) {\n throw new Error(\n `${importer} imports \"${source}\". ${CONNECT_IMPORT_HINT}`,\n );\n }\n const sources = imports.get(importer) ?? new Set<string>();\n imports.set(importer, sources.add(source));\n return null;\n },\n buildEnd(this: ModuleGraph, error?: Error) {\n if (error || !imports.size) return;\n const entry = this.getModuleInfo(routesEntry)\n ? routesEntry\n : slash(routesEntry);\n const reached = reachableFrom(this, entry);\n const described = ([importer, sources]: [string, Set<string>]) =>\n `${importer} imports ${[...sources].map((s) => `\"${s}\"`).join(\", \")}`;\n const offered = [...imports].filter(([id]) => reached.has(id));\n if (offered.length) {\n this.error(\n `${offered.map(described).join(\"\\n\")}\\n${CONNECT_IMPORT_HINT}`,\n );\n }\n console.warn(\n `⚠ ${[...imports].map(described).join(\"\\n\")}\\nConnect isn't shared with the packages it loads, so the build bundles a copy of these modules, apart from the app's state. Import @powerhousedao/connect-core instead; a later version fails the build.`,\n );\n },\n };\n}\n\ntype PluginError = Error & { plugin?: string };\n\nconst IN_NODE_MODULES = /[\\\\/]node_modules[\\\\/]/;\nconst SCRIPT = /\\.[cm]?[jt]sx?$/;\n\n// The project's own modules only: dependencies, styles and assets stay out.\nconst projectModulesOnly: Plugin = {\n name: \"ph-offered-routes-project-modules\",\n async resolveId(source, importer, options) {\n if (!importer) return null;\n const resolved = await this.resolve(source, importer, {\n ...options,\n skipSelf: true,\n });\n if (!resolved || resolved.external) return { id: source, external: true };\n if (IN_NODE_MODULES.test(resolved.id) || !SCRIPT.test(resolved.id)) {\n return { id: resolved.id, external: true };\n }\n return resolved;\n },\n};\n\n/** Fails as `ph build` does when the routes the package offers reach an\n * import of Connect; bundles the project's modules in memory, writing nothing. */\nexport async function checkOfferedRoutesImports(projectDir: string) {\n // Module ids are real paths; the routes are matched against them.\n const projectRoot = realpathSync(projectDir);\n const entry = join(projectRoot, OFFERED_ROUTES_MODULE);\n if (!existsSync(entry)) return;\n const { rolldown } = await import(\"rolldown\");\n const bundle = await rolldown({\n input: entry,\n cwd: projectRoot,\n tsconfig: true,\n logLevel: \"silent\",\n plugins: [\n noConnectImports(entry, join(projectRoot, HOST_ROUTES_DIR)),\n projectModulesOnly,\n ],\n });\n try {\n // Rolldown resolves the graph on generate.\n await bundle.generate({});\n } catch (error) {\n // Only the import rule fails here; tsc and lint report a file that won't parse.\n const found = ((error as { errors?: PluginError[] }).errors ?? []).filter(\n (e) => e.plugin === GUARD,\n );\n if (found.length) {\n throw new Error(found.map((e) => e.message).join(\"\\n\"), {\n cause: error,\n });\n }\n } finally {\n await bundle.close();\n }\n}\n"],"names":[],"mappings":";;;;;;AAQA,MAAM,iBAAiB;AAEvB,MAAM,QAAQ;AAEd,MAAa,sBACX;AAUF,SAAS,cAAc,OAAoB,OAAe;CACxD,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,UAAU,CAAC,KAAK;CACtB,KAAK,IAAI,KAAK,QAAQ,IAAI,GAAG,OAAO,KAAA,GAAW,KAAK,QAAQ,IAAI,GAAG;EACjE,IAAI,QAAQ,IAAI,EAAE,GAAG;EACrB,QAAQ,IAAI,EAAE;EACd,MAAM,OAAO,MAAM,cAAc,EAAE;EACnC,IAAI,MAAM,QAAQ,KAAK,GAAG,KAAK,aAAa,GAAG,KAAK,sBAAsB;CAC5E;CACA,OAAO;AACT;;;;AAKA,SAAgB,iBAAiB,aAAqB,WAAmB;CACvE,MAAM,0BAAU,IAAI,IAAyB;CAE7C,MAAM,SAAS,SAAiB,KAAK,WAAW,MAAM,GAAG;CACzD,MAAM,WAAW,OACf,MAAM,EAAE,MAAM,MAAM,WAAW,KAC/B,MAAM,EAAE,CAAC,CAAC,WAAW,GAAG,MAAM,SAAS,EAAE,EAAE;CAC7C,OAAO;EACL,MAAM;EACN,UAAU,QAAgB,UAA8B;GACtD,IAAI,CAAC,YAAY,CAAC,eAAe,KAAK,MAAM,GAAG,OAAO;GAEtD,IAAI,QAAQ,QAAQ,GAClB,MAAM,IAAI,MACR,GAAG,SAAS,YAAY,OAAO,KAAK,qBACtC;GAEF,MAAM,UAAU,QAAQ,IAAI,QAAQ,qBAAK,IAAI,IAAY;GACzD,QAAQ,IAAI,UAAU,QAAQ,IAAI,MAAM,CAAC;GACzC,OAAO;EACT;EACA,SAA4B,OAAe;GACzC,IAAI,SAAS,CAAC,QAAQ,MAAM;GAC5B,M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,UAAU;EACV,SAAS,CACP,iBAAiB,OAAO,KAAK,aAAa,eAAe,CAAC,GAC1D,kBACF;CACF,CAAC;CACD,IAAI;EAEF,MAAM,OAAO,SAAS,CAAC,CAAC;CAC1B,SAAS,OAAO;EAEd,MAAM,SAAU,MAAqC,UAAU,CAAC,EAAA,CAAG,QAChE,MAAM,EAAE,WAAW,KACtB;EACA,IAAI,MAAM,QACR,MAAM,IAAI,MAAM,MAAM,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI,GAAG,EACtD,OAAO,MACT,CAAC;CAEL,UAAU;EACR,MAAM,OAAO,MAAM;CACrB;AACF","debug_id":"a3aeccc2-72fd-5986-9fd9-071f527658da"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { n as phCliCommands } from "./ph-cli-commands-DFmTGL-H.mjs";
|
|
2
|
+
export { phCliCommands };
|
|
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]="06eb4112-c53e-56d7-8a34-60087894ab72")}catch(e){}}();
|
|
4
|
+
//# debugId=06eb4112-c53e-56d7-8a34-60087894ab72
|