@prisma/cli-engine 0.0.1

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.
@@ -0,0 +1,1703 @@
1
+ import { i as okVoid, n as notOk, t as CliStructuredError } from "./protocol-C1JQcGl9.js";
2
+ import { createRequire } from "node:module";
3
+ import { buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
4
+ import { resolve } from "node:path";
5
+ import { Readable, Writable } from "node:stream";
6
+ //#region src/args.ts
7
+ function flagRuntime(spec) {
8
+ return spec;
9
+ }
10
+ function brandFlag(spec) {
11
+ const runtime = {
12
+ type: spec.type,
13
+ brief: spec.brief,
14
+ placeholder: spec.placeholder,
15
+ alias: spec.alias,
16
+ default: spec.default,
17
+ values: spec.values
18
+ };
19
+ return Object.freeze(runtime);
20
+ }
21
+ /**
22
+ * Command-declared flags. The shared family (--format/--json,
23
+ * --log-level/--verbose, --quiet, --yes, --interactive, --color) is
24
+ * engine-injected and reserved. Flags are optional by default
25
+ * (requiredString is the exception); positionals are required by
26
+ * default (optionalString is the exception).
27
+ */
28
+ const flag = {
29
+ string(spec) {
30
+ return brandFlag({
31
+ type: "string",
32
+ ...spec
33
+ });
34
+ },
35
+ requiredString(spec) {
36
+ return brandFlag({
37
+ type: "requiredString",
38
+ ...spec
39
+ });
40
+ },
41
+ number(spec) {
42
+ return brandFlag({
43
+ type: "number",
44
+ ...spec
45
+ });
46
+ },
47
+ boolean(spec) {
48
+ return brandFlag({
49
+ type: "boolean",
50
+ ...spec
51
+ });
52
+ },
53
+ enum(spec) {
54
+ return brandFlag({
55
+ type: "enum",
56
+ ...spec
57
+ });
58
+ },
59
+ repeated(spec) {
60
+ return brandFlag({
61
+ type: "repeated",
62
+ ...spec
63
+ });
64
+ }
65
+ };
66
+ function positionalRuntime(spec) {
67
+ return spec;
68
+ }
69
+ function brandPositional(spec) {
70
+ return Object.freeze(spec);
71
+ }
72
+ const positional = {
73
+ string(spec) {
74
+ return brandPositional({
75
+ type: "string",
76
+ ...spec
77
+ });
78
+ },
79
+ optionalString(spec) {
80
+ return brandPositional({
81
+ type: "optionalString",
82
+ ...spec
83
+ });
84
+ },
85
+ /**
86
+ * Zero or more trailing values; at most one, declared last (order =
87
+ * declaration order; keys must not be integer-like).
88
+ */
89
+ variadic(spec) {
90
+ return brandPositional({
91
+ type: "variadic",
92
+ ...spec
93
+ });
94
+ }
95
+ };
96
+ //#endregion
97
+ //#region src/presentation.ts
98
+ const PRESENTED = Symbol.for("prisma.cli-engine.presented");
99
+ //#endregion
100
+ //#region src/execution/rendering.ts
101
+ function firstLine(text) {
102
+ const newline = text.indexOf("\n");
103
+ return (newline === -1 ? text : text.slice(0, newline)).trim();
104
+ }
105
+ const STEP_OUTCOME_SYMBOL = {
106
+ ok: "✔",
107
+ failed: "✖",
108
+ skipped: "↷",
109
+ warning: "⚠"
110
+ };
111
+ /** Human rendering: `output` data lines are the command's data on OUR
112
+ * stdout; everything else is commentary on stderr. `remediation` is
113
+ * transcript-only: framed in json mode, never rendered in human mode,
114
+ * never aggregated into any envelope. */
115
+ function renderEventHuman(invocation, event) {
116
+ const { stdout, stderr } = invocation.runtime;
117
+ switch (event.kind) {
118
+ case "message":
119
+ stderr.write(`${event.text}\n`);
120
+ return;
121
+ case "output":
122
+ (event.channel === "data" ? stdout : stderr).write(`${event.line}\n`);
123
+ return;
124
+ case "step-started":
125
+ stderr.write(`▸ ${event.step}\n`);
126
+ return;
127
+ case "step-finished":
128
+ stderr.write(`${STEP_OUTCOME_SYMBOL[event.outcome]} ${event.step}\n`);
129
+ return;
130
+ case "progress":
131
+ stderr.write(`${event.step === void 0 ? "progress" : event.step} ${event.completed}${event.total === void 0 ? "" : `/${event.total}`}\n`);
132
+ return;
133
+ case "remediation": return;
134
+ case "endpoint":
135
+ stderr.write(`${event.name}: ${event.url}\n`);
136
+ return;
137
+ case "status":
138
+ stderr.write(`${event.subject}: ${event.from === void 0 ? "" : `${event.from} → `}${event.status}\n`);
139
+ return;
140
+ case "artifact":
141
+ stderr.write(`${event.path}${event.description === void 0 ? "" : ` — ${event.description}`}\n`);
142
+ return;
143
+ }
144
+ }
145
+ const TONE_SYMBOL = {
146
+ ok: "✔",
147
+ error: "✖",
148
+ warn: "⚠",
149
+ info: "ℹ"
150
+ };
151
+ function renderBlock(block, write) {
152
+ switch (block.kind) {
153
+ case "summary":
154
+ write(`${TONE_SYMBOL[block.tone]} ${block.text}`);
155
+ return;
156
+ case "fields":
157
+ for (const row of block.rows) write(`${row.label}: ${row.sensitive === true ? "********" : row.value}`);
158
+ return;
159
+ case "table":
160
+ write(block.columns.join(" "));
161
+ for (const row of block.rows) write(row.join(" "));
162
+ return;
163
+ case "list":
164
+ for (const item of block.items) write(`- ${item}`);
165
+ return;
166
+ case "tree":
167
+ writeTree(block.roots, 0, write);
168
+ return;
169
+ }
170
+ }
171
+ function writeTree(nodes, depth, write) {
172
+ for (const node of nodes) {
173
+ write(`${" ".repeat(depth)}${node.label}`);
174
+ if (node.children !== void 0) writeTree(node.children, depth + 1, write);
175
+ }
176
+ }
177
+ const DIAGNOSTIC_SYMBOL = {
178
+ error: "✖",
179
+ warn: "⚠",
180
+ info: "ℹ"
181
+ };
182
+ function writeDiagnostic(stream, diagnostic) {
183
+ stream.write(`${DIAGNOSTIC_SYMBOL[diagnostic.severity]} [${diagnostic.code}] ${diagnostic.summary}\n`);
184
+ if (diagnostic.why !== void 0) stream.write(` why: ${diagnostic.why}\n`);
185
+ for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action)}\n`);
186
+ if (diagnostic.docsUrl !== void 0) stream.write(` docs: ${diagnostic.docsUrl}\n`);
187
+ }
188
+ function renderNextAction(action) {
189
+ return `→ ${action.label}${action.command === void 0 ? "" : `: ${action.command}`}`;
190
+ }
191
+ /** Populates docsUrl from the owning family's docsBaseUrl (base + code)
192
+ * when the diagnostic does not carry its own — a per-raise docsUrl wins. */
193
+ function withDocsUrl(state, diagnostic) {
194
+ if (diagnostic.docsUrl !== void 0 || state.docsBaseUrl === void 0) return diagnostic;
195
+ const base = state.docsBaseUrl.endsWith("/") ? state.docsBaseUrl : `${state.docsBaseUrl}/`;
196
+ return {
197
+ ...diagnostic,
198
+ docsUrl: `${base}${diagnostic.code}`
199
+ };
200
+ }
201
+ /** Channel discipline (operator ruling, 2026-08-09): human Blocks,
202
+ * next-action lines, and diagnostics are presentation prose on stderr;
203
+ * the materialized `stdout` presentation lines are the machine-usable
204
+ * payload on stdout, always — human mode stays pipe-clean. */
205
+ function renderCompletedHuman(invocation, presented) {
206
+ const { runtime, state } = invocation;
207
+ for (const block of presented.presentation.human) renderBlock(block, (line) => runtime.stderr.write(`${line}\n`));
208
+ for (const action of presented.presentation.next) runtime.stderr.write(`${renderNextAction(action)}\n`);
209
+ for (const diagnostic of presented.diagnostics) writeDiagnostic(runtime.stderr, withDocsUrl(state, diagnostic));
210
+ for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
211
+ }
212
+ //#endregion
213
+ //#region src/execution/reporting.ts
214
+ const SEVERITY_RANK = {
215
+ error: 0,
216
+ warn: 1,
217
+ info: 2,
218
+ verbose: 3
219
+ };
220
+ /** The display severity a commentary event is filtered by. `output`
221
+ * data lines are the command's data, never filtered (undefined). */
222
+ function eventDisplaySeverity(event) {
223
+ if (event.kind === "message") return event.severity;
224
+ if (event.kind === "output" && event.channel === "data") return;
225
+ return "info";
226
+ }
227
+ /** report() after the handler resolved is a bug (InternalError). The
228
+ * run has always settled by the time the resolved flag is observable,
229
+ * so the only surface left is a stderr note — throwing here would
230
+ * surface as an unhandled rejection in a detached async context. */
231
+ function reportAfterResolution(invocation) {
232
+ invocation.runtime.stderr.write("✖ [CLI.INTERNAL_ERROR] @prisma/cli-engine: report() was called after the handler resolved\n");
233
+ }
234
+ function reportEvent(invocation, event) {
235
+ const state = invocation.state;
236
+ if (state.resolved) {
237
+ reportAfterResolution(invocation);
238
+ return;
239
+ }
240
+ invocation.hooks.onEvent?.(event);
241
+ const severity = eventDisplaySeverity(event);
242
+ if (severity !== void 0 && SEVERITY_RANK[severity] > SEVERITY_RANK[state.logLevel]) return;
243
+ if (state.format === "json") {
244
+ emitFrame(invocation, {
245
+ ...event,
246
+ commandId: state.commandId,
247
+ timestamp: invocation.now().toISOString()
248
+ });
249
+ return;
250
+ }
251
+ renderEventHuman(invocation, event);
252
+ }
253
+ function emitFrame(invocation, frame) {
254
+ invocation.runtime.stdout.write(`${JSON.stringify(frame)}\n`);
255
+ invocation.hooks.onStreamEvent?.(frame);
256
+ }
257
+ //#endregion
258
+ //#region src/execution/needs.ts
259
+ function needsErrored(error, diagnostics = []) {
260
+ return {
261
+ kind: "errored",
262
+ error,
263
+ diagnostics
264
+ };
265
+ }
266
+ function structuredErrorFromDiagnostic(diagnostic) {
267
+ return new CliStructuredError(diagnostic.code, diagnostic.summary, {
268
+ severity: diagnostic.severity,
269
+ why: diagnostic.why,
270
+ nextActions: diagnostic.nextActions,
271
+ where: diagnostic.where,
272
+ meta: diagnostic.meta,
273
+ docsUrl: diagnostic.docsUrl
274
+ });
275
+ }
276
+ /** The needs checks the engine enforces before the handler runs:
277
+ * interaction, dependencies, credentials, and the command's config
278
+ * section. File-level config problems fail only commands with a
279
+ * needs.config section — every other command runs normally. On
280
+ * success it carries the validated section value for ctx.config. */
281
+ async function checkNeeds(def, invocation) {
282
+ const needs = def.needs;
283
+ const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation) ?? await checkCredentials(needs, invocation);
284
+ if (failure !== void 0) return failure;
285
+ if (needs.config !== void 0) return checkConfiguration(needs.config, invocation);
286
+ return {
287
+ kind: "ok",
288
+ config: void 0
289
+ };
290
+ }
291
+ function checkInteraction(needs, invocation) {
292
+ if (!needs.interaction || invocation.state.interactive) return;
293
+ return needsErrored(new CliStructuredError("CLI.INTERACTION_REQUIRED", "This command requires an interactive terminal.", {
294
+ why: "It prompts for input that cannot be supplied when the session is not interactive (no TTY stdin, CI, or --no-interactive).",
295
+ nextActions: [{
296
+ kind: "user-choice",
297
+ label: "Run it from an interactive terminal, or pass --interactive."
298
+ }]
299
+ }));
300
+ }
301
+ function checkDependencies(needs, invocation) {
302
+ for (const specifier of needs.dependencies) if (!dependencyResolvable(specifier, invocation.runtime.cwd)) return needsErrored(missingDependencyError(specifier, invocation.runtime.packageManager));
303
+ }
304
+ async function checkCredentials(needs, invocation) {
305
+ if (!needs.credentials) return;
306
+ let credentials;
307
+ try {
308
+ credentials = await invocation.runtime.getCredentials();
309
+ } catch (cause) {
310
+ return needsErrored(new CliStructuredError("CLI.CREDENTIALS_UNREADABLE", "The stored credentials could not be read.", {
311
+ why: firstLine(cause instanceof Error ? cause.message : String(cause)),
312
+ nextActions: [{
313
+ kind: "user-choice",
314
+ label: "Sign in again to replace the stored credentials, then run the command again."
315
+ }]
316
+ }));
317
+ }
318
+ if (credentials === void 0) return needsErrored(credentialsRequiredError());
319
+ }
320
+ /** The single source of the sign-in error: raised by the needs check
321
+ * and by an unauthenticated ctx.api request. */
322
+ function credentialsRequiredError() {
323
+ return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [{
324
+ kind: "user-choice",
325
+ label: "Sign in, then run the command again."
326
+ }] });
327
+ }
328
+ function checkConfiguration(section, invocation) {
329
+ const fileLevel = invocation.runtime.config.diagnostics.filter((entry) => entry.section === null);
330
+ if (fileLevel.length > 0) return needsErrored(structuredErrorFromDiagnostic(fileLevel[0].diagnostic), fileLevel.slice(1).map((entry) => entry.diagnostic));
331
+ return validateConfigSection(section, invocation);
332
+ }
333
+ /** Validates the command's needed config section. The validator
334
+ * owns absence (it receives undefined when the section is missing) and
335
+ * never throws — a throw is an engine-boundary bug, settled as one. */
336
+ function validateConfigSection(section, invocation) {
337
+ const raw = invocation.runtime.config.sections[section.name];
338
+ let validation;
339
+ try {
340
+ validation = section.validate(raw);
341
+ } catch (cause) {
342
+ return {
343
+ kind: "bug",
344
+ cause: new Error(`@prisma/cli-engine: the '${section.name}' config section validator threw instead of returning diagnostics (a validator never throws)`, { cause })
345
+ };
346
+ }
347
+ if (!validation.ok) return needsErrored(new CliStructuredError("CLI.CONFIG_INVALID", `The '${section.name}' section of prisma.config.ts is invalid.`, { nextActions: [{
348
+ kind: "user-choice",
349
+ label: "Fix the reported problems in that section, then run the command again."
350
+ }] }), validation.diagnostics);
351
+ writeSectionWarnings(invocation, validation.diagnostics);
352
+ return {
353
+ kind: "ok",
354
+ config: validation.value
355
+ };
356
+ }
357
+ /** Diagnostics on an OK validation are warnings: written to stderr as
358
+ * commentary in both formats (stderr is free for commentary in json
359
+ * mode), filtered by the active log level, never added to the stream
360
+ * or the envelope. */
361
+ function writeSectionWarnings(invocation, diagnostics) {
362
+ const state = invocation.state;
363
+ for (const diagnostic of diagnostics) {
364
+ if (SEVERITY_RANK[diagnostic.severity] > SEVERITY_RANK[state.logLevel]) continue;
365
+ writeDiagnostic(invocation.runtime.stderr, withDocsUrl(state, diagnostic));
366
+ }
367
+ }
368
+ function dependencyResolvable(specifier, cwd) {
369
+ try {
370
+ createRequire(resolve(cwd, "__cli_engine_probe__.js")).resolve(specifier);
371
+ return true;
372
+ } catch {
373
+ return false;
374
+ }
375
+ }
376
+ function installCommand(packageManager, specifier) {
377
+ switch (packageManager) {
378
+ case "npm": return `npm install ${specifier}`;
379
+ case "pnpm": return `pnpm add ${specifier}`;
380
+ case "yarn": return `yarn add ${specifier}`;
381
+ case "bun": return `bun add ${specifier}`;
382
+ case "unknown": return;
383
+ }
384
+ }
385
+ /** Optional peer dependencies: the engine probes and phrases. */
386
+ function missingDependencyError(specifier, packageManager) {
387
+ const install = installCommand(packageManager, specifier);
388
+ return new CliStructuredError("CLI.MISSING_DEPENDENCY", `This command requires the optional dependency '${specifier}', which is not installed in this project.`, {
389
+ nextActions: [install === void 0 ? {
390
+ kind: "user-choice",
391
+ label: `Install '${specifier}' with your package manager, then run the command again.`
392
+ } : {
393
+ kind: "run-command",
394
+ label: `Install '${specifier}'`,
395
+ command: install
396
+ }],
397
+ meta: {
398
+ specifier,
399
+ ...install === void 0 ? {} : { installCommand: install }
400
+ }
401
+ });
402
+ }
403
+ //#endregion
404
+ //#region src/execution/api-client.ts
405
+ const CLIENT_ID = "";
406
+ const REDIRECT_URI = "";
407
+ /** ctx.api construction: the SDK reads tokens per request, so a token
408
+ * refreshed mid-run by the credentials source is picked up on the next
409
+ * request. A request while getCredentials() resolves undefined throws
410
+ * CLI.CREDENTIALS_REQUIRED.
411
+ *
412
+ * The SDK module itself is loaded lazily (dynamic import, mirroring
413
+ * the clack renderer pattern) and only when no `createSdk` test seam
414
+ * is injected, so a run that never issues a request never pays for —
415
+ * or depends on — the SDK module load. The returned client is a Proxy
416
+ * whose method wrappers await the lazy construction before applying
417
+ * the call; every client method is async, so the deferral is
418
+ * invisible to callers. */
419
+ function buildManagementApiClient(invocation) {
420
+ let clientPromise;
421
+ const resolveClient = () => {
422
+ clientPromise ??= constructClient(invocation);
423
+ return clientPromise;
424
+ };
425
+ return new Proxy({}, { get(_target, property) {
426
+ if (typeof property === "symbol" || property === "then") return;
427
+ return (...args) => resolveClient().then((client) => {
428
+ const value = Reflect.get(client, property);
429
+ if (typeof value !== "function") throw new TypeError(`@prisma/cli-engine: ctx.api.${property} is not a function`);
430
+ return Promise.resolve(Reflect.apply(value, client, args)).catch((cause) => {
431
+ throw restoreStructuredThrow(cause);
432
+ });
433
+ });
434
+ } });
435
+ }
436
+ async function constructClient(invocation) {
437
+ return (invocation.hooks.managementApi?.createSdk ?? (await import("@prisma/management-api-sdk")).createManagementApiSdk)({
438
+ clientId: CLIENT_ID,
439
+ redirectUri: REDIRECT_URI,
440
+ tokenStorage: {
441
+ getTokens: async () => {
442
+ const credentials = await invocation.runtime.getCredentials();
443
+ if (credentials === void 0) throw credentialsRequiredError();
444
+ return {
445
+ workspaceId: "",
446
+ accessToken: credentials.token
447
+ };
448
+ },
449
+ setTokens: async () => {},
450
+ clearTokens: async () => {}
451
+ },
452
+ apiBaseUrl: invocation.runtime.managementApi.baseUrl
453
+ }).client;
454
+ }
455
+ /** The SDK wraps every request failure in its FetchError; a structured
456
+ * error raised inside the request pipeline (the unauthenticated
457
+ * CLI.CREDENTIALS_REQUIRED throw) is rethrown unwrapped so it settles
458
+ * as itself. The SDK's own AuthError (a 401 the SDK cannot recover
459
+ * from — no refresh token is ever supplied here) maps to the same
460
+ * shared CLI.CREDENTIALS_REQUIRED error the needs check raises. */
461
+ function restoreStructuredThrow(cause) {
462
+ const structured = structuredCause(cause);
463
+ if (structured !== void 0) return structured;
464
+ if (causeChainHasSdkAuthError(cause)) return credentialsRequiredError();
465
+ return cause;
466
+ }
467
+ /** Cause chains can be cyclic (an Error whose `cause` eventually points
468
+ * back at itself); track visited nodes with a depth cap as a backstop
469
+ * so the walk always terminates. */
470
+ const CAUSE_CHAIN_DEPTH_CAP = 32;
471
+ function* causeChain(error) {
472
+ const visited = /* @__PURE__ */ new Set();
473
+ for (let current = error; current instanceof Error && !visited.has(current) && visited.size < CAUSE_CHAIN_DEPTH_CAP; current = current.cause) {
474
+ visited.add(current);
475
+ yield current;
476
+ }
477
+ }
478
+ function structuredCause(error) {
479
+ for (const current of causeChain(error)) if (CliStructuredError.is(current)) return current;
480
+ }
481
+ /** Structural match (name discriminator) rather than instanceof, so a
482
+ * duplicate SDK module instance cannot defeat the mapping — and so
483
+ * this check itself never forces the SDK module to load. */
484
+ function causeChainHasSdkAuthError(error) {
485
+ for (const current of causeChain(error)) if (current.name === "AuthError") return true;
486
+ return false;
487
+ }
488
+ //#endregion
489
+ //#region src/execution/clack-renderer.ts
490
+ /**
491
+ * Interactive prompt rendering backed by @clack/prompts, driven
492
+ * entirely by Runtime streams. Selected only when the runtime's stdin
493
+ * can enter raw mode (a real TTY); scripted answers, piped stdin, and
494
+ * the test harness stay on the plain line renderer (prompts.ts owns the
495
+ * branch). @clack/prompts is loaded by dynamic import here and nowhere
496
+ * else, so the module never touches non-interactive runs. Clack's
497
+ * spinner/log helpers install process-global handlers and must never be
498
+ * used: progress remains engine events.
499
+ *
500
+ * Accepted quirk: clack reads process.stdout.columns for wrap width —
501
+ * the one process-global read on the interactive path.
502
+ */
503
+ function clackCapable(runtime) {
504
+ return runtime.isTty.stdin && runtime.stdin.setRawMode !== void 0;
505
+ }
506
+ /** Presents the runtime's stdin to clack as a raw-mode-capable TTY. */
507
+ function toReadable(stdin) {
508
+ const readable = Readable.from(stdin, { objectMode: false });
509
+ Object.assign(readable, {
510
+ isTTY: true,
511
+ setRawMode: (enabled) => {
512
+ stdin.setRawMode?.(enabled);
513
+ return readable;
514
+ }
515
+ });
516
+ return readable;
517
+ }
518
+ function toWritable(out) {
519
+ return new Writable({ write(chunk, _encoding, callback) {
520
+ out.write(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
521
+ callback();
522
+ } });
523
+ }
524
+ async function makeClackRenderer(stdin, stderr) {
525
+ const clack = await import("@clack/prompts");
526
+ const input = toReadable(stdin);
527
+ const output = toWritable(stderr);
528
+ return {
529
+ confirm: (question, initial) => clack.confirm({
530
+ input,
531
+ output,
532
+ message: question,
533
+ initialValue: initial ?? false
534
+ }),
535
+ consent: (question) => clack.confirm({
536
+ input,
537
+ output,
538
+ message: question,
539
+ initialValue: false
540
+ }),
541
+ select: (question, options, initial) => clack.select({
542
+ input,
543
+ output,
544
+ message: question,
545
+ options: options.map((option) => ({
546
+ value: option.value,
547
+ label: option.label
548
+ })),
549
+ initialValue: initial
550
+ }),
551
+ text: (question, placeholder, fallback) => clack.text({
552
+ input,
553
+ output,
554
+ message: question,
555
+ placeholder,
556
+ defaultValue: fallback
557
+ }),
558
+ isCancel: (value) => clack.isCancel(value)
559
+ };
560
+ }
561
+ //#endregion
562
+ //#region src/execution/prompts.ts
563
+ function makeLineReader(stdin, invocation) {
564
+ const iterator = stdin[Symbol.asyncIterator]();
565
+ invocation.state.stdinIterator = iterator;
566
+ const decoder = new TextDecoder();
567
+ let buffer = "";
568
+ let done = false;
569
+ return async () => {
570
+ for (;;) {
571
+ const newline = buffer.indexOf("\n");
572
+ if (newline !== -1) {
573
+ const line = buffer.slice(0, newline);
574
+ buffer = buffer.slice(newline + 1);
575
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
576
+ }
577
+ if (done) {
578
+ if (buffer.length > 0) {
579
+ const line = buffer;
580
+ buffer = "";
581
+ return line;
582
+ }
583
+ return;
584
+ }
585
+ const next = await iterator.next();
586
+ if (next.done === true) {
587
+ done = true;
588
+ continue;
589
+ }
590
+ buffer += decoder.decode(next.value, { stream: true });
591
+ }
592
+ };
593
+ }
594
+ function promptCancelled(question) {
595
+ return new CliStructuredError("CLI.PROMPT_CANCELLED", `The prompt "${question}" was cancelled before it was answered.`);
596
+ }
597
+ function promptUnanswerable(question, state) {
598
+ return new CliStructuredError("CLI.PROMPT_REQUIRED", state.yes ? `--yes cannot answer "${question}" because the prompt has no default.` : `The command asked "${question}" but the session is not interactive and the prompt has no default.`, { nextActions: [{
599
+ kind: "user-choice",
600
+ label: "Run the command from an interactive terminal, or pass a flag that answers the prompt."
601
+ }] });
602
+ }
603
+ function consentUnavailable(question, state) {
604
+ return new CliStructuredError("CLI.CONSENT_REQUIRED", state.yes ? `"${question}" requires explicit consent, which --yes cannot grant.` : `"${question}" requires explicit consent, and the session is not interactive.`, { nextActions: [{
605
+ kind: "user-choice",
606
+ label: "Run the command interactively, or pass the command's explicit consent flag if it documents one."
607
+ }] });
608
+ }
609
+ function promptInvalid(question, raw) {
610
+ return new CliStructuredError("CLI.PROMPT_INVALID", `"${raw}" is not a valid answer to "${question}".`);
611
+ }
612
+ function isExplicitYes(raw) {
613
+ if (typeof raw === "boolean") return raw;
614
+ return [
615
+ "y",
616
+ "yes",
617
+ "true"
618
+ ].includes(raw.trim().toLowerCase());
619
+ }
620
+ function parseBooleanAnswer(raw, fallback, question) {
621
+ if (typeof raw === "boolean") return raw;
622
+ const normalized = raw.trim().toLowerCase();
623
+ if (normalized === "") return fallback ?? false;
624
+ if ([
625
+ "y",
626
+ "yes",
627
+ "true"
628
+ ].includes(normalized)) return true;
629
+ if ([
630
+ "n",
631
+ "no",
632
+ "false"
633
+ ].includes(normalized)) return false;
634
+ throw promptInvalid(question, raw);
635
+ }
636
+ function makePromptSurface(invocation) {
637
+ const { runtime, hooks, state } = invocation;
638
+ let readLine;
639
+ let answerCursor = 0;
640
+ let renderer;
641
+ const useClack = () => hooks.answers === void 0 && clackCapable(runtime);
642
+ const renderWithClack = async (question, run) => {
643
+ renderer ??= (() => {
644
+ const iterator = runtime.stdin[Symbol.asyncIterator]();
645
+ invocation.state.stdinIterator = iterator;
646
+ return makeClackRenderer({
647
+ [Symbol.asyncIterator]: () => iterator,
648
+ setRawMode: (enabled) => runtime.stdin.setRawMode?.(enabled)
649
+ }, runtime.stderr);
650
+ })();
651
+ const r = await renderer;
652
+ const value = await run(r);
653
+ if (r.isCancel(value)) throw promptCancelled(question);
654
+ return value;
655
+ };
656
+ const ask = async (question, rendered) => {
657
+ const answers = hooks.answers;
658
+ if (answers !== void 0) {
659
+ if (answerCursor >= answers.length) throw new Error(`@prisma/cli-engine: the run prompted ("${question}") past the scripted answers`);
660
+ const answer = answers[answerCursor];
661
+ answerCursor += 1;
662
+ return answer;
663
+ }
664
+ runtime.stderr.write(rendered);
665
+ readLine ??= makeLineReader(runtime.stdin, invocation);
666
+ const line = await readLine();
667
+ if (line === void 0) throw promptCancelled(question);
668
+ return line;
669
+ };
670
+ return {
671
+ confirm: async (question, opts) => {
672
+ const fallback = opts?.default;
673
+ if (state.yes || !state.interactive) {
674
+ if (fallback === void 0) throw promptUnanswerable(question, state);
675
+ return fallback;
676
+ }
677
+ if (useClack()) return renderWithClack(question, (r) => r.confirm(question, fallback));
678
+ let hint = "(y/n)";
679
+ if (fallback === true) hint = "(Y/n)";
680
+ else if (fallback === false) hint = "(y/N)";
681
+ return parseBooleanAnswer(await ask(question, `? ${question} ${hint} `), fallback, question);
682
+ },
683
+ consent: async (question) => {
684
+ if (state.yes || !state.interactive) throw consentUnavailable(question, state);
685
+ if (useClack()) return renderWithClack(question, (r) => r.consent(question));
686
+ return isExplicitYes(await ask(question, `? ${question} (y/n) `));
687
+ },
688
+ select: async (question, options, opts) => {
689
+ const fallback = opts?.default;
690
+ if (state.yes || !state.interactive) {
691
+ if (fallback === void 0) throw promptUnanswerable(question, state);
692
+ return fallback;
693
+ }
694
+ if (useClack()) return renderWithClack(question, (r) => r.select(question, options, fallback));
695
+ const raw = await ask(question, [
696
+ `? ${question}`,
697
+ ...options.map((option) => ` ${option.value === fallback ? "▸" : " "} ${option.value}: ${option.label}`),
698
+ "> "
699
+ ].join("\n"));
700
+ if (typeof raw !== "string") throw promptInvalid(question, String(raw));
701
+ const answer = raw.trim();
702
+ if (answer === "") {
703
+ if (fallback === void 0) throw promptInvalid(question, raw);
704
+ return fallback;
705
+ }
706
+ const match = options.find((option) => option.value === answer);
707
+ if (match === void 0) throw promptInvalid(question, raw);
708
+ return match.value;
709
+ },
710
+ text: async (question, opts) => {
711
+ const fallback = opts?.default;
712
+ if (state.yes || !state.interactive) {
713
+ if (fallback === void 0) throw promptUnanswerable(question, state);
714
+ return fallback;
715
+ }
716
+ if (useClack()) {
717
+ const value = await renderWithClack(question, (r) => r.text(question, opts?.placeholder, fallback));
718
+ return value === "" ? fallback ?? "" : value;
719
+ }
720
+ const raw = await ask(question, `? ${question}${fallback === void 0 ? "" : ` (${fallback})`} `);
721
+ if (typeof raw !== "string") throw promptInvalid(question, String(raw));
722
+ if (raw === "") return fallback ?? "";
723
+ return raw;
724
+ }
725
+ };
726
+ }
727
+ //#endregion
728
+ //#region src/execution/command-context.ts
729
+ function makeUi(colorEnabled) {
730
+ if (!colorEnabled) return {
731
+ emphasize: (text) => text,
732
+ dim: (text) => text,
733
+ code: (text) => `\`${text}\``
734
+ };
735
+ return {
736
+ emphasize: (text) => `\u001b[1m${text}\u001b[22m`,
737
+ dim: (text) => `\u001b[2m${text}\u001b[22m`,
738
+ code: (text) => `\`${text}\``
739
+ };
740
+ }
741
+ /** Materializes ONLY the active format's presentation functions, at the
742
+ * return site: human → human + stdout + next; json → json + next. */
743
+ function materializePresentation(state, ui, presentations) {
744
+ if (state.format === "json") return {
745
+ human: [],
746
+ stdout: [],
747
+ json: presentations.json?.(),
748
+ next: presentations.next?.() ?? []
749
+ };
750
+ return {
751
+ human: presentations.human(ui),
752
+ stdout: presentations.stdout?.() ?? [],
753
+ json: void 0,
754
+ next: presentations.next?.() ?? []
755
+ };
756
+ }
757
+ function makeContext(invocation, config) {
758
+ const state = invocation.state;
759
+ const ui = makeUi(state.colorEnabled);
760
+ const present = (outcome, presentations) => {
761
+ const exitCode = outcome.exitCode ?? 0;
762
+ const diagnostics = outcome.diagnostics ?? [];
763
+ if (exitCode === 0 && diagnostics.some((diagnostic) => diagnostic.severity === "error")) throw new Error("@prisma/cli-engine: a severity-'error' diagnostic requires a non-zero exitCode; a genuine could-not-complete belongs in notOk");
764
+ return Object.freeze({
765
+ [PRESENTED]: true,
766
+ data: outcome.data,
767
+ exitCode,
768
+ diagnostics,
769
+ presentation: materializePresentation(state, ui, presentations)
770
+ });
771
+ };
772
+ let api;
773
+ return {
774
+ config,
775
+ present,
776
+ getCredentials: () => invocation.runtime.getCredentials(),
777
+ get api() {
778
+ api ??= invocation.hooks.managementApi?.client ?? buildManagementApiClient(invocation);
779
+ return api;
780
+ },
781
+ report: (event) => reportEvent(invocation, event),
782
+ prompt: makePromptSurface(invocation),
783
+ signal: invocation.signal,
784
+ cwd: invocation.runtime.cwd,
785
+ env: invocation.runtime.env,
786
+ requireDependency: async (specifier) => dependencyResolvable(specifier, invocation.runtime.cwd) ? okVoid() : notOk(missingDependencyError(specifier, invocation.runtime.packageManager))
787
+ };
788
+ }
789
+ //#endregion
790
+ //#region src/execution/shared-flags.ts
791
+ /** The engine-injected shared flag family. Commands cannot declare
792
+ * these names or aliases; handlers never see their values. */
793
+ const RESERVED_FLAG_NAMES = new Set([
794
+ "format",
795
+ "json",
796
+ "logLevel",
797
+ "verbose",
798
+ "quiet",
799
+ "yes",
800
+ "interactive",
801
+ "color",
802
+ "help",
803
+ "helpAll",
804
+ "version"
805
+ ]);
806
+ const RESERVED_ALIASES = new Set([
807
+ "v",
808
+ "q",
809
+ "y",
810
+ "h"
811
+ ]);
812
+ const SHARED_FLAG_PARAMETERS = {
813
+ format: {
814
+ kind: "enum",
815
+ values: ["human", "json"],
816
+ optional: true,
817
+ brief: "Output format"
818
+ },
819
+ json: {
820
+ kind: "boolean",
821
+ default: false,
822
+ brief: "Shorthand for --format json"
823
+ },
824
+ logLevel: {
825
+ kind: "enum",
826
+ values: [
827
+ "error",
828
+ "warn",
829
+ "info",
830
+ "verbose"
831
+ ],
832
+ optional: true,
833
+ brief: "Commentary verbosity"
834
+ },
835
+ verbose: {
836
+ kind: "boolean",
837
+ default: false,
838
+ brief: "Shorthand for --log-level verbose"
839
+ },
840
+ quiet: {
841
+ kind: "boolean",
842
+ default: false,
843
+ brief: "Shorthand for --log-level error"
844
+ },
845
+ yes: {
846
+ kind: "boolean",
847
+ default: false,
848
+ brief: "Accept prompt defaults without asking"
849
+ },
850
+ interactive: {
851
+ kind: "boolean",
852
+ optional: true,
853
+ withNegated: true,
854
+ brief: "Force interactive prompts on or off"
855
+ },
856
+ color: {
857
+ kind: "boolean",
858
+ optional: true,
859
+ withNegated: true,
860
+ brief: "Force ANSI color on or off"
861
+ }
862
+ };
863
+ const SHARED_ALIASES = {
864
+ v: "verbose",
865
+ q: "quiet",
866
+ y: "yes"
867
+ };
868
+ /** The pre-parse format decision: json framing must be in effect before
869
+ * stricli parses (its own failure output is framed too), so the format
870
+ * flags are scanned from raw argv. */
871
+ function sniffFormat(argv, runtime) {
872
+ return explicitFormat(argv) ?? (runtime.isTty.stdout ? "human" : "json");
873
+ }
874
+ /** The format requested by --json / --format / --format=<value>, if
875
+ * any. Arguments after a bare `--` are positionals, never flags. */
876
+ function explicitFormat(argv) {
877
+ for (const [index, argument] of argv.entries()) {
878
+ if (argument === "--") return;
879
+ if (argument === "--json" || argument === "--format=json") return "json";
880
+ if (argument === "--format=human") return "human";
881
+ if (argument === "--format") {
882
+ const value = argv[index + 1];
883
+ if (value === "json" || value === "human") return value;
884
+ }
885
+ }
886
+ }
887
+ function applySharedFlags(state, shared, runtime) {
888
+ state.format = shared.format ?? resolveAutoFormat(shared, runtime);
889
+ state.yes = shared.yes === true;
890
+ state.interactive = shared.interactive ?? defaultInteractive(runtime);
891
+ state.logLevel = resolveLogLevel(shared);
892
+ state.colorEnabled = shared.color ?? (runtime.isTty.stdout && runtime.env.NO_COLOR === void 0);
893
+ }
894
+ /** Interactive iff TTY stdin outside CI; --interactive and
895
+ * --no-interactive override in either direction. Format never decides
896
+ * interactivity (operator ruling, 2026-08-09): an interactive json run
897
+ * may prompt — the prompt UI writes to stderr, so stdout stays a clean
898
+ * frame stream. */
899
+ function defaultInteractive(runtime) {
900
+ return runtime.isTty.stdin && runtime.env.CI === void 0;
901
+ }
902
+ function resolveAutoFormat(shared, runtime) {
903
+ if (shared.json === true) return "json";
904
+ return runtime.isTty.stdout ? "human" : "json";
905
+ }
906
+ /** --quiet and --verbose are log-level shorthands; either one beats an
907
+ * explicit --log-level given alongside it. */
908
+ function resolveLogLevel(shared) {
909
+ if (shared.quiet === true) return "error";
910
+ if (shared.verbose === true) return "verbose";
911
+ return shared.logLevel ?? "info";
912
+ }
913
+ //#endregion
914
+ //#region src/execution/command-snapshot.ts
915
+ /**
916
+ * Builds the value-free `EngineCommandSnapshot` for a mounted run —
917
+ * everything `RunHooks.onSettled` may reveal about the invocation.
918
+ * The projection happens at parse time from what the engine already
919
+ * knows: the command's declared flags, the raw argv tokens (consulted
920
+ * only for WHICH flag names appear, never for values), and the parsed
921
+ * positional slots (reduced to a count on the spot).
922
+ */
923
+ function kebabCase(key) {
924
+ return key.replace(/[A-Z]/g, (upper) => `-${upper.toLowerCase()}`);
925
+ }
926
+ function camelCase(raw) {
927
+ return raw.replace(/-([a-zA-Z0-9])/g, (_, char) => char.toUpperCase());
928
+ }
929
+ function declaredFlagKeys(def) {
930
+ const own = Object.keys(def.args.flags);
931
+ if (def.kind === "server-command") return own;
932
+ return [...Object.keys(SHARED_FLAG_PARAMETERS), ...own];
933
+ }
934
+ function aliasMap(def) {
935
+ const aliases = /* @__PURE__ */ new Map();
936
+ if (def.kind !== "server-command") for (const [alias, key] of Object.entries(SHARED_ALIASES)) aliases.set(alias, key);
937
+ for (const [key, spec] of Object.entries(def.args.flags)) {
938
+ const alias = flagRuntime(spec).alias;
939
+ if (alias !== void 0) aliases.set(alias, key);
940
+ }
941
+ return aliases;
942
+ }
943
+ /**
944
+ * The flag keys explicitly present on argv, resolved against the
945
+ * command's declared keys and aliases. Long tokens match in both the
946
+ * kebab and camel spellings (the scanner allows kebab-for-camel), a
947
+ * `--no-<flag>` token marks its base flag, and single-dash tokens are
948
+ * resolved character-by-character through the alias map. Everything
949
+ * after a bare `--` is positional and never consulted. Values are
950
+ * irrelevant here: `--name=value` is cut at the `=` before matching.
951
+ */
952
+ function explicitFlagKeys(def, declared, argv) {
953
+ const declaredSet = new Set(declared);
954
+ const aliases = aliasMap(def);
955
+ const explicit = /* @__PURE__ */ new Set();
956
+ for (const token of argv) {
957
+ if (token === "--") break;
958
+ if (token.startsWith("--")) {
959
+ const equals = token.indexOf("=");
960
+ const raw = token.slice(2, equals === -1 ? void 0 : equals);
961
+ const exact = camelCase(raw);
962
+ if (declaredSet.has(exact)) {
963
+ explicit.add(exact);
964
+ continue;
965
+ }
966
+ if (raw.startsWith("no-")) {
967
+ const negated = camelCase(raw.slice(3));
968
+ if (declaredSet.has(negated)) explicit.add(negated);
969
+ }
970
+ continue;
971
+ }
972
+ if (token.startsWith("-") && token.length > 1) for (const char of token.slice(1)) {
973
+ const key = aliases.get(char);
974
+ if (key !== void 0 && declaredSet.has(key)) explicit.add(key);
975
+ }
976
+ }
977
+ return explicit;
978
+ }
979
+ function buildCommandSnapshot(entryId, def, argv, positionalValues) {
980
+ const declared = declaredFlagKeys(def);
981
+ const explicit = explicitFlagKeys(def, declared, argv);
982
+ return {
983
+ commandPath: entryId.split("."),
984
+ flags: declared.map((key) => ({
985
+ name: kebabCase(key),
986
+ source: explicit.has(key) ? "cli" : "default"
987
+ })),
988
+ positionalCount: positionalValues.filter((value) => value !== void 0).length
989
+ };
990
+ }
991
+ //#endregion
992
+ //#region src/execution/command-tree.ts
993
+ function constructionError(message) {
994
+ return /* @__PURE__ */ new Error(`@prisma/cli-engine: ${message}`);
995
+ }
996
+ const CAMEL_CASE = /^[a-z][a-zA-Z0-9]*$/;
997
+ const INTEGER_LIKE = /^\d+$/;
998
+ function validateFlags(path, def) {
999
+ const flags = def.args.flags;
1000
+ const seenAliases = /* @__PURE__ */ new Set();
1001
+ for (const [key, spec] of Object.entries(flags)) {
1002
+ if (RESERVED_FLAG_NAMES.has(key)) throw constructionError(`command '${path}' declares reserved flag '${key}' (the shared flag family is engine-injected)`);
1003
+ if (!CAMEL_CASE.test(key)) throw constructionError(`command '${path}' flag '${key}' must be camelCase (it transliterates to --kebab-case on the CLI)`);
1004
+ const alias = flagRuntime(spec).alias;
1005
+ if (alias === void 0) continue;
1006
+ if (RESERVED_ALIASES.has(alias)) throw constructionError(`command '${path}' flag '${key}' uses reserved alias '-${alias}'`);
1007
+ if (seenAliases.has(alias)) throw constructionError(`command '${path}' declares alias '-${alias}' twice`);
1008
+ seenAliases.add(alias);
1009
+ }
1010
+ }
1011
+ function validatePositionals(path, def) {
1012
+ const entries = Object.entries(def.args.positionals);
1013
+ let sawOptional = false;
1014
+ for (const [index, [key, spec]] of entries.entries()) {
1015
+ const runtime = positionalRuntime(spec);
1016
+ if (INTEGER_LIKE.test(key)) throw constructionError(`command '${path}' positional key '${key}' must not be integer-like`);
1017
+ if (runtime.type === "variadic" && index !== entries.length - 1) throw constructionError(`command '${path}' variadic positional '${key}' must be declared last`);
1018
+ if (runtime.type === "optionalString") sawOptional = true;
1019
+ if (runtime.type === "string" && sawOptional) throw constructionError(`command '${path}' required positional '${key}' may not follow an optional one`);
1020
+ }
1021
+ }
1022
+ function validateExitCodes(path, def) {
1023
+ if (def.kind !== "result-command") return;
1024
+ for (const key of Object.keys(def.exitCodes)) {
1025
+ const code = Number(key);
1026
+ if (!Number.isInteger(code) || code < 4 || code > 99) throw constructionError(`command '${path}' documents exit code ${key}; documented codes must be integers in 4-99`);
1027
+ }
1028
+ }
1029
+ function emptyNode() {
1030
+ return {
1031
+ commands: /* @__PURE__ */ new Map(),
1032
+ children: /* @__PURE__ */ new Map()
1033
+ };
1034
+ }
1035
+ function insertCommand(root, path, def, docsBaseUrl) {
1036
+ const segments = path.split(" ");
1037
+ if (segments.some((segment) => segment.length === 0)) throw constructionError(`invalid command path '${path}'`);
1038
+ let node = root;
1039
+ for (const segment of segments.slice(0, -1)) {
1040
+ if (node.commands.has(segment)) throw constructionError(`command path '${path}' collides with a command mounted at a prefix of it`);
1041
+ let child = node.children.get(segment);
1042
+ if (child === void 0) {
1043
+ child = emptyNode();
1044
+ node.children.set(segment, child);
1045
+ }
1046
+ node = child;
1047
+ }
1048
+ const leaf = segments[segments.length - 1];
1049
+ if (node.commands.has(leaf) || node.children.has(leaf)) throw constructionError(`command path '${path}' collides with another mounted command`);
1050
+ node.commands.set(leaf, {
1051
+ def,
1052
+ id: segments.join("."),
1053
+ docsBaseUrl
1054
+ });
1055
+ }
1056
+ /** A command belongs to the family whose commands record contains it
1057
+ * (identity). Harness-mounted commands with no family are unowned. */
1058
+ function commandFamilyOf(spec, def) {
1059
+ return spec.commandFamilies.find((commandFamily) => Object.values(commandFamily.commands).includes(def));
1060
+ }
1061
+ function validateSectionOwnership(spec, path, def) {
1062
+ const section = def.needs.config;
1063
+ if (section === void 0) return;
1064
+ const commandFamily = commandFamilyOf(spec, def);
1065
+ if (commandFamily === void 0) return;
1066
+ if (commandFamily.configSection !== section) throw constructionError(`command '${path}' needs the '${section.name}' config section, which is not its command family's section`);
1067
+ }
1068
+ function validateDocsBaseUrls(spec) {
1069
+ for (const commandFamily of spec.commandFamilies) {
1070
+ const base = commandFamily.docsBaseUrl;
1071
+ if (base !== void 0 && !URL.canParse(base)) throw constructionError(`command family docsBaseUrl '${base}' is not a valid URL`);
1072
+ }
1073
+ }
1074
+ function buildCommandTree(spec) {
1075
+ const paths = Object.keys(spec.commands);
1076
+ if (paths.length === 0) throw constructionError("createCli requires at least one mounted command");
1077
+ validateDocsBaseUrls(spec);
1078
+ const root = emptyNode();
1079
+ for (const path of paths) {
1080
+ const def = spec.commands[path];
1081
+ validateFlags(path, def);
1082
+ validatePositionals(path, def);
1083
+ validateExitCodes(path, def);
1084
+ validateSectionOwnership(spec, path, def);
1085
+ const segments = path.split(" ");
1086
+ for (let depth = 1; depth < segments.length; depth += 1) {
1087
+ const groupPath = segments.slice(0, depth).join(" ");
1088
+ if (spec.groups[groupPath] === void 0) throw constructionError(`command path '${path}' references unknown group '${groupPath}' (declare it in createCli's groups)`);
1089
+ }
1090
+ insertCommand(root, path, def, commandFamilyOf(spec, def)?.docsBaseUrl);
1091
+ }
1092
+ return root;
1093
+ }
1094
+ //#endregion
1095
+ //#region src/execution/stricli-adapter.ts
1096
+ /**
1097
+ * The stricli boundary — fully internal: no stricli type appears in the
1098
+ * public surface, and stricli never owns process lifetime. Maps command
1099
+ * definitions onto stricli commands and captures stricli's own text so
1100
+ * it can be re-shaped into engine envelopes.
1101
+ */
1102
+ function parseNumberInput(input) {
1103
+ if (input.trim() === "") throw new Error("expected a number, received an empty value");
1104
+ const value = Number(input);
1105
+ if (!Number.isFinite(value)) throw new Error(`expected a number, received '${input}'`);
1106
+ return value;
1107
+ }
1108
+ function identity(input) {
1109
+ return input;
1110
+ }
1111
+ function stricliFlagParameter(spec) {
1112
+ switch (spec.type) {
1113
+ case "boolean": return {
1114
+ kind: "boolean",
1115
+ brief: spec.brief,
1116
+ default: false
1117
+ };
1118
+ case "enum": return {
1119
+ kind: "enum",
1120
+ brief: spec.brief,
1121
+ values: spec.values ?? [],
1122
+ ...spec.default === void 0 ? { optional: true } : { default: spec.default }
1123
+ };
1124
+ case "repeated": return {
1125
+ kind: "parsed",
1126
+ parse: identity,
1127
+ brief: spec.brief,
1128
+ placeholder: spec.placeholder,
1129
+ variadic: true,
1130
+ optional: true
1131
+ };
1132
+ case "number": return {
1133
+ kind: "parsed",
1134
+ parse: parseNumberInput,
1135
+ brief: spec.brief,
1136
+ placeholder: spec.placeholder,
1137
+ ...spec.default === void 0 ? { optional: true } : { default: String(spec.default) }
1138
+ };
1139
+ case "requiredString": return {
1140
+ kind: "parsed",
1141
+ parse: identity,
1142
+ brief: spec.brief,
1143
+ placeholder: spec.placeholder
1144
+ };
1145
+ case "string": return {
1146
+ kind: "parsed",
1147
+ parse: identity,
1148
+ brief: spec.brief,
1149
+ placeholder: spec.placeholder,
1150
+ ...spec.default === void 0 ? { optional: true } : { default: spec.default }
1151
+ };
1152
+ }
1153
+ }
1154
+ function stricliPositional(entries) {
1155
+ if (entries.length === 0) return;
1156
+ const variadic = entries.find(([, spec]) => spec.type === "variadic");
1157
+ if (variadic === void 0) return {
1158
+ kind: "tuple",
1159
+ parameters: entries.map(([, spec]) => ({
1160
+ brief: spec.brief,
1161
+ placeholder: spec.placeholder,
1162
+ parse: identity,
1163
+ ...spec.type === "optionalString" ? { optional: true } : {}
1164
+ }))
1165
+ };
1166
+ const minimum = entries.filter(([, spec]) => spec.type === "string").length;
1167
+ return {
1168
+ kind: "array",
1169
+ parameter: {
1170
+ brief: variadic[1].brief,
1171
+ placeholder: variadic[1].placeholder,
1172
+ parse: identity,
1173
+ optional: true
1174
+ },
1175
+ ...minimum > 0 ? { minimum } : {}
1176
+ };
1177
+ }
1178
+ function commandParameters(def) {
1179
+ const declaredFlags = {};
1180
+ const aliases = {};
1181
+ for (const [key, spec] of Object.entries(def.args.flags)) {
1182
+ const runtime = flagRuntime(spec);
1183
+ declaredFlags[key] = stricliFlagParameter(runtime);
1184
+ if (runtime.alias !== void 0) aliases[runtime.alias] = key;
1185
+ }
1186
+ const injectShared = def.kind !== "server-command";
1187
+ const positional = stricliPositional(Object.entries(def.args.positionals).map(([key, spec]) => [key, positionalRuntime(spec)]));
1188
+ return {
1189
+ flags: injectShared ? {
1190
+ ...SHARED_FLAG_PARAMETERS,
1191
+ ...declaredFlags
1192
+ } : declaredFlags,
1193
+ aliases: injectShared ? {
1194
+ ...SHARED_ALIASES,
1195
+ ...aliases
1196
+ } : aliases,
1197
+ ...positional === void 0 ? {} : { positional }
1198
+ };
1199
+ }
1200
+ /** Help examples never contain the binary name (operator ruling,
1201
+ * 2026-08-09): `{bin}` is substituted with the CLI name; an example
1202
+ * without `{bin}` gets the name prepended. */
1203
+ function resolveExample(example, cliName) {
1204
+ return example.includes("{bin}") ? example.replaceAll("{bin}", cliName) : `${cliName} ${example}`;
1205
+ }
1206
+ function commandDocs(def, cliName) {
1207
+ const examples = def.help.examples.map((example) => resolveExample(example, cliName));
1208
+ if (examples.length === 0) return {
1209
+ brief: def.help.summary,
1210
+ fullDescription: def.help.description
1211
+ };
1212
+ return {
1213
+ brief: def.help.summary,
1214
+ fullDescription: [
1215
+ def.help.description ?? def.help.summary,
1216
+ "",
1217
+ "Examples:",
1218
+ ...examples.map((example) => ` ${example}`)
1219
+ ].join("\n")
1220
+ };
1221
+ }
1222
+ function toStricliCommand(entry, cliName, runEntry) {
1223
+ return buildCommand({
1224
+ async func(flags, ...values) {
1225
+ await runEntry(this.invocation, entry, flags, values);
1226
+ },
1227
+ parameters: commandParameters(entry.def),
1228
+ docs: commandDocs(entry.def, cliName)
1229
+ });
1230
+ }
1231
+ function buildRoutes(spec, node, groupPath, runEntry) {
1232
+ const routes = {};
1233
+ for (const [name, entry] of node.commands) routes[name] = toStricliCommand(entry, spec.name, runEntry);
1234
+ for (const [name, child] of node.children) routes[name] = buildRoutes(spec, child, groupPath === "" ? name : `${groupPath} ${name}`, runEntry);
1235
+ return buildRouteMap({
1236
+ routes,
1237
+ docs: groupPath === "" ? { brief: spec.name } : {
1238
+ brief: spec.groups[groupPath].brief,
1239
+ fullDescription: spec.groups[groupPath].description
1240
+ }
1241
+ });
1242
+ }
1243
+ function capturingText(state) {
1244
+ return {
1245
+ ...text_en,
1246
+ exceptionWhileParsingArguments(exc, ansiColor) {
1247
+ const message = text_en.exceptionWhileParsingArguments.call(text_en, exc, ansiColor);
1248
+ state.usageErrorText = message;
1249
+ return message;
1250
+ },
1251
+ noCommandRegisteredForInput(args) {
1252
+ const message = text_en.noCommandRegisteredForInput(args);
1253
+ state.usageErrorText = message;
1254
+ return message;
1255
+ },
1256
+ exceptionWhileLoadingCommandFunction(exc, ansiColor) {
1257
+ const message = text_en.exceptionWhileLoadingCommandFunction.call(text_en, exc, ansiColor);
1258
+ state.internalErrorText = message;
1259
+ return message;
1260
+ },
1261
+ exceptionWhileRunningCommand(exc, ansiColor) {
1262
+ const message = text_en.exceptionWhileRunningCommand.call(text_en, exc, ansiColor);
1263
+ state.internalErrorText = message;
1264
+ return message;
1265
+ }
1266
+ };
1267
+ }
1268
+ function usageErrorCode(stricliExitCode) {
1269
+ if (stricliExitCode === -5) return "CLI.UNKNOWN_COMMAND";
1270
+ if (stricliExitCode === -4) return "CLI.INVALID_ARGUMENTS";
1271
+ }
1272
+ //#endregion
1273
+ //#region src/execution/settlement.ts
1274
+ function undocumentedExitCode(def, exitCode) {
1275
+ if (exitCode === 0) return;
1276
+ if ((def.kind === "result-command" ? Object.keys(def.exitCodes).map(Number) : []).includes(exitCode)) return;
1277
+ return /* @__PURE__ */ new Error(`@prisma/cli-engine: the handler completed with exit code ${exitCode}, which is not 0 or one of the command's documented exit codes`);
1278
+ }
1279
+ function settleCompleted(invocation, def, presented) {
1280
+ if (typeof presented !== "object" || presented === null || presented[PRESENTED] !== true) {
1281
+ settleBug(invocation, /* @__PURE__ */ new Error("@prisma/cli-engine: a handler returned ok(...) without a PresentedResult built by ctx.present"));
1282
+ return;
1283
+ }
1284
+ const violation = undocumentedExitCode(def, presented.exitCode);
1285
+ if (violation !== void 0) {
1286
+ settleBug(invocation, violation);
1287
+ return;
1288
+ }
1289
+ const state = invocation.state;
1290
+ invocation.hooks.onPresented?.(presented);
1291
+ state.settledExitCode = presented.exitCode;
1292
+ if (state.format === "json") {
1293
+ emitFrame(invocation, {
1294
+ kind: "result",
1295
+ envelope: {
1296
+ ok: true,
1297
+ commandId: state.commandId,
1298
+ result: presented.presentation.json === void 0 ? presented.data : presented.presentation.json,
1299
+ exitCode: presented.exitCode,
1300
+ diagnostics: presented.diagnostics.map((diagnostic) => withDocsUrl(state, diagnostic)),
1301
+ nextActions: presented.presentation.next
1302
+ },
1303
+ commandId: state.commandId,
1304
+ timestamp: invocation.now().toISOString()
1305
+ });
1306
+ return;
1307
+ }
1308
+ renderCompletedHuman(invocation, presented);
1309
+ }
1310
+ function diagnosticOf(error) {
1311
+ const { ok: _ok, ...diagnostic } = error.toEnvelope();
1312
+ return diagnostic;
1313
+ }
1314
+ function settleErrored(invocation, error, diagnostics = []) {
1315
+ const state = invocation.state;
1316
+ state.settledExitCode = error.code === "CLI.PROMPT_CANCELLED" ? 3 : 2;
1317
+ emitErrored(invocation, {
1318
+ ok: false,
1319
+ commandId: state.commandId,
1320
+ error: diagnosticOf(error),
1321
+ diagnostics,
1322
+ nextActions: error.nextActions
1323
+ });
1324
+ }
1325
+ /** Signal exit codes: 130 SIGINT, 143 SIGTERM. The engine's own
1326
+ * controller only ever aborts with a signal name. */
1327
+ function signalExitCode(reason) {
1328
+ return reason === "SIGTERM" ? 143 : 130;
1329
+ }
1330
+ function isAbortCause(cause, signal) {
1331
+ if (!signal.aborted) return false;
1332
+ if (cause === signal.reason) return true;
1333
+ return cause instanceof Error && cause.name === "AbortError";
1334
+ }
1335
+ function settleThrown(invocation, cause) {
1336
+ if (isAbortCause(cause, invocation.signal)) settleAborted(invocation);
1337
+ else if (CliStructuredError.is(cause)) settleErrored(invocation, cause);
1338
+ else settleBug(invocation, cause);
1339
+ }
1340
+ function settleAborted(invocation) {
1341
+ const state = invocation.state;
1342
+ state.settledExitCode = signalExitCode(invocation.signal.reason);
1343
+ emitErrored(invocation, {
1344
+ ok: false,
1345
+ commandId: state.commandId,
1346
+ error: {
1347
+ code: "CLI.ABORTED",
1348
+ severity: "error",
1349
+ summary: "The command was aborted before it completed.",
1350
+ nextActions: []
1351
+ },
1352
+ diagnostics: [],
1353
+ nextActions: []
1354
+ });
1355
+ }
1356
+ /** A session command that returned ok — including after the signal
1357
+ * fired — shut down cleanly: exit 0, no presentation. In json mode the
1358
+ * stream still terminates with exactly one result frame. */
1359
+ function settleSessionCompleted(invocation) {
1360
+ const state = invocation.state;
1361
+ state.settledExitCode = 0;
1362
+ if (state.format !== "json") return;
1363
+ emitFrame(invocation, {
1364
+ kind: "result",
1365
+ envelope: {
1366
+ ok: true,
1367
+ commandId: state.commandId,
1368
+ result: null,
1369
+ exitCode: 0,
1370
+ diagnostics: [],
1371
+ nextActions: []
1372
+ },
1373
+ commandId: state.commandId,
1374
+ timestamp: invocation.now().toISOString()
1375
+ });
1376
+ }
1377
+ function settleBug(invocation, cause) {
1378
+ const state = invocation.state;
1379
+ state.settledExitCode = 1;
1380
+ emitErrored(invocation, {
1381
+ ok: false,
1382
+ commandId: state.commandId,
1383
+ error: {
1384
+ code: "CLI.INTERNAL_ERROR",
1385
+ severity: "error",
1386
+ summary: firstLine(cause instanceof Error ? cause.message : String(cause)),
1387
+ nextActions: []
1388
+ },
1389
+ diagnostics: [],
1390
+ nextActions: []
1391
+ });
1392
+ }
1393
+ function emitErrored(invocation, raw) {
1394
+ const state = invocation.state;
1395
+ const envelope = {
1396
+ ...raw,
1397
+ error: withDocsUrl(state, raw.error),
1398
+ diagnostics: raw.diagnostics.map((diagnostic) => withDocsUrl(state, diagnostic))
1399
+ };
1400
+ if (state.format === "json") {
1401
+ emitFrame(invocation, {
1402
+ kind: "result",
1403
+ envelope,
1404
+ commandId: envelope.commandId,
1405
+ timestamp: invocation.now().toISOString()
1406
+ });
1407
+ return;
1408
+ }
1409
+ const stderr = invocation.runtime.stderr;
1410
+ writeDiagnostic(stderr, envelope.error);
1411
+ for (const diagnostic of envelope.diagnostics) writeDiagnostic(stderr, diagnostic);
1412
+ }
1413
+ /** `--version` prints createCli's version and exits 0. In json mode the
1414
+ * version travels as the run's single result frame. */
1415
+ function settleVersion(spec, invocation) {
1416
+ const { runtime, state } = invocation;
1417
+ if (state.format === "human") {
1418
+ runtime.stdout.write(`${spec.version}\n`);
1419
+ return 0;
1420
+ }
1421
+ emitFrame(invocation, {
1422
+ kind: "result",
1423
+ envelope: {
1424
+ ok: true,
1425
+ commandId: "version",
1426
+ result: { version: spec.version },
1427
+ exitCode: 0,
1428
+ diagnostics: [],
1429
+ nextActions: []
1430
+ },
1431
+ commandId: "version",
1432
+ timestamp: invocation.now().toISOString()
1433
+ });
1434
+ return 0;
1435
+ }
1436
+ /** Maps stricli's own settlement (parse/route failures, framework bugs)
1437
+ * onto the engine protocol when the pipeline never settled. A failure
1438
+ * addressed at a server command renders to stderr — a foreign client on
1439
+ * the other end of stdout must never receive an engine envelope. */
1440
+ function settleUnhandled(spec, invocation, stricliExitCode) {
1441
+ const state = invocation.state;
1442
+ const raw = typeof stricliExitCode === "number" ? stricliExitCode : 0;
1443
+ if (raw === 0) return 0;
1444
+ const segments = state.prefix[0] === spec.name ? state.prefix.slice(1) : state.prefix;
1445
+ if (spec.commands[segments.join(" ")]?.kind === "server-command") state.format = "human";
1446
+ const usage = usageErrorCode(raw) !== void 0;
1447
+ const captured = usage ? state.stricliStderr.trim() : state.usageErrorText ?? state.internalErrorText ?? state.stricliStderr.trim();
1448
+ const full = captured.length > 0 ? captured : "The command failed unexpectedly";
1449
+ const summary = firstLine(full);
1450
+ const remainder = full.slice(full.indexOf("\n") + 1).trim();
1451
+ emitErrored(invocation, {
1452
+ ok: false,
1453
+ commandId: segments.join("."),
1454
+ error: {
1455
+ code: usageErrorCode(raw) ?? "CLI.INTERNAL_ERROR",
1456
+ severity: "error",
1457
+ summary,
1458
+ ...usage && full.includes("\n") && remainder.length > 0 ? { why: remainder } : {},
1459
+ nextActions: []
1460
+ },
1461
+ diagnostics: [],
1462
+ nextActions: []
1463
+ });
1464
+ return usage ? 2 : 1;
1465
+ }
1466
+ //#endregion
1467
+ //#region src/execution/engine.ts
1468
+ function buildEngine(spec, options) {
1469
+ return new EngineImpl(spec, options?.now);
1470
+ }
1471
+ var EngineImpl = class {
1472
+ spec;
1473
+ root;
1474
+ now;
1475
+ constructor(spec, now = () => /* @__PURE__ */ new Date()) {
1476
+ this.spec = spec;
1477
+ this.now = now;
1478
+ this.root = buildRoutes(spec, buildCommandTree(spec), "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
1479
+ }
1480
+ async execute(argv, runtime, hooks) {
1481
+ const state = {
1482
+ commandId: "",
1483
+ docsBaseUrl: void 0,
1484
+ prefix: [],
1485
+ format: sniffFormat(argv, runtime),
1486
+ logLevel: "info",
1487
+ yes: false,
1488
+ interactive: defaultInteractive(runtime),
1489
+ colorEnabled: false,
1490
+ resolved: false,
1491
+ settledExitCode: void 0,
1492
+ usageErrorText: void 0,
1493
+ internalErrorText: void 0,
1494
+ stricliStderr: "",
1495
+ stdinIterator: void 0,
1496
+ argv,
1497
+ snapshot: void 0
1498
+ };
1499
+ const startedAtMs = this.now().getTime();
1500
+ const controller = new AbortController();
1501
+ let signalDelivered = false;
1502
+ const unsubscribe = runtime.onSignal((signal) => {
1503
+ if (signalDelivered) {
1504
+ runtime.exit(signal === "SIGTERM" ? 143 : 130);
1505
+ return;
1506
+ }
1507
+ signalDelivered = true;
1508
+ controller.abort(signal);
1509
+ });
1510
+ const invocation = {
1511
+ runtime,
1512
+ hooks: { ...hooks },
1513
+ now: this.now,
1514
+ state,
1515
+ signal: controller.signal
1516
+ };
1517
+ if (versionRequested(argv)) {
1518
+ unsubscribe();
1519
+ return settleVersion(this.spec, invocation);
1520
+ }
1521
+ const stricliProcess = {
1522
+ /** stricli writes only help text here. In json mode stdout carries
1523
+ * exactly the frame stream, so help prose goes to stderr instead. */
1524
+ stdout: { write: (text) => (state.format === "human" ? runtime.stdout : runtime.stderr).write(text) },
1525
+ stderr: { write: (text) => {
1526
+ state.stricliStderr += text;
1527
+ } },
1528
+ env: {
1529
+ ...runtime.env,
1530
+ STRICLI_NO_COLOR: "1"
1531
+ },
1532
+ exitCode: void 0
1533
+ };
1534
+ const app = buildApplication(this.root, {
1535
+ name: this.spec.name,
1536
+ scanner: {
1537
+ caseStyle: "allow-kebab-for-camel",
1538
+ allowArgumentEscapeSequence: true
1539
+ },
1540
+ localization: { text: capturingText(state) }
1541
+ });
1542
+ try {
1543
+ await run(app, [...argv], {
1544
+ process: stricliProcess,
1545
+ forCommand: (info) => {
1546
+ state.prefix = info.prefix;
1547
+ return {
1548
+ process: stricliProcess,
1549
+ invocation
1550
+ };
1551
+ }
1552
+ });
1553
+ } finally {
1554
+ unsubscribe();
1555
+ await state.stdinIterator?.return?.();
1556
+ }
1557
+ const exitCode = state.settledExitCode !== void 0 ? state.settledExitCode : settleUnhandled(this.spec, invocation, stricliProcess.exitCode);
1558
+ this.fireOnSettled(invocation, exitCode, startedAtMs);
1559
+ return exitCode;
1560
+ }
1561
+ /** The onSettled delivery: once per run, after the exit code is
1562
+ * final, only for runs that mounted a command (--help, --version,
1563
+ * and pre-mount usage errors leave no snapshot and fire nothing).
1564
+ * A throwing hook is swallowed — observation must not break runs. */
1565
+ fireOnSettled(invocation, exitCode, startedAtMs) {
1566
+ const { state, hooks } = invocation;
1567
+ if (state.snapshot === void 0 || hooks.onSettled === void 0) return;
1568
+ const summary = {
1569
+ commandId: state.commandId,
1570
+ exitCode,
1571
+ durationMs: this.now().getTime() - startedAtMs,
1572
+ snapshot: state.snapshot
1573
+ };
1574
+ try {
1575
+ hooks.onSettled(summary);
1576
+ } catch {}
1577
+ }
1578
+ async executeMounted(invocation, entry, rawFlags, values) {
1579
+ const state = invocation.state;
1580
+ state.commandId = entry.id;
1581
+ state.docsBaseUrl = entry.docsBaseUrl;
1582
+ state.snapshot = buildCommandSnapshot(entry.id, entry.def, state.argv, values);
1583
+ if (entry.def.kind === "server-command") {
1584
+ await this.executeServer(invocation, entry, rawFlags);
1585
+ return;
1586
+ }
1587
+ let needsOutcome;
1588
+ try {
1589
+ applySharedFlags(state, rawFlags, invocation.runtime);
1590
+ needsOutcome = await checkNeeds(entry.def, invocation);
1591
+ } catch (cause) {
1592
+ settleBug(invocation, cause);
1593
+ return;
1594
+ }
1595
+ if (needsOutcome.kind === "errored") {
1596
+ settleErrored(invocation, needsOutcome.error, needsOutcome.diagnostics);
1597
+ return;
1598
+ }
1599
+ if (needsOutcome.kind === "bug") {
1600
+ settleBug(invocation, needsOutcome.cause);
1601
+ return;
1602
+ }
1603
+ const handler = entry.def.handler;
1604
+ const args = {
1605
+ flags: declaredFlags(entry.def, rawFlags),
1606
+ positionals: distributePositionals(entry.def, values)
1607
+ };
1608
+ const ctx = makeContext(invocation, needsOutcome.config);
1609
+ if (entry.def.kind === "session-command") {
1610
+ try {
1611
+ const result = await handler(args, ctx);
1612
+ state.resolved = true;
1613
+ if (result.ok) settleSessionCompleted(invocation);
1614
+ else settleErrored(invocation, result.failure);
1615
+ } catch (cause) {
1616
+ state.resolved = true;
1617
+ settleThrown(invocation, cause);
1618
+ }
1619
+ return;
1620
+ }
1621
+ try {
1622
+ const result = await handler(args, ctx);
1623
+ state.resolved = true;
1624
+ if (result.ok) settleCompleted(invocation, entry.def, result.value);
1625
+ else settleErrored(invocation, result.failure);
1626
+ } catch (cause) {
1627
+ state.resolved = true;
1628
+ settleThrown(invocation, cause);
1629
+ }
1630
+ }
1631
+ /** The stdio handoff: a foreign client owns the conversation, so the
1632
+ * engine hands over the streams and stays out of stdout. The handler
1633
+ * returns the exit code directly; there is no envelope. */
1634
+ async executeServer(invocation, entry, rawFlags) {
1635
+ const state = invocation.state;
1636
+ state.format = "human";
1637
+ let needsOutcome;
1638
+ try {
1639
+ needsOutcome = await checkNeeds(entry.def, invocation);
1640
+ } catch (cause) {
1641
+ settleBug(invocation, cause);
1642
+ return;
1643
+ }
1644
+ if (needsOutcome.kind === "errored") {
1645
+ settleErrored(invocation, needsOutcome.error, needsOutcome.diagnostics);
1646
+ return;
1647
+ }
1648
+ if (needsOutcome.kind === "bug") {
1649
+ settleBug(invocation, needsOutcome.cause);
1650
+ return;
1651
+ }
1652
+ const handler = entry.def.handler;
1653
+ const runtime = invocation.runtime;
1654
+ const args = {
1655
+ flags: declaredFlags(entry.def, rawFlags),
1656
+ positionals: {}
1657
+ };
1658
+ try {
1659
+ const exitCode = await handler(args, {
1660
+ stdin: runtime.stdin,
1661
+ stdout: runtime.stdout,
1662
+ stderr: runtime.stderr,
1663
+ signal: invocation.signal,
1664
+ cwd: runtime.cwd,
1665
+ env: runtime.env,
1666
+ config: needsOutcome.config
1667
+ });
1668
+ if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > 255) {
1669
+ settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: the '${entry.id}' server command returned exit code ${String(exitCode)}, which is not an integer in 0-255`));
1670
+ return;
1671
+ }
1672
+ state.settledExitCode = exitCode;
1673
+ } catch (cause) {
1674
+ settleThrown(invocation, cause);
1675
+ }
1676
+ }
1677
+ };
1678
+ function versionRequested(argv) {
1679
+ for (const argument of argv) {
1680
+ if (argument === "--") return false;
1681
+ if (argument === "--version") return true;
1682
+ }
1683
+ return false;
1684
+ }
1685
+ function declaredFlags(def, rawFlags) {
1686
+ const flags = {};
1687
+ for (const key of Object.keys(def.args.flags)) flags[key] = rawFlags[key];
1688
+ return flags;
1689
+ }
1690
+ function distributePositionals(def, values) {
1691
+ const positionals = {};
1692
+ let cursor = 0;
1693
+ for (const [key, spec] of Object.entries(def.args.positionals)) if (positionalRuntime(spec).type === "variadic") {
1694
+ positionals[key] = values.slice(cursor).filter((value) => value !== void 0);
1695
+ cursor = values.length;
1696
+ } else {
1697
+ positionals[key] = values[cursor];
1698
+ cursor += 1;
1699
+ }
1700
+ return positionals;
1701
+ }
1702
+ //#endregion
1703
+ export { positional as i, PRESENTED as n, flag as r, buildEngine as t };