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

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 (55) hide show
  1. package/dist/{app-converge-bS1l9jIf-B1FOgxBQ.mjs → app-converge-CHMILMYi-Duhv9T-w.mjs} +5 -5
  2. package/dist/app-converge-CHMILMYi-Duhv9T-w.mjs.map +1 -0
  3. package/dist/{composer-config-QKdY85G--CEXrb2Uc.mjs → composer-config-aL0W4HPG-CTpDJKz4.mjs} +3 -3
  4. package/dist/composer-config-aL0W4HPG-CTpDJKz4.mjs.map +1 -0
  5. package/dist/{deploy-Br1yvLe3.mjs → deploy-Cu7Wtrf0.mjs} +6 -6
  6. package/dist/deploy-Cu7Wtrf0.mjs.map +1 -0
  7. package/dist/{dev-converge-messages-DML4rTz7-B6uxtpZG.mjs → dev-converge-messages-CElmPylA-6X7D08mQ.mjs} +6 -6
  8. package/dist/dev-converge-messages-CElmPylA-6X7D08mQ.mjs.map +1 -0
  9. package/dist/dev-converge-worker.mjs +4 -4
  10. package/dist/dev-converge-worker.mjs.map +1 -1
  11. package/dist/{dev-current-lAlj53eX-DvAHNZFo.mjs → dev-current-C7R8uqyQ-CgyoTX9q.mjs} +7 -7
  12. package/dist/dev-current-C7R8uqyQ-CgyoTX9q.mjs.map +1 -0
  13. package/dist/{dev-environment-name-6eEr5PW8-CCY7WNWz.mjs → dev-environment-name-6eEr5PW8-DSJ7HrEe.mjs} +2 -3
  14. package/dist/{dev-environment-name-6eEr5PW8-CCY7WNWz.mjs.map → dev-environment-name-6eEr5PW8-DSJ7HrEe.mjs.map} +1 -1
  15. package/dist/{dist-C0OGaDnj.mjs → dist-CZTXNHtS.mjs} +1 -2
  16. package/dist/{dist-C0OGaDnj.mjs.map → dist-CZTXNHtS.mjs.map} +1 -1
  17. package/dist/execute-deploy-destroy-BIRdFfwR-Czj9JB8M.mjs +517 -0
  18. package/dist/execute-deploy-destroy-BIRdFfwR-Czj9JB8M.mjs.map +1 -0
  19. package/dist/{execute-dev-DnVmNpc1-BzK9Qns_.mjs → execute-dev-D9PxdbV3-D-pdqLmO.mjs} +11 -13
  20. package/dist/execute-dev-D9PxdbV3-D-pdqLmO.mjs.map +1 -0
  21. package/dist/{execute-dev-current-CZdmxVQ4-DxDflvNG.mjs → execute-dev-current-BghQ0HLe-BY5COM8c.mjs} +6 -7
  22. package/dist/{execute-dev-current-CZdmxVQ4-DxDflvNG.mjs.map → execute-dev-current-BghQ0HLe-BY5COM8c.mjs.map} +1 -1
  23. package/dist/{family-DfwviKFj-CS1L-EvS.d.mts → family-5lQ0X01--mh7Vm2zv.d.mts} +74 -129
  24. package/dist/family-5lQ0X01--mh7Vm2zv.d.mts.map +1 -0
  25. package/dist/family.d.mts +1 -1
  26. package/dist/family.mjs +17 -11
  27. package/dist/family.mjs.map +1 -1
  28. package/dist/{list-deployed-D6vTzpWu.mjs → list-deployed-COZmPVO2.mjs} +3 -3
  29. package/dist/{list-deployed-D6vTzpWu.mjs.map → list-deployed-COZmPVO2.mjs.map} +1 -1
  30. package/dist/{local-target-CZzICh5R.mjs → local-target-bTjNRplR.mjs} +31 -3
  31. package/dist/local-target-bTjNRplR.mjs.map +1 -0
  32. package/dist/{redaction-DY6eDC12-BrK1aSN5.mjs → redaction-DHaXoToJ-zcuc7Sgf.mjs} +5 -5
  33. package/dist/redaction-DHaXoToJ-zcuc7Sgf.mjs.map +1 -0
  34. package/dist/{steps-BZXNqW6U-BM2Aa8Bp.mjs → steps-Det-FSAL-4BEaFT3G.mjs} +5 -118
  35. package/dist/steps-Det-FSAL-4BEaFT3G.mjs.map +1 -0
  36. package/dist/testing.d.mts +1 -1
  37. package/dist/{validate-environment-DCZiNSlR-idVge-kq.mjs → validate-environment-BevPErw8-BRVXeBjT.mjs} +6 -6
  38. package/dist/{validate-environment-DCZiNSlR-idVge-kq.mjs.map → validate-environment-BevPErw8-BRVXeBjT.mjs.map} +1 -1
  39. package/package.json +7 -8
  40. package/dist/app-config-CErnR6NK-DnKH4Kqc.mjs +0 -32
  41. package/dist/app-config-CErnR6NK-DnKH4Kqc.mjs.map +0 -1
  42. package/dist/app-converge-bS1l9jIf-B1FOgxBQ.mjs.map +0 -1
  43. package/dist/composer-config-QKdY85G--CEXrb2Uc.mjs.map +0 -1
  44. package/dist/deploy-Br1yvLe3.mjs.map +0 -1
  45. package/dist/dev-converge-messages-DML4rTz7-B6uxtpZG.mjs.map +0 -1
  46. package/dist/dev-current-lAlj53eX-DvAHNZFo.mjs.map +0 -1
  47. package/dist/execute-deploy-destroy-DN16ETAk-CzORriUO.mjs +0 -893
  48. package/dist/execute-deploy-destroy-DN16ETAk-CzORriUO.mjs.map +0 -1
  49. package/dist/execute-dev-DnVmNpc1-BzK9Qns_.mjs.map +0 -1
  50. package/dist/family-DfwviKFj-CS1L-EvS.d.mts.map +0 -1
  51. package/dist/local-target-CZzICh5R.mjs.map +0 -1
  52. package/dist/preflight-transport-2d6iIchu-ArIJUY1L.mjs +0 -56
  53. package/dist/preflight-transport-2d6iIchu-ArIJUY1L.mjs.map +0 -1
  54. package/dist/redaction-DY6eDC12-BrK1aSN5.mjs.map +0 -1
  55. package/dist/steps-BZXNqW6U-BM2Aa8Bp.mjs.map +0 -1
@@ -1,893 +0,0 @@
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";
13
- import * as fs from "node:fs";
14
- import * as path from "node:path";
15
- import { randomUUID } from "node:crypto";
16
- import spawn from "cross-spawn";
17
- //#region ../../0-framework/3-tooling/cli/dist/run-report-CmBz2-xc.mjs
18
- /** Names the file to write the run report to, when `--report` is not passed. */
19
- const RUN_REPORT_FILE_ENV = "PRISMA_COMPOSER_REPORT_FILE";
20
- function toRunReport(input) {
21
- return {
22
- version: 2,
23
- outcome: input.failure === void 0 ? "succeeded" : "failed",
24
- app: input.summary?.app ?? null,
25
- environment: input.environment,
26
- nodes: input.summary?.nodes ?? [],
27
- failure: input.failure ?? null
28
- };
29
- }
30
- /**
31
- * The path to write to: the `--report` flag first, then the env var. Relative
32
- * paths resolve against the deploy's cwd. `undefined` means no report was
33
- * asked for, which is the common case and writes nothing.
34
- */
35
- function resolveRunReportPath(flag, env, cwd) {
36
- const requested = flag !== void 0 && flag.length > 0 ? flag : env;
37
- if (requested === void 0 || requested.length === 0) return void 0;
38
- return path.resolve(cwd, requested);
39
- }
40
- /**
41
- * Writes the report, creating the parent directory if needed. A write failure
42
- * warns and returns false rather than failing a deploy that already
43
- * converged — but it is never silent, because the operator asked for this
44
- * file and a consumer is waiting on it.
45
- */
46
- function writeRunReport(filePath, report) {
47
- try {
48
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
49
- fs.writeFileSync(filePath, `${JSON.stringify(report, null, 2)}\n`);
50
- return true;
51
- } catch (error) {
52
- const detail = error instanceof Error ? error.message : String(error);
53
- console.warn(`\nCould not write the run report to ${filePath}: ${detail}`);
54
- return false;
55
- }
56
- }
57
- //#endregion
58
- //#region ../../0-framework/3-tooling/cli/dist/execute-deploy-destroy-DN16ETAk.mjs
59
- /** Pipeline step 6: writes a regenerated-every-run, independently runnable stack module at `.prisma-composer/alchemy.run.ts`. */
60
- const GENERATED_DIR = ".prisma-composer";
61
- const GENERATED_FILE = "alchemy.run.ts";
62
- /** A relative import specifier from `.prisma-composer/alchemy.run.ts` to `target` (posix separators). */
63
- function relativeImportSpecifier(generatedDir, target) {
64
- const rel = path.relative(generatedDir, target).split(path.sep).join("/");
65
- return rel.startsWith(".") ? rel : `./${rel}`;
66
- }
67
- function quote(value) {
68
- return JSON.stringify(value);
69
- }
70
- function renderBundle(bundle) {
71
- return `{ dir: ${quote(bundle.dir)}, entry: ${quote(bundle.entry)} }`;
72
- }
73
- function renderOptions(input) {
74
- const lines = [];
75
- lines.push(` name: ${quote(input.name)},`);
76
- lines.push(` environment: ${quote(input.environment)},`);
77
- lines.push(" appConfigurationRead: file.appConfigurationRead,");
78
- lines.push(" firstProcessNodeAddresses: file.nodeAddresses,");
79
- lines.push(" bundles: {");
80
- for (const [id, bundle] of Object.entries(input.assembled.bundles)) lines.push(` ${quote(id)}: ${renderBundle(bundle)},`);
81
- lines.push(" },");
82
- lines.push(" report: report.deploymentReport,");
83
- return lines.join("\n");
84
- }
85
- /** Renders the stack module's source (tests assert on it without touching disk) — uses `//` headers, not a block comment, since a cwd path with a star-slash could close one early. */
86
- function renderStackFile(input) {
87
- const generatedDir = path.join(input.cwd, GENERATED_DIR);
88
- const appImport = relativeImportSpecifier(generatedDir, input.entryPath);
89
- const configImport = relativeImportSpecifier(generatedDir, input.configFile);
90
- return `// Generated by Composer's deploy and destroy operations — overwritten on every
91
- // run; do not edit by hand. Runnable from ${quote(input.cwd)} WITH the env the
92
- // CLI passes its child (the PRISMA_COMPOSER_CONTAINER_*/_PREFLIGHT_* vars and the app configuration file —
93
- // without them lower() refuses because no container is resolved), by the
94
- // command Composer starts, which a failed run prints:
95
- //
96
- // <node> <bin of the alchemy @prisma/composer depends on> deploy ${GENERATED_DIR}/${GENERATED_FILE} --yes --stage <stage>
97
- //
98
- // bisects a CLI bug from an Alchemy bug (deploy-cli.md § Implementation decisions).
99
- // It runs no config adapter: it reads what the first process's Load read from the app configuration file named in PRISMA_COMPOSER_APP_CONFIGURATION_FILE.
100
- import { lower } from '@prisma/composer/deploy';
101
- import * as report from '@prisma/composer/report';
102
- import { readAppConfigurationFile } from '@prisma/composer/internal/app-configuration-file';
103
- import prismaConfig from ${quote(configImport)};
104
- import app from ${quote(appImport)};
105
-
106
- const config = prismaConfig.composer;
107
- if (config === undefined) {
108
- throw new Error(${quote(noComposerExportMessage(input.configFile))});
109
- }
110
-
111
- // The app's own @prisma/composer may predate the failure recorder.
112
- report.captureEngineFailure?.();
113
-
114
- const file = readAppConfigurationFile(process.env);
115
-
116
- export default lower(app, config, {
117
- ${renderOptions(input)}
118
- });
119
- `;
120
- }
121
- /** Writes the stack file, returning its absolute path. */
122
- function writeStackFile(input) {
123
- const generatedDir = path.join(input.cwd, GENERATED_DIR);
124
- fs.mkdirSync(generatedDir, { recursive: true });
125
- const filePath = path.join(generatedDir, GENERATED_FILE);
126
- fs.writeFileSync(filePath, renderStackFile(input));
127
- return filePath;
128
- }
129
- const GENERATED_STACK_RELATIVE_PATH = path.join(GENERATED_DIR, GENERATED_FILE);
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
- /**
353
- * The deploy/destroy executor — main.ts's pipeline orchestration with argv,
354
- * console, and exit codes removed: typed inputs in, structured results out.
355
- * Reached only by lazy import from deploy.ts/destroy.ts — this module's
356
- * static graph transitively loads alchemy's provider tree, so the control
357
- * entry must never import it statically.
358
- */
359
- const ALCHEMY_STATE_DIR = ".alchemy";
360
- /** Destroy guardrail (moved from main.ts): true when `<cwd>/.alchemy` is missing or empty — likely wrong directory or nothing deployed yet. */
361
- function hasNoLocalDeployState(cwd) {
362
- const stateDir = path.join(cwd, ALCHEMY_STATE_DIR);
363
- return !(fs.existsSync(stateDir) && fs.readdirSync(stateDir).length > 0);
364
- }
365
- /** Times each deploy step for the host's `onEvent`. A step still open when the run fails is closed as failed, innermost first. */
366
- function deploySteps(onEvent) {
367
- return stepTracker((step) => step.name === "assemble-service" ? `${step.name}:${step.address}` : step.name === "apply-resource" ? `${step.name}:${step.resourceId}` : step.name, onEvent);
368
- }
369
- async function executeDeploy(input, deps, cwd) {
370
- const outcome = await runStackPipeline("deploy", {
371
- entry: input.entry,
372
- config: input.config,
373
- name: input.name,
374
- environment: input.environment ?? "production",
375
- cwd,
376
- onEvent: void 0,
377
- deps,
378
- reportId: input.reportId,
379
- reportPath: resolveRunReportPath(input.reportPath, process.env[RUN_REPORT_FILE_ENV], cwd),
380
- steps: deploySteps(input.onEvent),
381
- signal: input.signal,
382
- redaction: deps.redaction ?? new SecretRedaction(process.env)
383
- });
384
- if (!outcome.ok) return outcome;
385
- return ok({ summary: outcome.value });
386
- }
387
- async function executeDestroy(input, deps, cwd) {
388
- const outcome = await runStackPipeline("destroy", {
389
- entry: input.entry,
390
- config: input.config,
391
- name: input.name,
392
- environment: input.environment,
393
- cwd,
394
- onEvent: input.onEvent,
395
- deps,
396
- reportId: void 0,
397
- reportPath: void 0,
398
- steps: deploySteps(void 0),
399
- signal: void 0,
400
- redaction: new SecretRedaction(process.env)
401
- });
402
- if (!outcome.ok) return outcome;
403
- return okVoid();
404
- }
405
- /**
406
- * Opens a session per extension that declares a reporter. A `begin` that
407
- * throws costs that extension its reporting and nothing else — the deploy
408
- * has not started, and refusing to run it because an observer failed would
409
- * invert the relationship.
410
- */
411
- async function beginReporters(extensions, context, redaction) {
412
- return (await Promise.all(extensions.map(async (extension) => {
413
- if (extension.reporter === void 0) return void 0;
414
- try {
415
- const reporter = await extension.reporter.begin(context);
416
- return reporter === void 0 ? void 0 : {
417
- extensionId: extension.id,
418
- reporter
419
- };
420
- } catch (error) {
421
- const detail = error instanceof Error ? error.message : String(error);
422
- console.warn(`\nCould not start deploy reporting for ${extension.id}: ${redaction.redact(detail)}`);
423
- return;
424
- }
425
- }))).filter((entry) => entry !== void 0);
426
- }
427
- /** Hands each session its own extension's resolved container, so it can attach the run to what that container names. */
428
- async function attachReporters(reporters, containers, redaction) {
429
- await Promise.all(reporters.map(async ({ extensionId, reporter }) => {
430
- try {
431
- await reporter.attach({ container: containers.get(extensionId) });
432
- } catch (error) {
433
- const detail = error instanceof Error ? error.message : String(error);
434
- console.warn(`\nCould not attach this deploy to its project for ${extensionId}: ${redaction.redact(detail)}`);
435
- }
436
- }));
437
- }
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) {
440
- const env = {};
441
- for (const { extensionId, reporter } of reporters) try {
442
- Object.assign(env, reporter.childEnv());
443
- } catch (error) {
444
- const detail = error instanceof Error ? error.message : String(error);
445
- console.warn(`\nCould not pass deploy reporting into the apply for ${extensionId}: ${redaction.redact(detail)}`);
446
- }
447
- return env;
448
- }
449
- /** `failingStep` is capped at 500 by the platform and `errorMessage` at 5000; truncating here keeps a long message from costing the whole report. */
450
- function truncate(value, limit) {
451
- return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
452
- }
453
- /** An interrupted converge — reported as `cancelled`, never as `failed`. */
454
- function wasInterrupted(failure) {
455
- return failure.code === "DEPLOY.INTERRUPTED" || typeof failure.meta?.["signal"] === "string";
456
- }
457
- /**
458
- * Ends every reporting session, whatever the run did. Sessions never reject
459
- * by contract, but a buggy one must not turn a converged deploy into a
460
- * failure — so this swallows anyway, and reports each session independently
461
- * so one bad implementation cannot silence another.
462
- */
463
- async function finishReporters(reporters, outcome, redaction) {
464
- const entities = outcome.summary?.nodes.flatMap((node) => node.entities) ?? [];
465
- await Promise.all(reporters.map(async ({ reporter }) => {
466
- try {
467
- await reporter.finish({
468
- ok: outcome.ok,
469
- cancelled: outcome.cancelled,
470
- failingStep: outcome.code === void 0 ? void 0 : truncate(outcome.code, 500),
471
- errorMessage: outcome.message === void 0 ? void 0 : truncate(outcome.message, 5e3),
472
- entities
473
- });
474
- } catch (error) {
475
- const detail = error instanceof Error ? error.message : String(error);
476
- console.warn(`\nCould not report this deploy's outcome: ${redaction.redact(detail)}`);
477
- }
478
- }));
479
- }
480
- /**
481
- * Owns the reporting sessions around the pipeline: the inner run opens them
482
- * once it knows which extensions are configured, and this closes them on
483
- * every exit path — a returned failure, a success, or a thrown defect — as
484
- * the `record` step, which also writes the run report.
485
- * Nothing here can change what the pipeline returns.
486
- */
487
- async function runStackPipeline(action, opts) {
488
- const reporters = [];
489
- let outcome;
490
- try {
491
- outcome = await runStackPipelineInner(action, opts, reporters);
492
- } catch (error) {
493
- opts.steps.closeOpen("failed");
494
- opts.steps.start({ name: "record" });
495
- const thrown = redactThrown(error, opts.redaction);
496
- await finishReporters(reporters, {
497
- ok: false,
498
- cancelled: false,
499
- code: "DEPLOY.UNEXPECTED",
500
- message: thrown.message
501
- }, opts.redaction);
502
- opts.steps.finish({ name: "record" });
503
- throw thrown;
504
- }
505
- if (!outcome.ok) outcome = notOk(redactError(outcome.failure, opts.redaction));
506
- if (!outcome.ok) opts.steps.closeOpen("failed");
507
- opts.steps.start({ name: "record" });
508
- await finishReporters(reporters, outcome.ok ? {
509
- ok: true,
510
- cancelled: false,
511
- summary: outcome.value
512
- } : {
513
- ok: false,
514
- cancelled: wasInterrupted(outcome.failure),
515
- code: outcome.failure.code,
516
- message: outcome.failure.message
517
- }, opts.redaction);
518
- if (opts.reportPath === void 0 || writeRunReport(opts.reportPath, toRunReport({
519
- summary: outcome.ok ? outcome.value : void 0,
520
- environment: opts.environment,
521
- failure: outcome.ok ? void 0 : {
522
- code: outcome.failure.code,
523
- message: outcome.failure.message
524
- }
525
- }))) opts.steps.finish({ name: "record" });
526
- else opts.steps.fail({ name: "record" });
527
- return outcome;
528
- }
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. */
533
- async function runStackPipelineInner(action, opts, reporters) {
534
- const { entry, config: composerConfig, name, environment, cwd, onEvent, deps, steps } = opts;
535
- steps.start({ name: "prepare" });
536
- removeLeftoverAppConfigurationFiles(cwd);
537
- try {
538
- validateEnvironmentName(environment);
539
- } catch (error) {
540
- if (CliStructuredError.is(error)) return notOk(error);
541
- throw error;
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;
550
- if (action === "destroy" && hasNoLocalDeployState(cwd)) onEvent?.({
551
- kind: "no-local-deploy-state",
552
- cwd
553
- });
554
- let pipeline;
555
- let containers;
556
- let alchemyStage;
557
- const preflightPayloads = /* @__PURE__ */ new Map();
558
- const unset = [];
559
- const preflightTransportEnv = {};
560
- try {
561
- pipeline = await runPipeline(entry, name, environment, cwd, composerConfig, {
562
- runAssembler: deps.runAssembler,
563
- readSecrets: action === "deploy",
564
- redaction: opts.redaction,
565
- onEvent: (event) => {
566
- switch (event.kind) {
567
- case "loaded":
568
- steps.finish({ name: "prepare" });
569
- steps.start({ name: "assemble" });
570
- return;
571
- case "service-started":
572
- steps.start({
573
- name: "assemble-service",
574
- address: event.address
575
- });
576
- return;
577
- case "service-assembled":
578
- steps.finish({
579
- name: "assemble-service",
580
- address: event.address
581
- }, event.data);
582
- return;
583
- }
584
- }
585
- }, action === "destroy" ? (error) => new CliStructuredError("DEPLOY.BUILD_REQUIRED", error.message, {
586
- why: "destroy evaluates the same stack program as deploy, which packages the built artifacts — so the app must be built first.",
587
- fix: "Run the build, then retry the destroy.",
588
- cause: error
589
- }) : void 0);
590
- steps.finish({ name: "assemble" });
591
- const { graph, name: resolvedName } = pipeline;
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.");
594
- steps.start({ name: "connect" });
595
- if (action === "deploy") reporters.push(...await beginReporters(config.extensions, {
596
- appName: resolvedName,
597
- graph,
598
- environment,
599
- cwd,
600
- reportId: opts.reportId,
601
- credentials: platformCredentials
602
- }, opts.redaction));
603
- containers = /* @__PURE__ */ new Map();
604
- for (const extension of config.extensions) {
605
- if (extension.container === void 0) continue;
606
- try {
607
- if (action === "deploy") {
608
- const instance = await extension.container.ensure({
609
- appName: resolvedName,
610
- environment
611
- }, platformCredentials);
612
- requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
613
- containers.set(extension.id, instance);
614
- } else {
615
- const instance = await extension.container.locate({
616
- appName: resolvedName,
617
- environment
618
- }, platformCredentials);
619
- if (instance === void 0) throw new CliStructuredError("DEPLOY.TARGET_NOT_FOUND", `Nothing deployed for ${resolvedName} in the environment ${environment}.`, { fix: "Deploy it first." });
620
- requireContainerForEnvironment(action, extension.id, extension.container, instance, environment);
621
- containers.set(extension.id, instance);
622
- }
623
- } catch (error) {
624
- throw toStructured("DEPLOY.CONTAINER_FAILED", error);
625
- }
626
- }
627
- await attachReporters(reporters, containers, opts.redaction);
628
- alchemyStage = containers.get(config.state.extension)?.alchemyStage ?? environment;
629
- steps.finish({ name: "connect" });
630
- if (action === "deploy") {
631
- steps.start({ name: "preflight" });
632
- let checked = 0;
633
- const report = (reported) => {
634
- checked += reported.checked;
635
- unset.push(...reported.unset.map((variable) => redactUnsetPlatformVariable(variable, opts.redaction)));
636
- };
637
- for (const extension of config.extensions) {
638
- if (extension.preflight === void 0) continue;
639
- try {
640
- const payload = await extension.preflight({
641
- graph,
642
- container: containers.get(extension.id),
643
- environment,
644
- configuration: pipeline.configuration,
645
- secrets: pipeline.secrets,
646
- credentials: platformCredentials,
647
- report
648
- });
649
- if (payload !== void 0) preflightPayloads.set(extension.id, payload);
650
- } catch (error) {
651
- throw toStructured("DEPLOY.PREFLIGHT_FAILED", error);
652
- }
653
- }
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
- });
662
- }
663
- if (action === "destroy") for (const extension of config.extensions) preflightTransportEnv[preflightEnvVarName(extension.id)] = "";
664
- } catch (error) {
665
- if (CliStructuredError.is(error)) return notOk(error);
666
- throw error;
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
- });
675
- let stackPath;
676
- const resultFilePath = path.join(cwd, ".prisma-composer", `deployment-result-${String(process.pid)}-${randomUUID()}.json`);
677
- let handover;
678
- try {
679
- try {
680
- handover = prepareSecondProcess({
681
- file: deployAppConfigurationFile(cwd, randomUUID()),
682
- appConfigurationRead: pipeline.graph.appConfigurationRead,
683
- plainVariableText: {},
684
- nodeAddresses: nodeAddresses(pipeline.graph),
685
- knownSecrets: opts.redaction.knownSecrets
686
- });
687
- stackPath = writeStackFile({
688
- entryPath: pipeline.entryModule.path,
689
- cwd,
690
- configFile: pipeline.configSource.file,
691
- name: pipeline.name,
692
- environment,
693
- assembled: pipeline.assembled
694
- });
695
- handover.writeFile();
696
- } catch (error) {
697
- return notOk(toStructured("DEPLOY.STACK_WRITE_FAILED", error));
698
- }
699
- const invocation = alchemyInvocation({
700
- command: action,
701
- stackFileRelativePath: GENERATED_STACK_RELATIVE_PATH,
702
- cwd,
703
- stage: alchemyStage,
704
- containerEnv: containerEnv(containers),
705
- preflightEnv: preflightTransportEnv,
706
- env: {
707
- ...reporterEnv(reporters, opts.redaction),
708
- ...handover.env,
709
- [DEPLOYMENT_RESULT_FILE_ENV]: resultFilePath
710
- },
711
- redactedValues: opts.redaction.allValues()
712
- });
713
- steps.start({ name: "apply" });
714
- let outcome;
715
- try {
716
- outcome = await (deps.alchemy ?? spawnAlchemy)(invocation);
717
- } catch (error) {
718
- if (CliStructuredError.is(error)) return notOk(error);
719
- return notOk(new CliStructuredError("DEPLOY.ENGINE_FAILED", error instanceof Error ? error.message : String(error), {
720
- cause: error,
721
- meta: { diagnostics: {
722
- exitCode: void 0,
723
- stackFilePath: stackPath,
724
- reproduceCommand: reproduceCommand(invocation),
725
- cwd
726
- } }
727
- }));
728
- }
729
- const reproduce = reproduceCommand(invocation, outcome);
730
- if (outcome.signal !== null) return notOk(new CliStructuredError("DEPLOY.ENGINE_FAILED", `alchemy ${action} was interrupted by ${outcome.signal}.`, { meta: {
731
- signal: outcome.signal,
732
- diagnostics: {
733
- exitCode: void 0,
734
- signal: outcome.signal,
735
- stackFilePath: stackPath,
736
- reproduceCommand: reproduce,
737
- cwd
738
- }
739
- } }));
740
- const status = outcome.exitCode ?? 1;
741
- if (status !== 0) {
742
- const engineCause = readEngineFailureCause(resultFilePath, (text) => opts.redaction.redact(text));
743
- const withCause = (sentence) => engineCause === void 0 ? sentence : `${sentence}\n${engineCause}`;
744
- return notOk(new CliStructuredError("DEPLOY.ENGINE_FAILED", withCause(`alchemy ${action} exited with status ${status}.`), { meta: {
745
- exitCode: status,
746
- ...engineCause !== void 0 ? { engineCause } : {},
747
- diagnostics: {
748
- exitCode: status,
749
- stackFilePath: stackPath,
750
- reproduceCommand: reproduce,
751
- cwd
752
- }
753
- } }));
754
- }
755
- steps.finish({ name: "apply" });
756
- try {
757
- if (action === "destroy") {
758
- for (const extension of pipeline.configSource.value.extensions) {
759
- if (extension.teardown === void 0) continue;
760
- try {
761
- await extension.teardown({
762
- container: containers.get(extension.id),
763
- environment
764
- });
765
- } catch (error) {
766
- throw toStructured("DEPLOY.TEARDOWN_FAILED", error);
767
- }
768
- }
769
- for (const extension of pipeline.configSource.value.extensions) {
770
- if (extension.container === void 0) continue;
771
- const instance = containers.get(extension.id);
772
- if (instance === void 0) continue;
773
- try {
774
- await extension.container.remove(instance, platformCredentials);
775
- } catch (error) {
776
- throw toStructured("DEPLOY.CONTAINER_REMOVE_FAILED", error);
777
- }
778
- }
779
- }
780
- } catch (error) {
781
- if (CliStructuredError.is(error)) return notOk(error);
782
- throw error;
783
- }
784
- return ok(void 0);
785
- } finally {
786
- try {
787
- fs.rmSync(resultFilePath, { force: true });
788
- fs.rmSync(engineFailureFilePath(resultFilePath), { force: true });
789
- } catch {}
790
- handover?.removeFile();
791
- }
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
- }
890
- //#endregion
891
- export { executeDeploy, executeDestroy };
892
-
893
- //# sourceMappingURL=execute-deploy-destroy-DN16ETAk-CzORriUO.mjs.map