@prisma/composer-cli 0.6.0-dev.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +201 -0
  2. package/dist/bin.mjs +987 -0
  3. package/dist/bin.mjs.map +1 -0
  4. package/dist/container-transport-DKmKg5JQ-CoY4XPma.mjs +30 -0
  5. package/dist/container-transport-DKmKg5JQ-CoY4XPma.mjs.map +1 -0
  6. package/dist/execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs +317 -0
  7. package/dist/execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs.map +1 -0
  8. package/dist/execute-deploy-destroy-DfVJUICu-quUQ08T8.mjs +316 -0
  9. package/dist/execute-deploy-destroy-DfVJUICu-quUQ08T8.mjs.map +1 -0
  10. package/dist/execute-dev-BMTFWfFc-B1whS-Rr.mjs +2011 -0
  11. package/dist/execute-dev-BMTFWfFc-B1whS-Rr.mjs.map +1 -0
  12. package/dist/execute-dev-BMTFWfFc-D0niyhe3.mjs +2012 -0
  13. package/dist/execute-dev-BMTFWfFc-D0niyhe3.mjs.map +1 -0
  14. package/dist/execute-log-Cay9hlKW-DJMh35AZ.mjs +158 -0
  15. package/dist/execute-log-Cay9hlKW-DJMh35AZ.mjs.map +1 -0
  16. package/dist/execute-log-Cay9hlKW-DrMeVOXq.mjs +157 -0
  17. package/dist/execute-log-Cay9hlKW-DrMeVOXq.mjs.map +1 -0
  18. package/dist/family-DkH0si4D-CN5QubKS.d.mts +1294 -0
  19. package/dist/family-DkH0si4D-CN5QubKS.d.mts.map +1 -0
  20. package/dist/family.d.mts +52 -0
  21. package/dist/family.d.mts.map +1 -0
  22. package/dist/family.mjs +923 -0
  23. package/dist/family.mjs.map +1 -0
  24. package/dist/local-target-CBZyaBy0.mjs +68 -0
  25. package/dist/local-target-CBZyaBy0.mjs.map +1 -0
  26. package/dist/local-target-H0IWu_FM.mjs +68 -0
  27. package/dist/local-target-H0IWu_FM.mjs.map +1 -0
  28. package/dist/pipeline-AoW8zq4I-C6Qe0VaZ.mjs +976 -0
  29. package/dist/pipeline-AoW8zq4I-C6Qe0VaZ.mjs.map +1 -0
  30. package/dist/pipeline-AoW8zq4I-DYNbf-ad.mjs +977 -0
  31. package/dist/pipeline-AoW8zq4I-DYNbf-ad.mjs.map +1 -0
  32. package/dist/result-B4XjxVK6.mjs +384 -0
  33. package/dist/result-B4XjxVK6.mjs.map +1 -0
  34. package/dist/result-D4d-xy4I.mjs +230 -0
  35. package/dist/result-D4d-xy4I.mjs.map +1 -0
  36. package/dist/run-alchemy-D44OZlyB-DA7s331N.mjs +93 -0
  37. package/dist/run-alchemy-D44OZlyB-DA7s331N.mjs.map +1 -0
  38. package/dist/run-alchemy-D44OZlyB-wmf8mHRE.mjs +93 -0
  39. package/dist/run-alchemy-D44OZlyB-wmf8mHRE.mjs.map +1 -0
  40. package/dist/shared-BTnATsqm-CDCqKwCF.mjs +158 -0
  41. package/dist/shared-BTnATsqm-CDCqKwCF.mjs.map +1 -0
  42. package/dist/testing.d.mts +53 -0
  43. package/dist/testing.d.mts.map +1 -0
  44. package/dist/testing.mjs +151 -0
  45. package/dist/testing.mjs.map +1 -0
  46. package/package.json +53 -0
  47. package/src/exports/family.ts +14 -0
  48. package/src/exports/testing.ts +6 -0
@@ -0,0 +1,923 @@
1
+ import { a as DOCS_BASE, t as notOk$1 } from "./result-D4d-xy4I.mjs";
2
+ import { n as executionDiagnostics, r as executorLoadFailure } from "./shared-BTnATsqm-CDCqKwCF.mjs";
3
+ import { t as alchemyCommandLine } from "./run-alchemy-D44OZlyB-wmf8mHRE.mjs";
4
+ import { spawn } from "node:child_process";
5
+ import { EnvironmentCredentialManager, createCli, defineCommand, defineCommandFamily, defineConfigSection, defineSessionCommand, exitWithChildStatus, flag, loadConfig, positional } from "@prisma/cli-engine";
6
+ import { CliStructuredError, notOk, ok } from "@prisma/cli-engine/protocol";
7
+ //#region ../../0-framework/3-tooling/cli/dist/log-DfT2hHqi.mjs
8
+ /** In-package variant threading the injection seam (the CLI's RunDeps, unit
9
+ * tests). Deliberately NOT re-exported through `./control` — the seam mirrors
10
+ * internal types and is not part of the published surface. */
11
+ async function deployWithDeps(input, deps) {
12
+ const cwd = input.cwd ?? process.cwd();
13
+ let executor;
14
+ try {
15
+ executor = await import("./execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs");
16
+ } catch (error) {
17
+ return notOk$1(executorLoadFailure("deploy", error, cwd));
18
+ }
19
+ return executor.executeDeploy(input, deps, cwd);
20
+ }
21
+ /** In-package variant threading the injection seam (the CLI's RunDeps, unit
22
+ * tests). Deliberately NOT re-exported through `./control` — the seam mirrors
23
+ * internal types and is not part of the published surface. */
24
+ async function destroyWithDeps(input, deps) {
25
+ const cwd = input.cwd ?? process.cwd();
26
+ let executor;
27
+ try {
28
+ executor = await import("./execute-deploy-destroy-DfVJUICu-D-kARRtf.mjs");
29
+ } catch (error) {
30
+ return notOk$1(executorLoadFailure("destroy", error, cwd));
31
+ }
32
+ return executor.executeDestroy(input, deps, cwd);
33
+ }
34
+ /** In-package variant threading the injection seam (the CLI's RunDeps, unit
35
+ * tests). Deliberately NOT re-exported through `./control` — the seam mirrors
36
+ * internal types and is not part of the published surface. */
37
+ async function devWithDeps(input, deps) {
38
+ const cwd = input.cwd ?? process.cwd();
39
+ let executor;
40
+ try {
41
+ executor = await import("./execute-dev-BMTFWfFc-D0niyhe3.mjs");
42
+ } catch (error) {
43
+ return notOk$1(executorLoadFailure("dev", error, cwd));
44
+ }
45
+ return executor.executeDev(input, deps, cwd);
46
+ }
47
+ /** In-package variant threading the injection seam (the CLI's LogRunDeps,
48
+ * unit tests). Deliberately NOT re-exported through `./control` — the seam
49
+ * mirrors internal types and is not part of the published surface. */
50
+ async function logWithDeps(input, deps) {
51
+ const cwd = input.cwd ?? process.cwd();
52
+ let executor;
53
+ try {
54
+ executor = await import("./execute-log-Cay9hlKW-DJMh35AZ.mjs");
55
+ } catch (error) {
56
+ return notOk$1(executorLoadFailure("log", error, cwd));
57
+ }
58
+ return executor.executeLog(input, deps, cwd);
59
+ }
60
+ //#endregion
61
+ //#region ../../0-framework/3-tooling/cli/dist/engine-cli-BurDkrQe.mjs
62
+ /**
63
+ * The family boundary's error translation.
64
+ *
65
+ * Composer and the engine each carry a class called `CliStructuredError`, both
66
+ * descended from the same prisma/prisma foundation, and both recognize errors
67
+ * by duck-typing on `name === 'CliStructuredError'`. That means a composer
68
+ * error handed to the engine untranslated is ACCEPTED — it does not fail
69
+ * loudly, it renders. What it loses is its `fix`: composer's foundation
70
+ * carries remediation as one prose string on that field, the engine carries it
71
+ * as a `nextActions` list and has no `fix` at all, so the fix text is dropped
72
+ * silently and the user is told what broke with no word on what to do about
73
+ * it. Nothing about that failure is visible without a test that looks for the
74
+ * fix on the other side, which is why there is one.
75
+ *
76
+ * Everything else on the envelope survives as-is; only remediation changes
77
+ * representation.
78
+ */
79
+ /**
80
+ * Composer's `fix` is free prose — "add this overrides block and reinstall",
81
+ * "run the build, then retry" — with no machine-readable command inside it.
82
+ * `user-choice` is the engine's own kind for exactly that (it is what the
83
+ * engine uses for its own config and prompt failures), so the text carries
84
+ * over verbatim as one action rather than being parsed into a command the
85
+ * author never wrote.
86
+ */
87
+ function fixAsNextActions(fix) {
88
+ return fix === void 0 ? [] : [{
89
+ kind: "user-choice",
90
+ label: fix
91
+ }];
92
+ }
93
+ /** Translates a composer failure into the engine's error type. Composer-side detail — `meta`, `where`, `docsUrl` — rides along untouched. */
94
+ function toEngineError(error) {
95
+ return new CliStructuredError(error.code, error.message, {
96
+ severity: error.severity,
97
+ nextActions: fixAsNextActions(error.fix),
98
+ ...error.why === void 0 ? {} : { why: error.why },
99
+ ...error.where === void 0 ? {} : { where: error.where },
100
+ ...error.meta === void 0 ? {} : { meta: error.meta },
101
+ ...error.docsUrl === void 0 ? {} : { docsUrl: error.docsUrl },
102
+ cause: error
103
+ });
104
+ }
105
+ /** The adapter the operations call, backed by the engine's `ctx.spawn` so the
106
+ * terminal reaches alchemy natively and the engine owns signal policy. */
107
+ function convergeSpawn(ctx) {
108
+ return async (invocation) => {
109
+ const line = alchemyCommandLine(invocation);
110
+ return await ctx.spawn({
111
+ command: line.command,
112
+ args: line.args,
113
+ cwd: line.cwd,
114
+ env: line.env
115
+ });
116
+ };
117
+ }
118
+ /** The in-process leg's deps: composer's existing seam, carrying the engine's
119
+ * own client and workspace id rather than anything read from the env. */
120
+ function operationDeps(spec) {
121
+ return {
122
+ alchemy: spec.alchemy,
123
+ configPath: spec.configPath,
124
+ credentials: {
125
+ workspaceId: spec.workspaceId,
126
+ client: spec.client
127
+ }
128
+ };
129
+ }
130
+ /**
131
+ * The reproduce hint a failed converge carries. Deliberately absent for an
132
+ * aborted one: the user stopped it, so there is nothing to reproduce.
133
+ */
134
+ function reproduceHint(failure) {
135
+ const diagnostics = executionDiagnostics(failure);
136
+ if (diagnostics === void 0) return [];
137
+ return [{
138
+ kind: "run-command",
139
+ label: `Run the converge directly from ${diagnostics.cwd} to reproduce this`,
140
+ command: diagnostics.reproduceCommand,
141
+ reason: `Generated stack file: ${diagnostics.stackFilePath}`
142
+ }];
143
+ }
144
+ /**
145
+ * How a FAILED converge settles. `deploy`, `destroy` and `dev` all end this
146
+ * way and must not drift apart, so the decision lives here once rather than
147
+ * inline in each handler.
148
+ *
149
+ * A failure that reached the child exits with the child's status verbatim and
150
+ * carries the reproduce hint; a failure that never reached the child is an
151
+ * ordinary structured error and gets the normal envelope. Nothing here reads
152
+ * `signal` — see settleConverge.
153
+ */
154
+ function settleConvergeFailure(failure, ctx) {
155
+ const child = ctx.lastChild();
156
+ if (child !== void 0 && child.exitCode !== 0) return ok(exitWithChildStatus({ nextActions: reproduceHint(failure) }));
157
+ return notOk(toEngineError(failure));
158
+ }
159
+ /**
160
+ * How a converge settles, now that the engine owns the child's status.
161
+ *
162
+ * Nothing here reads `signal`. `exitWithChildStatus` settles from the engine's
163
+ * own record of the child, and a signal-killed one overrules whatever this
164
+ * function asked for: 128 + the signal, no failure envelope, and the reproduce
165
+ * hint dropped, because the user stopped the run and there is nothing to
166
+ * reproduce.
167
+ *
168
+ * What is left is the operation's own verdict. A failure that reached the
169
+ * child exits with the child's status verbatim and carries the reproduce hint;
170
+ * a failure that never reached the child is an ordinary structured error and
171
+ * gets the normal envelope.
172
+ *
173
+ * A SUCCESS presents its result even when the child was signal-killed. No
174
+ * composer operation produces that pair today — each one reports a
175
+ * signal-killed converge as a failure — and an operation that ever did would
176
+ * have a real result worth showing. The run still exits 130, because the
177
+ * engine settles a signal-terminated run from its own record of the signal
178
+ * whatever the handler returns.
179
+ */
180
+ function settleConverge(result, ctx, present) {
181
+ if (!result.ok) return settleConvergeFailure(result.failure, ctx);
182
+ return ok(present(result.value));
183
+ }
184
+ /**
185
+ * Composer's projection into `prisma.config.ts` — the `composer` section.
186
+ *
187
+ * The section is deliberately tiny. Composer's real configuration lives in
188
+ * `prisma-composer.config.ts`, which holds executable values (Effect layers,
189
+ * provider factories, container lifecycles) and can only be understood by
190
+ * evaluating it inside a running command. A config-section validator loads
191
+ * with the command tree at start-up and must be dependency-light and total,
192
+ * so it is the wrong place to evaluate any of that. What the section carries
193
+ * is therefore only the one fact the engine can usefully know before a
194
+ * command runs: WHERE that file is, when the user wants to say so.
195
+ *
196
+ * Its fields grow only by amending the slice contract.
197
+ */
198
+ const KNOWN_FIELDS = ["configPath"];
199
+ function diagnostic(spec) {
200
+ return {
201
+ code: spec.code,
202
+ severity: spec.severity,
203
+ summary: spec.summary,
204
+ ...spec.why === void 0 ? {} : { why: spec.why },
205
+ nextActions: spec.fix === void 0 ? [] : [{
206
+ kind: "edit-file",
207
+ label: spec.fix
208
+ }]
209
+ };
210
+ }
211
+ function validate(raw) {
212
+ if (raw === void 0) return {
213
+ ok: true,
214
+ value: {},
215
+ diagnostics: []
216
+ };
217
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {
218
+ ok: false,
219
+ diagnostics: [diagnostic({
220
+ code: "CONFIG.FIELD_INVALID",
221
+ severity: "error",
222
+ summary: "The `composer` section of prisma.config.ts must be an object.",
223
+ fix: "Write `composer: { configPath: \"./prisma-composer.config.ts\" }`, or remove the section entirely."
224
+ })]
225
+ };
226
+ let record;
227
+ try {
228
+ record = { ...raw };
229
+ } catch {
230
+ return {
231
+ ok: false,
232
+ diagnostics: [diagnostic({
233
+ code: "CONFIG.FIELD_INVALID",
234
+ severity: "error",
235
+ summary: "The `composer` section of prisma.config.ts could not be read.",
236
+ why: "Reading its fields threw, so nothing in it can be trusted.",
237
+ fix: "Write it as a plain object literal, e.g. `composer: { configPath: \"./prisma-composer.config.ts\" }`."
238
+ })]
239
+ };
240
+ }
241
+ const configPath = record["configPath"];
242
+ if (configPath !== void 0 && (typeof configPath !== "string" || configPath.length === 0)) return {
243
+ ok: false,
244
+ diagnostics: [diagnostic({
245
+ code: "CONFIG.FIELD_INVALID",
246
+ severity: "error",
247
+ summary: "`composer.configPath` must be a non-empty string.",
248
+ why: "It names the prisma-composer.config.ts file to load.",
249
+ fix: "Set it to a path, or remove it to search upward from the entry."
250
+ })]
251
+ };
252
+ const unknown = Object.keys(record).filter((key) => !KNOWN_FIELDS.includes(key));
253
+ return {
254
+ ok: true,
255
+ value: configPath === void 0 ? {} : { configPath },
256
+ diagnostics: unknown.map((key) => diagnostic({
257
+ code: "CONFIG.FIELD_UNKNOWN",
258
+ severity: "warn",
259
+ summary: `The \`composer\` section has no field \`${key}\`; it is ignored.`,
260
+ fix: `Remove \`${key}\`, or check it against the version of @prisma/composer you have installed.`
261
+ }))
262
+ };
263
+ }
264
+ const composerSection = defineConfigSection({
265
+ name: "composer",
266
+ validate
267
+ });
268
+ /**
269
+ * The workspace the in-process leg acts in, from the engine's credential
270
+ * read. Handlers never decode a token and never read PRISMA_WORKSPACE_ID:
271
+ * whether the credential came from a stored session or the environment, the
272
+ * engine has already resolved it, and branching on where it came from is a
273
+ * defect by the credential-manager design.
274
+ *
275
+ * Undefined when the active credential names no workspace — an environment
276
+ * token whose claims carry none. The container descriptors raise their own
277
+ * "workspace required" error in that case, which is the error the user needs.
278
+ */
279
+ async function workspaceIdOf(ctx) {
280
+ return (await ctx.activeCredential())?.workspaceId;
281
+ }
282
+ /**
283
+ * `deploy <entry>` — a result command that hands the terminal to alchemy.
284
+ *
285
+ * `--production` is gone. It was accepted and then always errored ("only
286
+ * valid with destroy"), so no invocation using it could ever have succeeded;
287
+ * deploy targets production by default when no `--stage` is given.
288
+ */
289
+ const createDeployCommand = (operations) => defineCommand({
290
+ help: {
291
+ summary: "Deploy the application whose root node is <entry>'s default export.",
292
+ examples: ["{bin} deploy src/service.ts", "{bin} deploy src/service.ts --stage feat-auth"]
293
+ },
294
+ args: {
295
+ positionals: { entry: positional.string({
296
+ brief: "The module whose default export is the application root.",
297
+ placeholder: "entry"
298
+ }) },
299
+ flags: {
300
+ name: flag.string({
301
+ brief: "Override the root node's name — the deploy's application name.",
302
+ placeholder: "name"
303
+ }),
304
+ stage: flag.string({
305
+ brief: "Deploy scope to target; omit for production.",
306
+ placeholder: "stage"
307
+ })
308
+ }
309
+ },
310
+ needs: {
311
+ config: composerSection,
312
+ credentials: "child"
313
+ },
314
+ maySpawn: true,
315
+ handler: async (args, ctx) => {
316
+ const alchemy = convergeSpawn(ctx);
317
+ return settleConverge(await operations.deploy({
318
+ entry: args.positionals.entry,
319
+ name: args.flags.name,
320
+ stage: args.flags.stage,
321
+ cwd: ctx.cwd
322
+ }, operationDeps({
323
+ alchemy,
324
+ configPath: ctx.config.configPath,
325
+ workspaceId: await workspaceIdOf(ctx),
326
+ client: ctx.api
327
+ })), ctx, ({ summary }) => ctx.present({ data: { summary: summary ?? null } }, {
328
+ human: (ui) => summary === void 0 ? [{
329
+ kind: "summary",
330
+ status: "ok",
331
+ text: "Deployed."
332
+ }] : [{
333
+ kind: "summary",
334
+ status: "ok",
335
+ text: `Deployed ${ui.emphasize(summary.app)}.`
336
+ }, {
337
+ kind: "table",
338
+ columns: ["Address", "Deployed"],
339
+ rows: summary.nodes.map((node) => [node.address, node.entities.map((entity) => `${entity.kind} ${entity.id}`).join(", ")])
340
+ }],
341
+ stdout: () => [],
342
+ json: () => ({ summary: summary ?? null }),
343
+ next: () => []
344
+ }));
345
+ }
346
+ });
347
+ /**
348
+ * `destroy`'s target, from its two mutually exclusive flags. Kept out of the
349
+ * grammar because the engine's flag layer has no "exactly one of these"
350
+ * construct — and because both wrong shapes need their own remedy, which a
351
+ * generic arity error could not give.
352
+ */
353
+ function targetOf(stage, production) {
354
+ if (stage !== void 0 && production) return notOk(new CliStructuredError("DEPLOY.TARGET_CONFLICT", "Pass either --stage <name> or --production to `destroy`, not both."));
355
+ if (stage === void 0 && !production) return notOk(new CliStructuredError("DEPLOY.TARGET_MISSING", "`destroy` requires an explicit target.", { nextActions: [{
356
+ kind: "user-choice",
357
+ label: "Pass --stage <name> to tear down a branch environment, or --production to tear down the production environment."
358
+ }] }));
359
+ return ok(stage !== void 0 ? {
360
+ kind: "stage",
361
+ stage
362
+ } : { kind: "production" });
363
+ }
364
+ /**
365
+ * `destroy <entry>` — deploy's mirror: same derivation, alchemy destroy.
366
+ *
367
+ * No confirmation prompt, matching the CLI this replaces. The front door
368
+ * cannot know what the child will tear down, so a consent step here would be
369
+ * asking the user to approve a list nobody has computed yet; if destroy
370
+ * deserves one it belongs in composer's own operation, not in the grammar.
371
+ */
372
+ const createDestroyCommand = (operations) => defineCommand({
373
+ help: {
374
+ summary: "Tear down the application whose root node is <entry>'s default export.",
375
+ description: "Same derivation as deploy. Requires an explicit target: --stage <name> for a branch environment, or --production for the production environment.",
376
+ examples: ["{bin} destroy src/service.ts --stage feat-auth", "{bin} destroy src/service.ts --production"]
377
+ },
378
+ args: {
379
+ positionals: { entry: positional.string({
380
+ brief: "The module whose default export is the application root.",
381
+ placeholder: "entry"
382
+ }) },
383
+ flags: {
384
+ name: flag.string({
385
+ brief: "Override the root node's name — the application name to tear down.",
386
+ placeholder: "name"
387
+ }),
388
+ stage: flag.string({
389
+ brief: "Tear down this branch environment.",
390
+ placeholder: "stage"
391
+ }),
392
+ production: flag.boolean({ brief: "Tear down the project-level production environment." })
393
+ }
394
+ },
395
+ needs: {
396
+ config: composerSection,
397
+ credentials: "child"
398
+ },
399
+ maySpawn: true,
400
+ handler: async (args, ctx) => {
401
+ const target = targetOf(args.flags.stage, args.flags.production);
402
+ if (!target.ok) return target;
403
+ const alchemy = convergeSpawn(ctx);
404
+ return settleConverge(await operations.destroy({
405
+ entry: args.positionals.entry,
406
+ name: args.flags.name,
407
+ target: target.value,
408
+ cwd: ctx.cwd,
409
+ onEvent: (event) => {
410
+ if (event.kind !== "no-local-deploy-state") return;
411
+ ctx.report({
412
+ kind: "message",
413
+ severity: "warn",
414
+ text: `No prior deploy state under ${event.cwd} — if you deployed from a different directory, run destroy from there; otherwise this is a no-op.`
415
+ });
416
+ }
417
+ }, operationDeps({
418
+ alchemy,
419
+ configPath: ctx.config.configPath,
420
+ workspaceId: await workspaceIdOf(ctx),
421
+ client: ctx.api
422
+ })), ctx, () => ctx.present({ data: void 0 }, {
423
+ human: () => [{
424
+ kind: "summary",
425
+ status: "ok",
426
+ text: "Destroyed."
427
+ }],
428
+ stdout: () => [],
429
+ json: () => void 0,
430
+ next: () => []
431
+ }));
432
+ }
433
+ });
434
+ const STOP_STEP = "Stopping the app's services — emulators and data stay up";
435
+ /** Resolves when the run is asked to stop. */
436
+ function stopRequested(signal) {
437
+ if (signal.aborted) return Promise.resolve();
438
+ return new Promise((resolve) => {
439
+ signal.addEventListener("abort", () => resolve(), { once: true });
440
+ });
441
+ }
442
+ /**
443
+ * One converge at a time. `ctx.spawn` refuses a second live child, and the
444
+ * watch loop can well fire a rebuild while the previous converge is still
445
+ * running — so a request that arrives during a live converge joins the single
446
+ * queued follow-up instead of starting its own. That extends the coalescing
447
+ * the watcher already does across a burst of edits to cover the converge
448
+ * itself, and it is sound because every dev converge is the SAME invocation:
449
+ * one stack file at one fixed path, rewritten in place before each request.
450
+ */
451
+ function coalescedConverge(run) {
452
+ let live;
453
+ let queued;
454
+ const start = (invocation) => {
455
+ const outcome = run(invocation);
456
+ const settled = outcome.then(() => void 0, () => void 0);
457
+ live = settled;
458
+ settled.then(() => {
459
+ if (live === settled) live = void 0;
460
+ });
461
+ return outcome;
462
+ };
463
+ return (invocation) => {
464
+ const running = live;
465
+ if (running === void 0) return start(invocation);
466
+ queued ??= running.then(() => {
467
+ queued = void 0;
468
+ return start(invocation);
469
+ });
470
+ return queued;
471
+ };
472
+ }
473
+ /** The front door, ordered by address depth (fewest dots first) then lexicographically. */
474
+ function frontDoorOrder(endpoints) {
475
+ return [...endpoints].sort((a, b) => {
476
+ const depth = a.address.split(".").length - b.address.split(".").length;
477
+ if (depth !== 0) return depth;
478
+ return a.address < b.address ? -1 : a.address > b.address ? 1 : 0;
479
+ });
480
+ }
481
+ /**
482
+ * The operation's events as engine events. The legacy `[dev]` console prefix
483
+ * is gone: these are commentary the engine renders and frames.
484
+ */
485
+ function reportDevEvent(report, lastChild) {
486
+ let stopFailed = false;
487
+ return (event) => {
488
+ switch (event.kind) {
489
+ case "ready":
490
+ report({
491
+ kind: "status",
492
+ subject: "dev",
493
+ status: "ready"
494
+ });
495
+ for (const endpoint of frontDoorOrder(event.endpoints)) report({
496
+ kind: "endpoint",
497
+ name: endpoint.address,
498
+ url: endpoint.url
499
+ });
500
+ return;
501
+ case "unwatchable":
502
+ report({
503
+ kind: "message",
504
+ severity: "warn",
505
+ text: `${event.address} has no watchable inputs.`
506
+ });
507
+ return;
508
+ case "rebuild-failed":
509
+ report({
510
+ kind: "message",
511
+ severity: "warn",
512
+ text: `Rebuild failed: ${event.message}`
513
+ });
514
+ return;
515
+ case "watch-error":
516
+ report({
517
+ kind: "message",
518
+ severity: "warn",
519
+ text: `Watch error: ${event.message}`
520
+ });
521
+ return;
522
+ case "converge-failed": {
523
+ const child = lastChild();
524
+ if (child !== void 0 && child.signal !== null) return;
525
+ report({
526
+ kind: "message",
527
+ severity: "warn",
528
+ text: `Converge failed — the running app is untouched; still watching.
529
+ Generated stack file: ${event.stackFilePath}\nRun \`${event.reproduceCommand}\` from ${event.cwd} to reproduce this directly.`
530
+ });
531
+ report({
532
+ kind: "remediation",
533
+ action: {
534
+ kind: "run-command",
535
+ label: `Run the converge directly from ${event.cwd} to reproduce this`,
536
+ command: event.reproduceCommand,
537
+ reason: `Generated stack file: ${event.stackFilePath}`
538
+ }
539
+ });
540
+ return;
541
+ }
542
+ case "stopping":
543
+ report({
544
+ kind: "step-started",
545
+ step: STOP_STEP,
546
+ id: "dev-stop"
547
+ });
548
+ return;
549
+ case "stop-error":
550
+ stopFailed = true;
551
+ report({
552
+ kind: "message",
553
+ severity: "warn",
554
+ text: `A service refused to stop: ${event.message}`
555
+ });
556
+ return;
557
+ case "stopped":
558
+ report({
559
+ kind: "step-finished",
560
+ step: STOP_STEP,
561
+ id: "dev-stop",
562
+ outcome: stopFailed ? "warning" : "ok"
563
+ });
564
+ return;
565
+ }
566
+ };
567
+ }
568
+ const createDevCommand = (operations) => defineSessionCommand({
569
+ help: {
570
+ summary: "Bring up the application whose root node is <entry>'s default export, entirely on this machine.",
571
+ description: "Runs credential-free and watches the app for changes, reconverging on every edit. Logs are a separate command; run `log <entry>` to tail them.",
572
+ examples: ["{bin} dev src/service.ts", "{bin} dev src/service.ts --fresh"]
573
+ },
574
+ args: {
575
+ positionals: { entry: positional.string({
576
+ brief: "The module whose default export is the application root.",
577
+ placeholder: "entry"
578
+ }) },
579
+ flags: {
580
+ name: flag.string({
581
+ brief: "Override the root node's name — the dev instance's application name.",
582
+ placeholder: "name"
583
+ }),
584
+ fresh: flag.boolean({ brief: "Destroy the dev stack and wipe the dev state directory before starting." })
585
+ }
586
+ },
587
+ needs: { config: composerSection },
588
+ maySpawn: true,
589
+ handler: async (args, ctx) => {
590
+ const alchemy = convergeSpawn(ctx);
591
+ const result = await operations.dev({
592
+ entry: args.positionals.entry,
593
+ name: args.flags.name,
594
+ fresh: args.flags.fresh,
595
+ cwd: ctx.cwd,
596
+ onEvent: reportDevEvent(ctx.report, ctx.lastChild)
597
+ }, {
598
+ alchemy: coalescedConverge(alchemy),
599
+ configPath: ctx.config.configPath
600
+ });
601
+ if (!result.ok) return settleConvergeFailure(result.failure, ctx);
602
+ await stopRequested(ctx.signal);
603
+ await result.value.stop();
604
+ return ok(void 0);
605
+ }
606
+ });
607
+ /**
608
+ * `log <entry> [address]` — a session command that tails the merged logs of
609
+ * the app running locally on this machine.
610
+ *
611
+ * It reads the LOCAL dev-emulator daemon, not the platform's logs surface, so
612
+ * it is credential-free. It hands the terminal to nothing, which is why it
613
+ * does not declare `maySpawn` and keeps json support: the log lines ARE its
614
+ * json surface.
615
+ *
616
+ * Windows is refused inside the operation itself (LOG.PLATFORM_UNSUPPORTED),
617
+ * which is why nothing here reads the platform.
618
+ */
619
+ /** An empty screen reads as broken, so show a little recent history before going live. */
620
+ const DEFAULT_TAIL = 20;
621
+ const createLogCommand = (operations) => defineSessionCommand({
622
+ help: {
623
+ summary: "Tail the merged logs of the locally-running application whose root node is <entry>'s default export.",
624
+ examples: ["{bin} log src/service.ts", "{bin} log src/service.ts catalog.service"]
625
+ },
626
+ args: {
627
+ positionals: {
628
+ entry: positional.string({
629
+ brief: "The module whose default export is the application root.",
630
+ placeholder: "entry"
631
+ }),
632
+ address: positional.optionalString({
633
+ brief: "Only this service's lines, by its dotted address (catalog.service); every service when absent.",
634
+ placeholder: "address"
635
+ })
636
+ },
637
+ flags: {
638
+ name: flag.string({
639
+ brief: "Override the root node's name — the dev instance's application name.",
640
+ placeholder: "name"
641
+ }),
642
+ tail: flag.number({
643
+ brief: `How many trailing history lines to show before live output (default ${String(DEFAULT_TAIL)}).`,
644
+ placeholder: "lines",
645
+ default: DEFAULT_TAIL
646
+ })
647
+ }
648
+ },
649
+ needs: { config: composerSection },
650
+ handler: async (args, ctx) => {
651
+ const reportLogEvent = (event) => {
652
+ ctx.report({
653
+ kind: "message",
654
+ severity: "warn",
655
+ text: event.kind === "stream-failed" ? `Stream failed: ${event.message}` : `Falling behind — dropped the ${String(event.count)} oldest lines.`
656
+ });
657
+ };
658
+ const result = await operations.log({
659
+ entry: args.positionals.entry,
660
+ name: args.flags.name,
661
+ address: args.positionals.address,
662
+ tail: args.flags.tail ?? DEFAULT_TAIL,
663
+ cwd: ctx.cwd,
664
+ signal: ctx.signal,
665
+ onEvent: reportLogEvent
666
+ }, { configPath: ctx.config.configPath });
667
+ if (!result.ok) return notOk(toEngineError(result.failure));
668
+ const attached = result.value;
669
+ if (attached.services.length === 0) {
670
+ ctx.report({
671
+ kind: "message",
672
+ severity: "warn",
673
+ text: `No running services for "${attached.appName}" — start it first with \`dev ${args.positionals.entry}\`.`
674
+ });
675
+ return ok(void 0);
676
+ }
677
+ for await (const { service, line } of attached.lines) ctx.report({
678
+ kind: "output",
679
+ source: service,
680
+ channel: "data",
681
+ line: `[${service}] ${line}`
682
+ });
683
+ return ok(void 0);
684
+ }
685
+ });
686
+ /**
687
+ * Composer's `CommandFamily` — the unit the engine mounts, whether the process
688
+ * is composer's own CLI or the `prisma` bin.
689
+ *
690
+ * This module and everything it reaches statically must stay free of alchemy
691
+ * and of effect VALUE imports: the `prisma` bin imports the family directly,
692
+ * so anything in this static graph loads on `prisma --version`. The mechanism
693
+ * that holds it is the existing lazy boundary inside the operation modules —
694
+ * `operations/deploy.ts`, `destroy.ts`, `dev.ts` and `log.ts` each `await
695
+ * import()` their executor, and it is the executors that reach the provider
696
+ * tree. Importing the operations here is therefore free; importing an
697
+ * executor, or flattening one of those dynamic imports, is not.
698
+ * scripts/check-family-static-graph.mjs enforces this against BUILT output,
699
+ * where type-only imports have already been erased.
700
+ *
701
+ * The four commands close over the operations they are given, so a host can
702
+ * mount this family against the test double and exercise real grammar, real
703
+ * arg validation and real handlers with no alchemy behind them.
704
+ */
705
+ const realOperations = {
706
+ deploy: deployWithDeps,
707
+ destroy: destroyWithDeps,
708
+ dev: devWithDeps,
709
+ log: logWithDeps
710
+ };
711
+ function createComposerFamily(options = {}) {
712
+ const operations = options.operations ?? realOperations;
713
+ return defineCommandFamily({
714
+ configSection: composerSection,
715
+ commands: {
716
+ deploy: createDeployCommand(operations),
717
+ destroy: createDestroyCommand(operations),
718
+ dev: createDevCommand(operations),
719
+ log: createLogCommand(operations)
720
+ },
721
+ docsBaseUrl: DOCS_BASE
722
+ });
723
+ }
724
+ /**
725
+ * Everything environmental the engine needs, assembled from a host process.
726
+ *
727
+ * The engine takes no globals: streams, cwd, env, TTY-ness, exit and signal
728
+ * subscription all arrive through `Runtime`, which is what lets a test drive a
729
+ * whole run without touching `process`. Composing one is the substantive part
730
+ * of hosting the engine — `createCli` and `Cli.run` are two calls.
731
+ *
732
+ * Credentials come from the engine's own environment-only manager, which
733
+ * composes a session from PRISMA_SERVICE_TOKEN / PRISMA_WORKSPACE_ID and
734
+ * refuses every mutation. That is the whole of composer's standalone auth
735
+ * story: this CLI has no login flow and mounts no auth commands, so there is
736
+ * nothing to store — the two variables ARE the credential.
737
+ */
738
+ /** Where the management API lives. Matches the lowering client's default origin; the env var is the escape hatch for staging. */
739
+ const DEFAULT_MANAGEMENT_API_BASE_URL = "https://api.prisma.io";
740
+ const DEFAULT_AUTH_BASE_URL = "https://auth.prisma.io";
741
+ /**
742
+ * Starts the converge child: inherited stdio, this process's own group, no
743
+ * `detached` and no new console — which is what lets the terminal deliver
744
+ * Ctrl-C to the child natively instead of the CLI forwarding it. The engine
745
+ * never imports node:child_process; this adapter is the whole of the host's
746
+ * side of that seam.
747
+ */
748
+ const spawnChild = (request) => {
749
+ const child = spawn(request.command, [...request.args], {
750
+ cwd: request.cwd,
751
+ stdio: "inherit",
752
+ env: request.env
753
+ });
754
+ return {
755
+ ended: new Promise((resolve, reject) => {
756
+ child.on("error", reject);
757
+ child.on("close", (exitCode, signal) => {
758
+ resolve({
759
+ exitCode,
760
+ signal
761
+ });
762
+ });
763
+ }),
764
+ kill: (signal) => {
765
+ child.kill(signal);
766
+ }
767
+ };
768
+ };
769
+ /**
770
+ * The SDK's client construction config. The engine requires all four fields
771
+ * whenever a credential manager is wired, but this host reaches none of the
772
+ * login paths: an environment credential carries no refresh token, so nothing
773
+ * ever refreshes and `clientId`/`redirectUri` are never read. They are
774
+ * env-overridable rather than hard-coded so a staging run can point the whole
775
+ * client somewhere else in one place.
776
+ */
777
+ function clientConfig(env, apiBaseUrl) {
778
+ return {
779
+ clientId: env["PRISMA_CLIENT_ID"] ?? "prisma-composer-cli",
780
+ redirectUri: env["PRISMA_REDIRECT_URI"] ?? "http://127.0.0.1/callback",
781
+ apiBaseUrl,
782
+ authBaseUrl: env["PRISMA_AUTH_URL"] ?? DEFAULT_AUTH_BASE_URL
783
+ };
784
+ }
785
+ /**
786
+ * What this process runs on, for `ctx.host`. Bun and Deno both announce
787
+ * themselves in `versions`; nothing else does, so an absent marker means Node.
788
+ */
789
+ function describeHost(host) {
790
+ const name = ["bun", "deno"].find((candidate) => host.versions[candidate] !== void 0) ?? "node";
791
+ return {
792
+ runtime: {
793
+ name,
794
+ version: host.versions[name] ?? host.version
795
+ },
796
+ platform: host.platform,
797
+ arch: host.arch
798
+ };
799
+ }
800
+ /**
801
+ * Which package manager invoked us, read from the `npm_config_user_agent`
802
+ * every major manager sets (`pnpm/10.27.0 npm/? node/v24.16.0 darwin arm64`).
803
+ * `undefined` when the CLI was run directly rather than through a manager — a
804
+ * normal case, not a failure, so nothing is inferred from the filesystem, and
805
+ * the engine falls back to its own detection from the project at cwd.
806
+ */
807
+ function detectPackageManager(env) {
808
+ const agent = env["npm_config_user_agent"];
809
+ if (agent === void 0) return void 0;
810
+ const name = agent.split("/")[0];
811
+ switch (name) {
812
+ case "npm":
813
+ case "pnpm":
814
+ case "yarn":
815
+ case "bun":
816
+ case "deno": return name;
817
+ default: return;
818
+ }
819
+ }
820
+ /**
821
+ * The config loader arrives as a function rather than an already-loaded config
822
+ * because the engine reads `prisma.config.ts` on demand — only when the command
823
+ * it is about to run declares a config section, and with whatever file
824
+ * `--config` named. A host that loaded the file up front would read it for runs
825
+ * that never needed it, and would have nowhere to put `--config`.
826
+ *
827
+ * Nothing here answers "is this CI": the engine detects it from `env` itself,
828
+ * and `isCIOverride` exists only for hosts where that detection cannot be
829
+ * right — composer is not one.
830
+ */
831
+ function createRuntime(host, loadConfig) {
832
+ const env = host.env;
833
+ const apiBaseUrl = env["PRISMA_MANAGEMENT_API_URL"] ?? DEFAULT_MANAGEMENT_API_BASE_URL;
834
+ const packageManager = detectPackageManager(env);
835
+ return {
836
+ stdout: host.stdout,
837
+ stderr: host.stderr,
838
+ stdin: host.stdin,
839
+ cwd: host.cwd(),
840
+ env,
841
+ isTty: {
842
+ stdin: host.stdin.isTTY === true,
843
+ stdout: host.stdout.isTTY === true,
844
+ stderr: host.stderr.isTTY === true
845
+ },
846
+ exit: (code) => host.exit(code),
847
+ onSignal: (cb) => {
848
+ const onSigint = () => {
849
+ cb("SIGINT");
850
+ };
851
+ const onSigterm = () => {
852
+ cb("SIGTERM");
853
+ };
854
+ host.on("SIGINT", onSigint);
855
+ host.on("SIGTERM", onSigterm);
856
+ return () => {
857
+ host.off("SIGINT", onSigint);
858
+ host.off("SIGTERM", onSigterm);
859
+ };
860
+ },
861
+ loadConfig,
862
+ credentialManager: new EnvironmentCredentialManager({ env }),
863
+ managementApiClientConfig: clientConfig(env, apiBaseUrl),
864
+ spawn: spawnChild,
865
+ managementApi: { baseUrl: apiBaseUrl },
866
+ ...packageManager !== void 0 && { packageManager },
867
+ host: describeHost(host)
868
+ };
869
+ }
870
+ /**
871
+ * Composer's own CLI, rebuilt as a thin composition of the family it
872
+ * publishes: `createCli` over `createComposerFamily()`, `Cli.run` with a
873
+ * Runtime. Grammar, help, arg validation, output framing, exit codes and
874
+ * signal ownership all belong to the engine now — this module contributes the
875
+ * family and the environment, and nothing else.
876
+ *
877
+ * Running composer's commands through the same path an external host uses is
878
+ * the point: it is what proves the family works standalone before the `prisma`
879
+ * bin mounts it.
880
+ *
881
+ * This IS composer's CLI. The clipanion shell it replaced, and the bespoke
882
+ * runner that shelled out to alchemy, are gone; `bin.ts` is a call into here.
883
+ */
884
+ const BINARY_NAME = "prisma-composer";
885
+ /**
886
+ * Composer's commands mount at the top level of its own CLI (`prisma-composer
887
+ * deploy`); under the `prisma` bin the same family mounts one level down
888
+ * (`prisma composer deploy`). The family is identical either way — only the
889
+ * mount paths differ, which is exactly the split `createCli` draws between
890
+ * `commandFamilies` and `commands`.
891
+ */
892
+ function mountedTree(family) {
893
+ return { ...family.commands };
894
+ }
895
+ function createComposerCli(spec) {
896
+ const family = createComposerFamily({ operations: spec.operations });
897
+ return createCli({
898
+ name: BINARY_NAME,
899
+ version: spec.version,
900
+ commandFamilies: [family],
901
+ groups: {},
902
+ commands: mountedTree(family)
903
+ });
904
+ }
905
+ /**
906
+ * Composes the Runtime and runs one invocation. Returns the exit code rather
907
+ * than exiting, so the caller owns the process — a bin assigns it to
908
+ * `process.exitCode` and lets the streams drain, as composer's CLI has always
909
+ * done.
910
+ *
911
+ * `prisma.config.ts` is not read here. The loader goes in as a function, and the
912
+ * engine calls it only when the command it is about to run declares a config
913
+ * section, passing it the file `--config` named; the loader resolves that
914
+ * against the host's cwd.
915
+ */
916
+ function runComposerCli(argv, host, spec, hooks) {
917
+ const runtime = createRuntime(host, (configPath) => loadConfig(host.cwd(), configPath));
918
+ return createComposerCli(spec).run(argv, runtime, hooks);
919
+ }
920
+ //#endregion
921
+ export { BINARY_NAME, composerSection, createComposerCli, createComposerFamily, realOperations, runComposerCli, toEngineError };
922
+
923
+ //# sourceMappingURL=family.mjs.map