@prisma/composer-cli 0.39.0-dev.1 → 0.39.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/app-converge-bS1l9jIf-B1FOgxBQ.mjs +88 -0
  2. package/dist/app-converge-bS1l9jIf-B1FOgxBQ.mjs.map +1 -0
  3. package/dist/composer-config-QKdY85G--CEXrb2Uc.mjs +254 -0
  4. package/dist/composer-config-QKdY85G--CEXrb2Uc.mjs.map +1 -0
  5. package/dist/{validate-environment-D1BTCkTs-C5m4rL6t.mjs → deploy-Br1yvLe3.mjs} +335 -1091
  6. package/dist/deploy-Br1yvLe3.mjs.map +1 -0
  7. package/dist/dev-converge-messages-DML4rTz7-B6uxtpZG.mjs +256 -0
  8. package/dist/dev-converge-messages-DML4rTz7-B6uxtpZG.mjs.map +1 -0
  9. package/dist/dev-converge-worker.d.mts +1 -0
  10. package/dist/dev-converge-worker.mjs +143 -0
  11. package/dist/dev-converge-worker.mjs.map +1 -0
  12. package/dist/{dev-current-wD5YDLjA-CFI8XTAK.mjs → dev-current-lAlj53eX-DvAHNZFo.mjs} +12 -18
  13. package/dist/dev-current-lAlj53eX-DvAHNZFo.mjs.map +1 -0
  14. package/dist/dev-environment-name-6eEr5PW8-CCY7WNWz.mjs +43 -0
  15. package/dist/dev-environment-name-6eEr5PW8-CCY7WNWz.mjs.map +1 -0
  16. package/dist/{dist-D0rWRHos.mjs → dist-C0OGaDnj.mjs} +4 -3
  17. package/dist/{dist-D0rWRHos.mjs.map → dist-C0OGaDnj.mjs.map} +1 -1
  18. package/dist/errors-CVYwN2km.mjs +93 -0
  19. package/dist/errors-CVYwN2km.mjs.map +1 -0
  20. package/dist/{execute-deploy-destroy-DOzo2Psp-2iWcFbD9.mjs → execute-deploy-destroy-DN16ETAk-CzORriUO.mjs} +374 -141
  21. package/dist/execute-deploy-destroy-DN16ETAk-CzORriUO.mjs.map +1 -0
  22. package/dist/{execute-dev-BIyOI3Ys-DGpTd9rP.mjs → execute-dev-DnVmNpc1-BzK9Qns_.mjs} +444 -128
  23. package/dist/execute-dev-DnVmNpc1-BzK9Qns_.mjs.map +1 -0
  24. package/dist/{execute-dev-current-CKOzjWuO-DTOVqZzZ.mjs → execute-dev-current-CZdmxVQ4-DxDflvNG.mjs} +9 -6
  25. package/dist/{execute-dev-current-CKOzjWuO-DTOVqZzZ.mjs.map → execute-dev-current-CZdmxVQ4-DxDflvNG.mjs.map} +1 -1
  26. package/dist/{redaction-Bf8FvTFH-XGchRgrK.d.mts → family-DfwviKFj-CS1L-EvS.d.mts} +439 -204
  27. package/dist/family-DfwviKFj-CS1L-EvS.d.mts.map +1 -0
  28. package/dist/family.d.mts +1 -1
  29. package/dist/family.mjs +259 -269
  30. package/dist/family.mjs.map +1 -1
  31. package/dist/internal-error-Dfur7Zqt-B8J8e7ac.mjs +58 -0
  32. package/dist/internal-error-Dfur7Zqt-B8J8e7ac.mjs.map +1 -0
  33. package/dist/{list-deployed-BFJJxt_W.mjs → list-deployed-D6vTzpWu.mjs} +6 -5
  34. package/dist/list-deployed-D6vTzpWu.mjs.map +1 -0
  35. package/dist/local-target-CZzICh5R.mjs +34 -0
  36. package/dist/local-target-CZzICh5R.mjs.map +1 -0
  37. package/dist/{preflight-transport-DmmtoFPH-CZ0o7QPf.mjs → preflight-transport-2d6iIchu-ArIJUY1L.mjs} +7 -28
  38. package/dist/preflight-transport-2d6iIchu-ArIJUY1L.mjs.map +1 -0
  39. package/dist/{redaction-DXung4ip-Co_fv4Zl.mjs → redaction-DY6eDC12-BrK1aSN5.mjs} +33 -267
  40. package/dist/redaction-DY6eDC12-BrK1aSN5.mjs.map +1 -0
  41. package/dist/result-CttmabB6.mjs +91 -0
  42. package/dist/result-CttmabB6.mjs.map +1 -0
  43. package/dist/rolldown-runtime-C7HZzL1F.mjs +26 -0
  44. package/dist/steps-BZXNqW6U-BM2Aa8Bp.mjs +287 -0
  45. package/dist/steps-BZXNqW6U-BM2Aa8Bp.mjs.map +1 -0
  46. package/dist/testing.d.mts +4 -49
  47. package/dist/testing.d.mts.map +1 -1
  48. package/dist/testing.mjs +2 -75
  49. package/dist/testing.mjs.map +1 -1
  50. package/dist/validate-environment-DCZiNSlR-idVge-kq.mjs +983 -0
  51. package/dist/validate-environment-DCZiNSlR-idVge-kq.mjs.map +1 -0
  52. package/dist/value-reads-change-text-DcRCv7Zy-Ca8m3bal.mjs +15 -0
  53. package/dist/value-reads-change-text-DcRCv7Zy-Ca8m3bal.mjs.map +1 -0
  54. package/package.json +9 -9
  55. package/src/exports/dev-converge-worker.ts +2 -0
  56. package/src/exports/testing.ts +1 -4
  57. package/dist/app-configuration-file-CeJvBAti-DA4EKwFq.mjs +0 -140
  58. package/dist/app-configuration-file-CeJvBAti-DA4EKwFq.mjs.map +0 -1
  59. package/dist/dev-current-wD5YDLjA-CFI8XTAK.mjs.map +0 -1
  60. package/dist/dev-environment-name-6eEr5PW8-Bs4Dl0vW.mjs +0 -71
  61. package/dist/dev-environment-name-6eEr5PW8-Bs4Dl0vW.mjs.map +0 -1
  62. package/dist/execute-deploy-destroy-DOzo2Psp-2iWcFbD9.mjs.map +0 -1
  63. package/dist/execute-dev-BIyOI3Ys-DGpTd9rP.mjs.map +0 -1
  64. package/dist/generate-dev-stack-BV_n-X9n-DM5faH3-.mjs +0 -100
  65. package/dist/generate-dev-stack-BV_n-X9n-DM5faH3-.mjs.map +0 -1
  66. package/dist/list-deployed-BFJJxt_W.mjs.map +0 -1
  67. package/dist/preflight-transport-DmmtoFPH-CZ0o7QPf.mjs.map +0 -1
  68. package/dist/redaction-Bf8FvTFH-XGchRgrK.d.mts.map +0 -1
  69. package/dist/redaction-DXung4ip-Co_fv4Zl.mjs.map +0 -1
  70. package/dist/result-sR7PBi61.mjs +0 -229
  71. package/dist/result-sR7PBi61.mjs.map +0 -1
  72. package/dist/run-alchemy-CRLAyOtt-CwFLe4Zg.mjs +0 -236
  73. package/dist/run-alchemy-CRLAyOtt-CwFLe4Zg.mjs.map +0 -1
  74. package/dist/validate-environment-D1BTCkTs-C5m4rL6t.mjs.map +0 -1
@@ -1,71 +1,19 @@
1
- import { a as nodeAddresses, i as validateEnvironmentName, o as secretsKeys, r as runPipeline } from "./validate-environment-D1BTCkTs-C5m4rL6t.mjs";
2
- import { c as redactThrown, l as redactUnsetPlatformVariable, m as noComposerExportMessage, n as SecretRedaction, o as redactError, s as redactSummary } from "./redaction-DXung4ip-Co_fv4Zl.mjs";
3
- import { a as preflightFindingsEnv, i as preflightEnvVarName, r as preflightEnv, t as containerEnv } from "./preflight-transport-DmmtoFPH-CZ0o7QPf.mjs";
4
- import { i as CliStructuredError, n as ok, o as blindCast, r as okVoid, t as notOk } from "./result-sR7PBi61.mjs";
5
- import { c as toStructured, s as requireContainerForEnvironment } from "./dev-current-wD5YDLjA-CFI8XTAK.mjs";
6
- import { i as spawnAlchemy, n as alchemyInvocation, r as reproduceCommand } from "./run-alchemy-CRLAyOtt-CwFLe4Zg.mjs";
7
- import { i as removeLeftoverAppConfigurationFiles, r as prepareSecondProcess, t as deployAppConfigurationFile } from "./app-configuration-file-CeJvBAti-DA4EKwFq.mjs";
1
+ import { i as noComposerExportMessage } from "./composer-config-QKdY85G--CEXrb2Uc.mjs";
2
+ import { t as InternalError } from "./internal-error-Dfur7Zqt-B8J8e7ac.mjs";
3
+ import { f as nodeAddresses } from "./deploy-Br1yvLe3.mjs";
4
+ import { t as CliStructuredError } from "./errors-CVYwN2km.mjs";
5
+ import { a as redactError, c as redactUnsetPlatformVariable, n as StreamRedactor, o as redactSummary, r as credentialLookingValues, s as redactThrown, t as SecretRedaction } from "./redaction-DY6eDC12-BrK1aSN5.mjs";
6
+ import { r as preflightEnvVarName, t as containerEnv } from "./preflight-transport-2d6iIchu-ArIJUY1L.mjs";
7
+ import { n as ok, r as okVoid, t as notOk } from "./result-CttmabB6.mjs";
8
+ import { c as toStructured, n as convergeReasonsText, s as requireContainerForEnvironment } from "./dev-current-lAlj53eX-DvAHNZFo.mjs";
9
+ import { t as loadAppConvergeEntry } from "./app-converge-bS1l9jIf-B1FOgxBQ.mjs";
10
+ import { i as validateEnvironmentName, r as runPipeline } from "./validate-environment-DCZiNSlR-idVge-kq.mjs";
11
+ import { a as prepareSecondProcess, c as removeLeftoverAppConfigurationFiles, d as engineFailureFilePath, f as readEngineFailureCause, i as deployAppConfigurationFile, l as DEPLOYMENT_RESULT_FILE_ENV, m as withComposerAdvice, n as reportConvergeEvent, p as toDeploymentSummary, r as stepTracker, s as refuseSecretsInRootInput, t as interactionMessages, u as capFailureCause } from "./steps-BZXNqW6U-BM2Aa8Bp.mjs";
12
+ import { createRequire } from "node:module";
8
13
  import * as fs from "node:fs";
9
14
  import * as path from "node:path";
10
15
  import { randomUUID } from "node:crypto";
11
- //#region ../../0-framework/3-tooling/cli/dist/deployment-summary-D74WrJX7.mjs
12
- /**
13
- * The deploy result's cross-process protocol, whole in one place: the
14
- * serializable shape, the env var that names the carrier file, the writer the
15
- * report hook calls from inside the alchemy child, and the reader the deploy
16
- * operation runs after the child exits. `DeploymentResult` itself cannot
17
- * cross the boundary — its `DeployedNode` entries hold live graph-node
18
- * references (ADR-0033) — so the writer projects it down to what CAN.
19
- *
20
- * The summary is best-effort by contract: the writer never fails the child
21
- * over it, and the reader maps absent or malformed to `undefined`. So is the
22
- * failure cause the child leaves beside it when it exits non-zero.
23
- */
24
- /** Env var the deploy operation sets on the alchemy child: when present,
25
- * the report hook also writes the JSON DeploymentSummary there. */
26
- const DEPLOYMENT_RESULT_FILE_ENV = "PRISMA_COMPOSER_DEPLOYMENT_RESULT_FILE";
27
- function isRecord(value) {
28
- return typeof value === "object" && value !== null;
29
- }
30
- /**
31
- * Reader half, run by the deploy operation after the child exits. Absent or
32
- * malformed → undefined — the summary is best-effort, never a deploy failure.
33
- */
34
- function readDeploymentSummary(resultFilePath) {
35
- let raw;
36
- try {
37
- raw = fs.readFileSync(resultFilePath, "utf8");
38
- } catch {
39
- return;
40
- }
41
- let parsed;
42
- try {
43
- parsed = JSON.parse(raw);
44
- } catch {
45
- return;
46
- }
47
- if (!isRecord(parsed) || typeof parsed["app"] !== "string" || !Array.isArray(parsed["nodes"])) return;
48
- for (const node of parsed["nodes"]) {
49
- if (!isRecord(node) || typeof node["address"] !== "string" || !Array.isArray(node["entities"])) return;
50
- for (const entity of node["entities"]) if (!isRecord(entity) || typeof entity["kind"] !== "string" || typeof entity["id"] !== "string") return;
51
- }
52
- return blindCast(parsed);
53
- }
54
- /** The child's failure cause rides beside the result file, so the one env var names both and the parent's cleanup removes both. */
55
- function engineFailureFilePath(resultFilePath) {
56
- return `${resultFilePath}.failure.txt`;
57
- }
58
- /** Parent half: the cause the child recorded, passed through `redact`, or undefined when it recorded none. The child redacts only what its own environment names as a credential; the parent also knows the known secrets. */
59
- function readEngineFailureCause(resultFilePath, redact) {
60
- let cause;
61
- try {
62
- cause = fs.readFileSync(engineFailureFilePath(resultFilePath), "utf8");
63
- } catch {
64
- return;
65
- }
66
- return cause.length > 0 ? redact(cause) : void 0;
67
- }
68
- //#endregion
16
+ import spawn from "cross-spawn";
69
17
  //#region ../../0-framework/3-tooling/cli/dist/run-report-CmBz2-xc.mjs
70
18
  /** Names the file to write the run report to, when `--report` is not passed. */
71
19
  const RUN_REPORT_FILE_ENV = "PRISMA_COMPOSER_REPORT_FILE";
@@ -107,7 +55,7 @@ function writeRunReport(filePath, report) {
107
55
  }
108
56
  }
109
57
  //#endregion
110
- //#region ../../0-framework/3-tooling/cli/dist/execute-deploy-destroy-DOzo2Psp.mjs
58
+ //#region ../../0-framework/3-tooling/cli/dist/execute-deploy-destroy-DN16ETAk.mjs
111
59
  /** Pipeline step 6: writes a regenerated-every-run, independently runnable stack module at `.prisma-composer/alchemy.run.ts`. */
112
60
  const GENERATED_DIR = ".prisma-composer";
113
61
  const GENERATED_FILE = "alchemy.run.ts";
@@ -180,6 +128,228 @@ function writeStackFile(input) {
180
128
  }
181
129
  const GENERATED_STACK_RELATIVE_PATH = path.join(GENERATED_DIR, GENERATED_FILE);
182
130
  /**
131
+ * Which Alchemy CLI runs a generated stack file: the `alchemy` that
132
+ * `@prisma/composer` depends on, found from the app the way the stack file's
133
+ * own `@prisma/composer/...` imports are. The CLI and the stack code then
134
+ * come from one install, so the child loads one copy of `alchemy`.
135
+ *
136
+ * Node's resolver finds `@prisma/composer` from the app. It cannot find
137
+ * `alchemy` from there: alchemy exports neither its `package.json` nor its
138
+ * bin, and has no `require` condition. Bun has no `module.findPackageJSON`.
139
+ * So the last step is Node's own lookup written out: each `node_modules`
140
+ * above `@prisma/composer`'s real location, nearest first.
141
+ */
142
+ const FIX = "Check that the app depends on @prisma/composer and that `alchemy`, which @prisma/composer depends on, is installed in a node_modules directory. Layouts without one, such as Yarn Plug'n'Play, are not supported.";
143
+ function binMissing(message) {
144
+ return new CliStructuredError("DEPLOY.ALCHEMY_BIN_MISSING", message, { fix: FIX });
145
+ }
146
+ function composerPackageDir(appDir) {
147
+ try {
148
+ const manifest = createRequire(path.join(appDir, "package.json")).resolve("@prisma/composer/package.json");
149
+ return path.dirname(fs.realpathSync(manifest));
150
+ } catch {
151
+ return;
152
+ }
153
+ }
154
+ function alchemyPackageDirAbove(dir) {
155
+ for (let current = dir;; current = path.dirname(current)) {
156
+ const candidate = path.join(current, "node_modules", "alchemy");
157
+ if (fs.existsSync(path.join(candidate, "package.json"))) return candidate;
158
+ if (path.dirname(current) === current) return void 0;
159
+ }
160
+ }
161
+ function readPackageJson(packageDir) {
162
+ try {
163
+ return JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
164
+ } catch {
165
+ return;
166
+ }
167
+ }
168
+ function binOf(packageDir) {
169
+ const manifest = readPackageJson(packageDir);
170
+ if (typeof manifest !== "object" || manifest === null || !("bin" in manifest)) return void 0;
171
+ const bin = manifest.bin;
172
+ const relative = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null && "alchemy" in bin ? bin.alchemy : void 0;
173
+ if (typeof relative !== "string") return void 0;
174
+ const entry = path.join(packageDir, relative);
175
+ return fs.existsSync(entry) ? entry : void 0;
176
+ }
177
+ /**
178
+ * The JavaScript file `alchemy`'s `bin` names, for the app in `appDir`.
179
+ * Raises DEPLOY.ALCHEMY_BIN_MISSING when the app does not resolve
180
+ * `@prisma/composer` or no usable `alchemy` is installed beside it.
181
+ */
182
+ function resolveAlchemyBin(appDir) {
183
+ const composerDir = composerPackageDir(appDir);
184
+ if (composerDir === void 0) throw binMissing(`Could not resolve @prisma/composer from "${appDir}".`);
185
+ const alchemyDir = alchemyPackageDirAbove(composerDir);
186
+ const entry = alchemyDir === void 0 ? void 0 : binOf(alchemyDir);
187
+ if (entry === void 0) throw binMissing(`Could not resolve the bin of the \`alchemy\` package @prisma/composer depends on, from "${composerDir}".`);
188
+ return entry;
189
+ }
190
+ /**
191
+ * Pipeline step 9 (deploy-cli.md § The pipeline; design-notes.md's "Driving
192
+ * Alchemy" call): run the generated stack file and, for programmatic hosts, pipe its
193
+ * output through redaction.
194
+ *
195
+ * Runs the bin of the `alchemy` the app's `@prisma/composer` depends on
196
+ * (`resolveAlchemyBin`), started with Node (`nodeExecutable`). Never a
197
+ * `node_modules/.bin` link, which pnpm creates only for an app's direct
198
+ * dependencies.
199
+ *
200
+ * Only `destroy` still runs Alchemy in a child; `deploy` and `dev` converge
201
+ * in-process (ADR-0066). This module composes the invocation; `spawnAlchemy`
202
+ * starts it, piping the child's output through the stream redactor
203
+ * (ADR-0062), and tests substitute their own runner.
204
+ */
205
+ function currentRuntime() {
206
+ return {
207
+ bun: process.versions.bun !== void 0,
208
+ execPath: process.execPath,
209
+ env: process.env,
210
+ platform: process.platform,
211
+ exists: fs.existsSync
212
+ };
213
+ }
214
+ function envValue(env, name) {
215
+ return Object.entries(env).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
216
+ }
217
+ /** The file names `node` may have in a PATH directory: PATHEXT's extensions on Windows. */
218
+ function nodeFileNames(runtime) {
219
+ if (runtime.platform !== "win32") return ["node"];
220
+ return (envValue(runtime.env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((extension) => extension.length > 0).map((extension) => `node${extension}`);
221
+ }
222
+ /**
223
+ * The Node that starts Alchemy's launcher: this process's own runtime under
224
+ * Node, and the first `node` on PATH under Bun. Alchemy's launcher may still
225
+ * move itself to Bun when the package-manager environment says Bun invoked
226
+ * it (`bunx`, `bun run`), so the runtime Alchemy ends up on follows how
227
+ * `prisma` was invoked.
228
+ */
229
+ function nodeExecutable(runtime = currentRuntime()) {
230
+ if (!runtime.bun) return runtime.execPath;
231
+ const paths = runtime.platform === "win32" ? path.win32 : path.posix;
232
+ const names = nodeFileNames(runtime);
233
+ for (const rawDir of (envValue(runtime.env, "PATH") ?? "").split(paths.delimiter)) {
234
+ const dir = rawDir.replace(/^"(.*)"$/, "$1");
235
+ if (dir.length === 0) continue;
236
+ for (const name of names) {
237
+ const candidate = paths.join(dir, name);
238
+ if (runtime.exists(candidate)) return candidate;
239
+ }
240
+ }
241
+ throw new CliStructuredError("DEPLOY.NODE_MISSING", "Composer starts Alchemy with Node, and no `node` was found on PATH.", { fix: "Install Node.js 22.18 or newer on the 22 line, 24.11 or newer on the 24 line, or 26 or newer, and put it on PATH, or run `prisma` under Node." });
242
+ }
243
+ /**
244
+ * Resolves the invocation against this machine — the step every adapter takes
245
+ * and no caller should. Runs alchemy's JavaScript entry with Node, so no shell
246
+ * shim is involved on any platform. Raises DEPLOY.ALCHEMY_BIN_MISSING when
247
+ * Composer's alchemy cannot be resolved, and DEPLOY.NODE_MISSING when no Node
248
+ * can run it.
249
+ */
250
+ function alchemyCommandLine(invocation, alchemyBin = resolveAlchemyBin(invocation.cwd), node = nodeExecutable()) {
251
+ return {
252
+ command: node,
253
+ args: [
254
+ alchemyBin,
255
+ invocation.action,
256
+ invocation.stackFileRelativePath,
257
+ "--yes",
258
+ "--stage",
259
+ invocation.stage
260
+ ],
261
+ cwd: invocation.cwd,
262
+ env: invocation.env
263
+ };
264
+ }
265
+ /** What becomes `alchemy deploy|destroy <stack file> --yes --stage <stage>`. */
266
+ function alchemyInvocation(input) {
267
+ return {
268
+ action: input.command,
269
+ stackFileRelativePath: input.stackFileRelativePath,
270
+ cwd: input.cwd,
271
+ stage: input.stage,
272
+ env: {
273
+ ...input.containerEnv,
274
+ ...input.preflightEnv,
275
+ ...input.env
276
+ },
277
+ redactedValues: input.redactedValues
278
+ };
279
+ }
280
+ /**
281
+ * The default runner for hosts with no engine: stdin inherited and output piped through redaction, the caller's
282
+ * own process group, and the child's status returned verbatim. It does not
283
+ * collapse a signal into an exit code — that collapse is what made a
284
+ * Ctrl-C'd deploy report itself as a failure.
285
+ */
286
+ const spawnAlchemy = async (invocation) => {
287
+ const commandLine = alchemyCommandLine(invocation);
288
+ return {
289
+ ...await spawnCommandLine(commandLine, invocation.redactedValues),
290
+ commandLine
291
+ };
292
+ };
293
+ /**
294
+ * One argument as the platform's shell reads it literally: single quotes for
295
+ * POSIX shells, double quotes for cmd.exe. cmd.exe expands `%VAR%` inside
296
+ * double quotes, and strips or expands `!` when delayed expansion is on; no
297
+ * quoting prevents either, so an argument containing them is not fully
298
+ * literal there.
299
+ */
300
+ function shellArg(arg, platform) {
301
+ if (platform === "win32") return /^[\w@+=:,./\\~-]+$/.test(arg) ? arg : `"${arg.replaceAll("\"", "\"\"")}"`;
302
+ return /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
303
+ }
304
+ /**
305
+ * The command a user runs from the invocation's directory to repeat a
306
+ * converge: the command line the adapter started, or, from an adapter that
307
+ * does not report one, `alchemy` with the same arguments.
308
+ */
309
+ function reproduceCommand(invocation, outcome, platform = process.platform) {
310
+ return (outcome?.commandLine === void 0 ? [
311
+ "alchemy",
312
+ invocation.action,
313
+ invocation.stackFileRelativePath,
314
+ "--yes",
315
+ "--stage",
316
+ invocation.stage
317
+ ] : [outcome.commandLine.command, ...outcome.commandLine.args]).map((arg) => shellArg(arg, platform)).join(" ");
318
+ }
319
+ /** Starts a resolved command line with stdin inherited and its output piped through redaction, and returns how it ended. */
320
+ function spawnCommandLine(line, redactedValues, outputs = process) {
321
+ return new Promise((resolve, reject) => {
322
+ const child = spawn(line.command, [...line.args], {
323
+ cwd: line.cwd,
324
+ stdio: [
325
+ "inherit",
326
+ "pipe",
327
+ "pipe"
328
+ ],
329
+ env: {
330
+ ...process.env,
331
+ ...line.env
332
+ }
333
+ });
334
+ const stdout = new StreamRedactor(redactedValues);
335
+ const stderr = new StreamRedactor(redactedValues);
336
+ const write = (stream, text) => {
337
+ if (text.length > 0) stream.write(text);
338
+ };
339
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => write(outputs.stdout, stdout.push(chunk)));
340
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => write(outputs.stderr, stderr.push(chunk)));
341
+ child.on("error", reject);
342
+ child.on("close", (exitCode, signal) => {
343
+ write(outputs.stdout, stdout.end());
344
+ write(outputs.stderr, stderr.end());
345
+ resolve({
346
+ exitCode,
347
+ signal
348
+ });
349
+ });
350
+ });
351
+ }
352
+ /**
183
353
  * The deploy/destroy executor — main.ts's pipeline orchestration with argv,
184
354
  * console, and exit codes removed: typed inputs in, structured results out.
185
355
  * Reached only by lazy import from deploy.ts/destroy.ts — this module's
@@ -192,54 +362,9 @@ function hasNoLocalDeployState(cwd) {
192
362
  const stateDir = path.join(cwd, ALCHEMY_STATE_DIR);
193
363
  return !(fs.existsSync(stateDir) && fs.readdirSync(stateDir).length > 0);
194
364
  }
195
- /**
196
- * Times each deploy step for the host's `onEvent`. A step still open when the
197
- * run fails is closed as failed, innermost first. A host `onEvent` that throws
198
- * is the host's bug and cannot fail the deploy.
199
- */
365
+ /** Times each deploy step for the host's `onEvent`. A step still open when the run fails is closed as failed, innermost first. */
200
366
  function deploySteps(onEvent) {
201
- const open = /* @__PURE__ */ new Map();
202
- const keyOf = (step) => step.name === "assemble-service" ? `${step.name}:${step.address}` : step.name;
203
- const emit = (event) => {
204
- try {
205
- onEvent?.(event);
206
- } catch {}
207
- };
208
- const finish = (step, outcome, data) => {
209
- const entry = open.get(keyOf(step));
210
- if (entry === void 0) return;
211
- open.delete(keyOf(step));
212
- const durationMs = Math.round(performance.now() - entry.startedAt);
213
- emit({
214
- kind: "step-finished",
215
- step,
216
- outcome,
217
- durationMs,
218
- data
219
- });
220
- };
221
- return {
222
- start(step) {
223
- open.set(keyOf(step), {
224
- step,
225
- startedAt: performance.now()
226
- });
227
- emit({
228
- kind: "step-started",
229
- step
230
- });
231
- },
232
- finish(step, data) {
233
- finish(step, "ok", data);
234
- },
235
- fail(step) {
236
- finish(step, "failed");
237
- },
238
- failOpen() {
239
- for (const { step } of [...open.values()].reverse()) finish(step, "failed");
240
- },
241
- emit
242
- };
367
+ return stepTracker((step) => step.name === "assemble-service" ? `${step.name}:${step.address}` : step.name === "apply-resource" ? `${step.name}:${step.resourceId}` : step.name, onEvent);
243
368
  }
244
369
  async function executeDeploy(input, deps, cwd) {
245
370
  const outcome = await runStackPipeline("deploy", {
@@ -253,7 +378,8 @@ async function executeDeploy(input, deps, cwd) {
253
378
  reportId: input.reportId,
254
379
  reportPath: resolveRunReportPath(input.reportPath, process.env[RUN_REPORT_FILE_ENV], cwd),
255
380
  steps: deploySteps(input.onEvent),
256
- redaction: new SecretRedaction(process.env)
381
+ signal: input.signal,
382
+ redaction: deps.redaction ?? new SecretRedaction(process.env)
257
383
  });
258
384
  if (!outcome.ok) return outcome;
259
385
  return ok({ summary: outcome.value });
@@ -270,6 +396,7 @@ async function executeDestroy(input, deps, cwd) {
270
396
  reportId: void 0,
271
397
  reportPath: void 0,
272
398
  steps: deploySteps(void 0),
399
+ signal: void 0,
273
400
  redaction: new SecretRedaction(process.env)
274
401
  });
275
402
  if (!outcome.ok) return outcome;
@@ -308,8 +435,8 @@ async function attachReporters(reporters, containers, redaction) {
308
435
  }
309
436
  }));
310
437
  }
311
- /** Every session's contribution to the alchemy child's environment, so reporting that happens inside the apply can find the run. */
312
- function reporterChildEnv(reporters, redaction) {
438
+ /** Every session's contribution to the apply's environment, so reporting that happens inside the apply can find the run. */
439
+ function reporterEnv(reporters, redaction) {
313
440
  const env = {};
314
441
  for (const { extensionId, reporter } of reporters) try {
315
442
  Object.assign(env, reporter.childEnv());
@@ -323,9 +450,9 @@ function reporterChildEnv(reporters, redaction) {
323
450
  function truncate(value, limit) {
324
451
  return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
325
452
  }
326
- /** An interrupted converge (the engine settled a Ctrl-C) — reported as `cancelled`, never as `failed`. */
453
+ /** An interrupted converge — reported as `cancelled`, never as `failed`. */
327
454
  function wasInterrupted(failure) {
328
- return typeof failure.meta?.["signal"] === "string";
455
+ return failure.code === "DEPLOY.INTERRUPTED" || typeof failure.meta?.["signal"] === "string";
329
456
  }
330
457
  /**
331
458
  * Ends every reporting session, whatever the run did. Sessions never reject
@@ -363,7 +490,7 @@ async function runStackPipeline(action, opts) {
363
490
  try {
364
491
  outcome = await runStackPipelineInner(action, opts, reporters);
365
492
  } catch (error) {
366
- opts.steps.failOpen();
493
+ opts.steps.closeOpen("failed");
367
494
  opts.steps.start({ name: "record" });
368
495
  const thrown = redactThrown(error, opts.redaction);
369
496
  await finishReporters(reporters, {
@@ -376,7 +503,7 @@ async function runStackPipeline(action, opts) {
376
503
  throw thrown;
377
504
  }
378
505
  if (!outcome.ok) outcome = notOk(redactError(outcome.failure, opts.redaction));
379
- if (!outcome.ok) opts.steps.failOpen();
506
+ if (!outcome.ok) opts.steps.closeOpen("failed");
380
507
  opts.steps.start({ name: "record" });
381
508
  await finishReporters(reporters, outcome.ok ? {
382
509
  ok: true,
@@ -399,9 +526,10 @@ async function runStackPipeline(action, opts) {
399
526
  else opts.steps.fail({ name: "record" });
400
527
  return outcome;
401
528
  }
402
- /** The pipeline both actions share: validate, resolve containers, preflight,
403
- * write the stack file, run alchemy against it, then the destroy-only
404
- * teardown/removal suffix. The value is only ever a summary for deploy. */
529
+ /** The pipeline both actions share: validate, resolve containers, then for
530
+ * deploy preflight and the in-process converge, and for destroy the stack
531
+ * file, the alchemy child and the teardown/removal suffix. The value is only
532
+ * ever a summary for deploy. */
405
533
  async function runStackPipelineInner(action, opts, reporters) {
406
534
  const { entry, config: composerConfig, name, environment, cwd, onEvent, deps, steps } = opts;
407
535
  steps.start({ name: "prepare" });
@@ -412,6 +540,13 @@ async function runStackPipelineInner(action, opts, reporters) {
412
540
  if (CliStructuredError.is(error)) return notOk(error);
413
541
  throw error;
414
542
  }
543
+ let appConvergeEntry;
544
+ if (action === "deploy") {
545
+ const loaded = await prepareAppConvergeEntry(deps, path.dirname(path.resolve(cwd, composerConfig.file)));
546
+ if (!loaded.ok) return loaded;
547
+ appConvergeEntry = loaded.value;
548
+ }
549
+ const platformCredentials = deps.credentials;
415
550
  if (action === "destroy" && hasNoLocalDeployState(cwd)) onEvent?.({
416
551
  kind: "no-local-deploy-state",
417
552
  cwd
@@ -420,7 +555,8 @@ async function runStackPipelineInner(action, opts, reporters) {
420
555
  let containers;
421
556
  let alchemyStage;
422
557
  const preflightPayloads = /* @__PURE__ */ new Map();
423
- let preflightTransportEnv = {};
558
+ const unset = [];
559
+ const preflightTransportEnv = {};
424
560
  try {
425
561
  pipeline = await runPipeline(entry, name, environment, cwd, composerConfig, {
426
562
  runAssembler: deps.runAssembler,
@@ -454,6 +590,7 @@ async function runStackPipelineInner(action, opts, reporters) {
454
590
  steps.finish({ name: "assemble" });
455
591
  const { graph, name: resolvedName } = pipeline;
456
592
  const config = pipeline.configSource.value;
593
+ if (action === "deploy") refuseSecretsInRootInput(graph.appConfigurationRead, opts.redaction.knownSecrets, "A deploy sends every plain value Load read to the platform as plain configuration, and never sends a secret that way.");
457
594
  steps.start({ name: "connect" });
458
595
  if (action === "deploy") reporters.push(...await beginReporters(config.extensions, {
459
596
  appName: resolvedName,
@@ -461,7 +598,7 @@ async function runStackPipelineInner(action, opts, reporters) {
461
598
  environment,
462
599
  cwd,
463
600
  reportId: opts.reportId,
464
- credentials: deps.credentials
601
+ credentials: platformCredentials
465
602
  }, opts.redaction));
466
603
  containers = /* @__PURE__ */ new Map();
467
604
  for (const extension of config.extensions) {
@@ -471,14 +608,14 @@ async function runStackPipelineInner(action, opts, reporters) {
471
608
  const instance = await extension.container.ensure({
472
609
  appName: resolvedName,
473
610
  environment
474
- }, deps.credentials);
611
+ }, platformCredentials);
475
612
  requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
476
613
  containers.set(extension.id, instance);
477
614
  } else {
478
615
  const instance = await extension.container.locate({
479
616
  appName: resolvedName,
480
617
  environment
481
- }, deps.credentials);
618
+ }, platformCredentials);
482
619
  if (instance === void 0) throw new CliStructuredError("DEPLOY.TARGET_NOT_FOUND", `Nothing deployed for ${resolvedName} in the environment ${environment}.`, { fix: "Deploy it first." });
483
620
  requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
484
621
  containers.set(extension.id, instance);
@@ -490,7 +627,6 @@ async function runStackPipelineInner(action, opts, reporters) {
490
627
  await attachReporters(reporters, containers, opts.redaction);
491
628
  alchemyStage = containers.get(config.state.extension)?.alchemyStage ?? environment;
492
629
  steps.finish({ name: "connect" });
493
- const unset = [];
494
630
  if (action === "deploy") {
495
631
  steps.start({ name: "preflight" });
496
632
  let checked = 0;
@@ -507,7 +643,7 @@ async function runStackPipelineInner(action, opts, reporters) {
507
643
  environment,
508
644
  configuration: pipeline.configuration,
509
645
  secrets: pipeline.secrets,
510
- credentials: deps.credentials,
646
+ credentials: platformCredentials,
511
647
  report
512
648
  });
513
649
  if (payload !== void 0) preflightPayloads.set(extension.id, payload);
@@ -515,11 +651,6 @@ async function runStackPipelineInner(action, opts, reporters) {
515
651
  throw toStructured("DEPLOY.PREFLIGHT_FAILED", error);
516
652
  }
517
653
  }
518
- try {
519
- preflightTransportEnv = preflightEnv(preflightPayloads);
520
- } catch (error) {
521
- throw toStructured("DEPLOY.PREFLIGHT_FAILED", error);
522
- }
523
654
  steps.finish({ name: "preflight" }, {
524
655
  checked,
525
656
  unset: unset.length
@@ -529,12 +660,18 @@ async function runStackPipelineInner(action, opts, reporters) {
529
660
  findings: { unset }
530
661
  });
531
662
  }
532
- for (const extension of config.extensions) preflightTransportEnv[preflightEnvVarName(extension.id)] ??= "";
533
- Object.assign(preflightTransportEnv, preflightFindingsEnv({ unset }));
663
+ if (action === "destroy") for (const extension of config.extensions) preflightTransportEnv[preflightEnvVarName(extension.id)] = "";
534
664
  } catch (error) {
535
665
  if (CliStructuredError.is(error)) return notOk(error);
536
666
  throw error;
537
667
  }
668
+ if (appConvergeEntry !== void 0) return convergeDeploy(opts, pipeline, appConvergeEntry, {
669
+ containers,
670
+ stage: alchemyStage,
671
+ preflightPayloads,
672
+ findings: { unset },
673
+ env: reporterEnv(reporters, opts.redaction)
674
+ });
538
675
  let stackPath;
539
676
  const resultFilePath = path.join(cwd, ".prisma-composer", `deployment-result-${String(process.pid)}-${randomUUID()}.json`);
540
677
  let handover;
@@ -543,8 +680,8 @@ async function runStackPipelineInner(action, opts, reporters) {
543
680
  handover = prepareSecondProcess({
544
681
  file: deployAppConfigurationFile(cwd, randomUUID()),
545
682
  appConfigurationRead: pipeline.graph.appConfigurationRead,
683
+ plainVariableText: {},
546
684
  nodeAddresses: nodeAddresses(pipeline.graph),
547
- secretsKeys: secretsKeys(pipeline.graph),
548
685
  knownSecrets: opts.redaction.knownSecrets
549
686
  });
550
687
  stackPath = writeStackFile({
@@ -567,7 +704,7 @@ async function runStackPipelineInner(action, opts, reporters) {
567
704
  containerEnv: containerEnv(containers),
568
705
  preflightEnv: preflightTransportEnv,
569
706
  env: {
570
- ...reporterChildEnv(reporters, opts.redaction),
707
+ ...reporterEnv(reporters, opts.redaction),
571
708
  ...handover.env,
572
709
  [DEPLOYMENT_RESULT_FILE_ENV]: resultFilePath
573
710
  },
@@ -634,7 +771,7 @@ async function runStackPipelineInner(action, opts, reporters) {
634
771
  const instance = containers.get(extension.id);
635
772
  if (instance === void 0) continue;
636
773
  try {
637
- await extension.container.remove(instance, deps.credentials);
774
+ await extension.container.remove(instance, platformCredentials);
638
775
  } catch (error) {
639
776
  throw toStructured("DEPLOY.CONTAINER_REMOVE_FAILED", error);
640
777
  }
@@ -644,7 +781,6 @@ async function runStackPipelineInner(action, opts, reporters) {
644
781
  if (CliStructuredError.is(error)) return notOk(error);
645
782
  throw error;
646
783
  }
647
- if (action === "deploy") return ok(redactSummary(readDeploymentSummary(resultFilePath), opts.redaction));
648
784
  return ok(void 0);
649
785
  } finally {
650
786
  try {
@@ -654,7 +790,104 @@ async function runStackPipelineInner(action, opts, reporters) {
654
790
  handover?.removeFile();
655
791
  }
656
792
  }
793
+ /** Loaded before anything is created, so a missing or incompatible install fails first. */
794
+ async function prepareAppConvergeEntry(deps, appDir) {
795
+ try {
796
+ return ok(deps.appConvergeEntry ?? await loadAppConvergeEntry(appDir));
797
+ } catch (error) {
798
+ if (CliStructuredError.is(error)) return notOk(error);
799
+ throw error;
800
+ }
801
+ }
802
+ /** The structured failure a converge that did not apply settles as. */
803
+ function convergeFailure(outcome, redact) {
804
+ switch (outcome.kind) {
805
+ case "interrupted": return new CliStructuredError("DEPLOY.INTERRUPTED", "The deploy was interrupted.", {
806
+ why: "It stopped while Alchemy planned or applied it. Resources it had already changed stay as they are.",
807
+ fix: "Deploy again to finish."
808
+ });
809
+ case "refused": return outcome.reason === "already-running" ? new CliStructuredError("DEPLOY.CONVERGE_RUNNING", "Another deploy is already running in this process.", {
810
+ why: "A deploy sets the process's environment and working directory while Alchemy runs, so two cannot overlap.",
811
+ fix: "Wait for the other deploy to finish, or run this one in its own process."
812
+ }) : new CliStructuredError("DEPLOY.WORKER_THREAD", "Deploy cannot run in a worker thread when its cwd is not the process working directory.", {
813
+ why: "Alchemy reads `.env` and keeps `.alchemy` in the working directory, and a worker thread cannot change it.",
814
+ fix: "Call deploy from the main thread, or with the process's working directory as its cwd."
815
+ });
816
+ case "failed": {
817
+ const cause = capFailureCause(redact(withComposerAdvice(convergeReasonsText(outcome.reasons))));
818
+ return new CliStructuredError("DEPLOY.ENGINE_FAILED", `Alchemy could not deploy the app.\n${cause}`, { meta: {
819
+ engineCause: cause,
820
+ reasons: outcome.reasons.map(({ tag, message }) => ({
821
+ tag,
822
+ message: redact(message)
823
+ }))
824
+ } });
825
+ }
826
+ }
827
+ return new CliStructuredError("DEPLOY.ENGINE_FAILED", "The converge ended with an outcome this Composer does not know.");
828
+ }
829
+ /**
830
+ * Deploy's converge: lowers the app with the containers and preflight
831
+ * payloads this run resolved, then plans and applies it in this process.
832
+ * The report hook runs inside the apply, here, so the summary comes back as
833
+ * a value.
834
+ */
835
+ async function convergeDeploy(opts, pipeline, entry, resolved) {
836
+ const { cwd, environment, steps } = opts;
837
+ const config = pipeline.configSource.value;
838
+ const env = resolved.env;
839
+ opts.redaction.addCredentialLookingValues(credentialLookingValues(env));
840
+ const redact = (text) => opts.redaction.redact(text);
841
+ let summary;
842
+ const root = pipeline.graph.root.node;
843
+ if (root.kind !== "module") throw new InternalError("runPipeline admitted a root that is not a module");
844
+ steps.start({ name: "apply" });
845
+ let stack;
846
+ try {
847
+ stack = entry.lower(root, config, {
848
+ name: pipeline.name,
849
+ environment,
850
+ appConfigurationRead: pipeline.graph.appConfigurationRead,
851
+ firstProcessNodeAddresses: nodeAddresses(pipeline.graph),
852
+ bundles: pipeline.assembled.bundles,
853
+ containers: resolved.containers,
854
+ preflightPayloads: resolved.preflightPayloads,
855
+ findings: resolved.findings,
856
+ credentials: opts.deps.credentials,
857
+ report: (result) => {
858
+ summary = toDeploymentSummary(result);
859
+ }
860
+ });
861
+ } catch (error) {
862
+ if (CliStructuredError.is(error)) return notOk(error);
863
+ return notOk(new CliStructuredError("DEPLOY.ENGINE_FAILED", redact(error instanceof Error ? error.message : String(error))));
864
+ }
865
+ const output = interactionMessages(steps, opts.redaction);
866
+ let outcome;
867
+ try {
868
+ outcome = await entry.converge({
869
+ operation: "deploy",
870
+ stack,
871
+ stage: resolved.stage,
872
+ cwd,
873
+ env,
874
+ signal: opts.signal,
875
+ onEvent: (event) => reportConvergeEvent(steps, event, redact, (resource) => ({
876
+ name: "apply-resource",
877
+ ...resource
878
+ })),
879
+ output: (text) => output.push(text)
880
+ });
881
+ } catch (error) {
882
+ return notOk(new CliStructuredError("DEPLOY.ENGINE_FAILED", redact(`Alchemy could not deploy the app.\n${error instanceof Error ? error.message : String(error)}`)));
883
+ } finally {
884
+ output.end();
885
+ }
886
+ if (outcome.kind !== "applied") return notOk(convergeFailure(outcome, redact));
887
+ steps.finish({ name: "apply" });
888
+ return ok(redactSummary(summary, opts.redaction));
889
+ }
657
890
  //#endregion
658
891
  export { executeDeploy, executeDestroy };
659
892
 
660
- //# sourceMappingURL=execute-deploy-destroy-DOzo2Psp-2iWcFbD9.mjs.map
893
+ //# sourceMappingURL=execute-deploy-destroy-DN16ETAk-CzORriUO.mjs.map