@prisma/composer-cli 0.38.0 → 0.39.0-dev.10

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-C_YkTIBF-RmqGOR45.mjs +88 -0
  2. package/dist/app-converge-C_YkTIBF-RmqGOR45.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-CpQLC3CA-Ct-PXoKN.mjs → deploy-Br1yvLe3.mjs} +341 -1082
  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-D-Qb6Yem-CvaY4xsk.mjs → dev-current-DANgmcle-RwunETUJ.mjs} +12 -18
  13. package/dist/dev-current-DANgmcle-RwunETUJ.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-BH6HQ6zZ.mjs → dist-C0OGaDnj.mjs} +4 -3
  17. package/dist/{dist-BH6HQ6zZ.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-C6EsdmLz-DqdToZ_i.mjs → execute-deploy-destroy-DIR9uvA_-Bk0HBMTz.mjs} +385 -141
  21. package/dist/execute-deploy-destroy-DIR9uvA_-Bk0HBMTz.mjs.map +1 -0
  22. package/dist/{execute-dev-gjIKYybU-hRndPEgC.mjs → execute-dev-Cu9_LsQi-CsyIqphZ.mjs} +450 -127
  23. package/dist/execute-dev-Cu9_LsQi-CsyIqphZ.mjs.map +1 -0
  24. package/dist/{execute-dev-current-tBKmDAjV-DOOMGrl5.mjs → execute-dev-current-Bs0lE_5--BU3A2hsC.mjs} +9 -6
  25. package/dist/{execute-dev-current-tBKmDAjV-DOOMGrl5.mjs.map → execute-dev-current-Bs0lE_5--BU3A2hsC.mjs.map} +1 -1
  26. package/dist/{redaction-Bf8FvTFH-D0dXGsO8.d.mts → family-DfwviKFj-CS1L-EvS.d.mts} +484 -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 +350 -270
  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-IL0MgmTX.mjs → list-deployed-slo4P7dl.mjs} +6 -5
  34. package/dist/list-deployed-slo4P7dl.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/{config-DiZaanS3.mjs → preflight-transport-2d6iIchu-ArIJUY1L.mjs} +11 -19
  38. package/dist/preflight-transport-2d6iIchu-ArIJUY1L.mjs.map +1 -0
  39. package/dist/{redaction-HnbkSFrK-CCKJNRwi.mjs → redaction-DY6eDC12-BrK1aSN5.mjs} +55 -262
  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 +11 -11
  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-Dk65W3Az.mjs +0 -140
  58. package/dist/app-configuration-file-CeJvBAti-Dk65W3Az.mjs.map +0 -1
  59. package/dist/config-DiZaanS3.mjs.map +0 -1
  60. package/dist/dev-current-D-Qb6Yem-CvaY4xsk.mjs.map +0 -1
  61. package/dist/dev-environment-name-6eEr5PW8-DpdGjmTb.mjs +0 -71
  62. package/dist/dev-environment-name-6eEr5PW8-DpdGjmTb.mjs.map +0 -1
  63. package/dist/execute-deploy-destroy-C6EsdmLz-DqdToZ_i.mjs.map +0 -1
  64. package/dist/execute-dev-gjIKYybU-hRndPEgC.mjs.map +0 -1
  65. package/dist/generate-dev-stack-BV_n-X9n-BDBjgphH.mjs +0 -100
  66. package/dist/generate-dev-stack-BV_n-X9n-BDBjgphH.mjs.map +0 -1
  67. package/dist/list-deployed-IL0MgmTX.mjs.map +0 -1
  68. package/dist/redaction-Bf8FvTFH-D0dXGsO8.d.mts.map +0 -1
  69. package/dist/redaction-HnbkSFrK-CCKJNRwi.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-OS_ix5g0-DSlHsv2p.mjs +0 -236
  73. package/dist/run-alchemy-OS_ix5g0-DSlHsv2p.mjs.map +0 -1
  74. package/dist/validate-environment-CpQLC3CA-Ct-PXoKN.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-CpQLC3CA-Ct-PXoKN.mjs";
2
- import { c as redactThrown, n as SecretRedaction, o as redactError, p as noComposerExportMessage, s as redactSummary } from "./redaction-HnbkSFrK-CCKJNRwi.mjs";
3
- import { i as CliStructuredError, n as ok, o as blindCast, r as okVoid, t as notOk } from "./result-sR7PBi61.mjs";
4
- import { c as toStructured, s as requireContainerForEnvironment } from "./dev-current-D-Qb6Yem-CvaY4xsk.mjs";
5
- import { i as spawnAlchemy, n as alchemyInvocation, r as reproduceCommand } from "./run-alchemy-OS_ix5g0-DSlHsv2p.mjs";
6
- import { n as preflightEnvVarName, r as containerEnv, t as preflightEnv } from "./config-DiZaanS3.mjs";
7
- import { i as removeLeftoverAppConfigurationFiles, r as prepareSecondProcess, t as deployAppConfigurationFile } from "./app-configuration-file-CeJvBAti-Dk65W3Az.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-DANgmcle-RwunETUJ.mjs";
9
+ import { t as loadAppConvergeEntry } from "./app-converge-C_YkTIBF-RmqGOR45.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-BiBkPWlB.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-C6EsdmLz.mjs
58
+ //#region ../../0-framework/3-tooling/cli/dist/execute-deploy-destroy-DIR9uvA_.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,53 +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
- };
367
+ return stepTracker((step) => step.name === "assemble-service" ? `${step.name}:${step.address}` : step.name === "apply-resource" ? `${step.name}:${step.resourceId}` : step.name, onEvent);
242
368
  }
243
369
  async function executeDeploy(input, deps, cwd) {
244
370
  const outcome = await runStackPipeline("deploy", {
@@ -252,7 +378,8 @@ async function executeDeploy(input, deps, cwd) {
252
378
  reportId: input.reportId,
253
379
  reportPath: resolveRunReportPath(input.reportPath, process.env[RUN_REPORT_FILE_ENV], cwd),
254
380
  steps: deploySteps(input.onEvent),
255
- redaction: new SecretRedaction(process.env)
381
+ signal: input.signal,
382
+ redaction: deps.redaction ?? new SecretRedaction(process.env)
256
383
  });
257
384
  if (!outcome.ok) return outcome;
258
385
  return ok({ summary: outcome.value });
@@ -269,6 +396,7 @@ async function executeDestroy(input, deps, cwd) {
269
396
  reportId: void 0,
270
397
  reportPath: void 0,
271
398
  steps: deploySteps(void 0),
399
+ signal: void 0,
272
400
  redaction: new SecretRedaction(process.env)
273
401
  });
274
402
  if (!outcome.ok) return outcome;
@@ -307,8 +435,8 @@ async function attachReporters(reporters, containers, redaction) {
307
435
  }
308
436
  }));
309
437
  }
310
- /** Every session's contribution to the alchemy child's environment, so reporting that happens inside the apply can find the run. */
311
- 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) {
312
440
  const env = {};
313
441
  for (const { extensionId, reporter } of reporters) try {
314
442
  Object.assign(env, reporter.childEnv());
@@ -322,9 +450,9 @@ function reporterChildEnv(reporters, redaction) {
322
450
  function truncate(value, limit) {
323
451
  return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
324
452
  }
325
- /** 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`. */
326
454
  function wasInterrupted(failure) {
327
- return typeof failure.meta?.["signal"] === "string";
455
+ return failure.code === "DEPLOY.INTERRUPTED" || typeof failure.meta?.["signal"] === "string";
328
456
  }
329
457
  /**
330
458
  * Ends every reporting session, whatever the run did. Sessions never reject
@@ -362,7 +490,7 @@ async function runStackPipeline(action, opts) {
362
490
  try {
363
491
  outcome = await runStackPipelineInner(action, opts, reporters);
364
492
  } catch (error) {
365
- opts.steps.failOpen();
493
+ opts.steps.closeOpen("failed");
366
494
  opts.steps.start({ name: "record" });
367
495
  const thrown = redactThrown(error, opts.redaction);
368
496
  await finishReporters(reporters, {
@@ -375,7 +503,7 @@ async function runStackPipeline(action, opts) {
375
503
  throw thrown;
376
504
  }
377
505
  if (!outcome.ok) outcome = notOk(redactError(outcome.failure, opts.redaction));
378
- if (!outcome.ok) opts.steps.failOpen();
506
+ if (!outcome.ok) opts.steps.closeOpen("failed");
379
507
  opts.steps.start({ name: "record" });
380
508
  await finishReporters(reporters, outcome.ok ? {
381
509
  ok: true,
@@ -398,9 +526,10 @@ async function runStackPipeline(action, opts) {
398
526
  else opts.steps.fail({ name: "record" });
399
527
  return outcome;
400
528
  }
401
- /** The pipeline both actions share: validate, resolve containers, preflight,
402
- * write the stack file, run alchemy against it, then the destroy-only
403
- * 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. */
404
533
  async function runStackPipelineInner(action, opts, reporters) {
405
534
  const { entry, config: composerConfig, name, environment, cwd, onEvent, deps, steps } = opts;
406
535
  steps.start({ name: "prepare" });
@@ -411,6 +540,13 @@ async function runStackPipelineInner(action, opts, reporters) {
411
540
  if (CliStructuredError.is(error)) return notOk(error);
412
541
  throw error;
413
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;
414
550
  if (action === "destroy" && hasNoLocalDeployState(cwd)) onEvent?.({
415
551
  kind: "no-local-deploy-state",
416
552
  cwd
@@ -419,7 +555,8 @@ async function runStackPipelineInner(action, opts, reporters) {
419
555
  let containers;
420
556
  let alchemyStage;
421
557
  const preflightPayloads = /* @__PURE__ */ new Map();
422
- let preflightTransportEnv = {};
558
+ const unset = [];
559
+ const preflightTransportEnv = {};
423
560
  try {
424
561
  pipeline = await runPipeline(entry, name, environment, cwd, composerConfig, {
425
562
  runAssembler: deps.runAssembler,
@@ -453,6 +590,7 @@ async function runStackPipelineInner(action, opts, reporters) {
453
590
  steps.finish({ name: "assemble" });
454
591
  const { graph, name: resolvedName } = pipeline;
455
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.");
456
594
  steps.start({ name: "connect" });
457
595
  if (action === "deploy") reporters.push(...await beginReporters(config.extensions, {
458
596
  appName: resolvedName,
@@ -460,7 +598,7 @@ async function runStackPipelineInner(action, opts, reporters) {
460
598
  environment,
461
599
  cwd,
462
600
  reportId: opts.reportId,
463
- credentials: deps.credentials
601
+ credentials: platformCredentials
464
602
  }, opts.redaction));
465
603
  containers = /* @__PURE__ */ new Map();
466
604
  for (const extension of config.extensions) {
@@ -470,14 +608,14 @@ async function runStackPipelineInner(action, opts, reporters) {
470
608
  const instance = await extension.container.ensure({
471
609
  appName: resolvedName,
472
610
  environment
473
- }, deps.credentials);
611
+ }, platformCredentials);
474
612
  requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
475
613
  containers.set(extension.id, instance);
476
614
  } else {
477
615
  const instance = await extension.container.locate({
478
616
  appName: resolvedName,
479
617
  environment
480
- }, deps.credentials);
618
+ }, platformCredentials);
481
619
  if (instance === void 0) throw new CliStructuredError("DEPLOY.TARGET_NOT_FOUND", `Nothing deployed for ${resolvedName} in the environment ${environment}.`, { fix: "Deploy it first." });
482
620
  requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
483
621
  containers.set(extension.id, instance);
@@ -491,9 +629,10 @@ async function runStackPipelineInner(action, opts, reporters) {
491
629
  steps.finish({ name: "connect" });
492
630
  if (action === "deploy") {
493
631
  steps.start({ name: "preflight" });
494
- const counts = {};
632
+ let checked = 0;
495
633
  const report = (reported) => {
496
- for (const [key, value] of Object.entries(reported)) counts[key] = (counts[key] ?? 0) + value;
634
+ checked += reported.checked;
635
+ unset.push(...reported.unset.map((variable) => redactUnsetPlatformVariable(variable, opts.redaction)));
497
636
  };
498
637
  for (const extension of config.extensions) {
499
638
  if (extension.preflight === void 0) continue;
@@ -504,7 +643,7 @@ async function runStackPipelineInner(action, opts, reporters) {
504
643
  environment,
505
644
  configuration: pipeline.configuration,
506
645
  secrets: pipeline.secrets,
507
- credentials: deps.credentials,
646
+ credentials: platformCredentials,
508
647
  report
509
648
  });
510
649
  if (payload !== void 0) preflightPayloads.set(extension.id, payload);
@@ -512,18 +651,27 @@ async function runStackPipelineInner(action, opts, reporters) {
512
651
  throw toStructured("DEPLOY.PREFLIGHT_FAILED", error);
513
652
  }
514
653
  }
515
- try {
516
- preflightTransportEnv = preflightEnv(preflightPayloads);
517
- } catch (error) {
518
- throw toStructured("DEPLOY.PREFLIGHT_FAILED", error);
519
- }
520
- steps.finish({ name: "preflight" }, counts);
654
+ steps.finish({ name: "preflight" }, {
655
+ checked,
656
+ unset: unset.length
657
+ });
658
+ if (unset.length > 0) steps.emit({
659
+ kind: "preflight-findings",
660
+ findings: { unset }
661
+ });
521
662
  }
522
- for (const extension of config.extensions) preflightTransportEnv[preflightEnvVarName(extension.id)] ??= "";
663
+ if (action === "destroy") for (const extension of config.extensions) preflightTransportEnv[preflightEnvVarName(extension.id)] = "";
523
664
  } catch (error) {
524
665
  if (CliStructuredError.is(error)) return notOk(error);
525
666
  throw error;
526
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
+ });
527
675
  let stackPath;
528
676
  const resultFilePath = path.join(cwd, ".prisma-composer", `deployment-result-${String(process.pid)}-${randomUUID()}.json`);
529
677
  let handover;
@@ -532,8 +680,8 @@ async function runStackPipelineInner(action, opts, reporters) {
532
680
  handover = prepareSecondProcess({
533
681
  file: deployAppConfigurationFile(cwd, randomUUID()),
534
682
  appConfigurationRead: pipeline.graph.appConfigurationRead,
683
+ plainVariableText: {},
535
684
  nodeAddresses: nodeAddresses(pipeline.graph),
536
- secretsKeys: secretsKeys(pipeline.graph),
537
685
  knownSecrets: opts.redaction.knownSecrets
538
686
  });
539
687
  stackPath = writeStackFile({
@@ -556,7 +704,7 @@ async function runStackPipelineInner(action, opts, reporters) {
556
704
  containerEnv: containerEnv(containers),
557
705
  preflightEnv: preflightTransportEnv,
558
706
  env: {
559
- ...reporterChildEnv(reporters, opts.redaction),
707
+ ...reporterEnv(reporters, opts.redaction),
560
708
  ...handover.env,
561
709
  [DEPLOYMENT_RESULT_FILE_ENV]: resultFilePath
562
710
  },
@@ -623,7 +771,7 @@ async function runStackPipelineInner(action, opts, reporters) {
623
771
  const instance = containers.get(extension.id);
624
772
  if (instance === void 0) continue;
625
773
  try {
626
- await extension.container.remove(instance, deps.credentials);
774
+ await extension.container.remove(instance, platformCredentials);
627
775
  } catch (error) {
628
776
  throw toStructured("DEPLOY.CONTAINER_REMOVE_FAILED", error);
629
777
  }
@@ -633,7 +781,6 @@ async function runStackPipelineInner(action, opts, reporters) {
633
781
  if (CliStructuredError.is(error)) return notOk(error);
634
782
  throw error;
635
783
  }
636
- if (action === "deploy") return ok(redactSummary(readDeploymentSummary(resultFilePath), opts.redaction));
637
784
  return ok(void 0);
638
785
  } finally {
639
786
  try {
@@ -643,7 +790,104 @@ async function runStackPipelineInner(action, opts, reporters) {
643
790
  handover?.removeFile();
644
791
  }
645
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
+ }
646
890
  //#endregion
647
891
  export { executeDeploy, executeDestroy };
648
892
 
649
- //# sourceMappingURL=execute-deploy-destroy-C6EsdmLz-DqdToZ_i.mjs.map
893
+ //# sourceMappingURL=execute-deploy-destroy-DIR9uvA_-Bk0HBMTz.mjs.map