@prisma/cli-engine 0.0.2 → 0.0.3

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.
@@ -3,6 +3,7 @@ import { createRequire } from "node:module";
3
3
  import { buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
4
4
  import { resolve } from "node:path";
5
5
  import { Readable, Writable } from "node:stream";
6
+ import { Buffer } from "node:buffer";
6
7
  //#region src/args.ts
7
8
  function flagRuntime(spec) {
8
9
  return spec;
@@ -94,6 +95,49 @@ const positional = {
94
95
  }
95
96
  };
96
97
  //#endregion
98
+ //#region src/spawn.ts
99
+ const CHILD_STATUS = Symbol.for("@prisma/cli-engine.childStatus");
100
+ /** Signal numbers shared by Linux, macOS and the BSDs. Numbers that
101
+ * differ by platform (SIGBUS, SIGUSR1, SIGUSR2, …) are deliberately
102
+ * absent — a wrong 128+n is worse than the unknown-signal fallback. */
103
+ const SIGNAL_NUMBERS = {
104
+ SIGHUP: 1,
105
+ SIGINT: 2,
106
+ SIGQUIT: 3,
107
+ SIGILL: 4,
108
+ SIGTRAP: 5,
109
+ SIGABRT: 6,
110
+ SIGFPE: 8,
111
+ SIGKILL: 9,
112
+ SIGSEGV: 11,
113
+ SIGPIPE: 13,
114
+ SIGALRM: 14,
115
+ SIGTERM: 15
116
+ };
117
+ /** A signal-killed child settles 128 + the signal number; otherwise the
118
+ * child's own exit code, verbatim. Unknown is never success: a signal
119
+ * outside the portable table, or an adapter that cannot say how the
120
+ * child ended (exitCode and signal both null), settles 1. */
121
+ function exitWithChildStatus(child, options) {
122
+ const nextActions = Object.freeze([...options?.nextActions ?? []]);
123
+ if (child.signal !== null) {
124
+ const signalNumber = SIGNAL_NUMBERS[child.signal];
125
+ return Object.freeze({
126
+ [CHILD_STATUS]: true,
127
+ exitCode: signalNumber === void 0 ? 1 : 128 + signalNumber,
128
+ nextActions
129
+ });
130
+ }
131
+ return Object.freeze({
132
+ [CHILD_STATUS]: true,
133
+ exitCode: child.exitCode ?? 1,
134
+ nextActions
135
+ });
136
+ }
137
+ function isChildStatusSettlement(value) {
138
+ return typeof value === "object" && value !== null && value[CHILD_STATUS] === true;
139
+ }
140
+ //#endregion
97
141
  //#region src/presentation.ts
98
142
  const PRESENTED = Symbol.for("prisma.cli-engine.presented");
99
143
  //#endregion
@@ -109,13 +153,17 @@ const useSessionAction = {
109
153
  };
110
154
  /**
111
155
  * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
112
- * identically by the needs check, ctx.session, and the engine's
113
- * request path.
156
+ * identically by the needs check, ctx.activeCredential, and the
157
+ * engine's request path.
114
158
  */
115
159
  function credentialsRequiredError(reason = "unauthenticated") {
116
160
  switch (reason) {
117
161
  case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
118
162
  case "expired": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session has expired — sign in again.", { nextActions: [signInAction] });
163
+ case "expiring-soon": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session expires too soon to run this command — sign in again.", {
164
+ why: "This command hands your credentials to another program, which cannot refresh them while it runs.",
165
+ nextActions: [signInAction]
166
+ });
119
167
  case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
120
168
  why: "It was ended while the command was running (for example by another prisma process).",
121
169
  nextActions: [useSessionAction, signInAction]
@@ -149,9 +197,25 @@ function credentialRejectedError(origin, envVar) {
149
197
  return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
150
198
  }
151
199
  /**
200
+ * A credential's workspace_id claim disagrees with the workspace it is
201
+ * being stored under, or a rotated token would re-scope a session.
202
+ * Raised by every CredentialManager, so a test sees what production
203
+ * raises.
204
+ */
205
+ function credentialWorkspaceMismatchError(workspaceId) {
206
+ return new CliStructuredError("AUTH.CREDENTIAL_WORKSPACE_MISMATCH", "That credential belongs to a different workspace.", {
207
+ why: `The token's workspace_id claim does not name workspace '${workspaceId}'.`,
208
+ nextActions: [{
209
+ kind: "run-command",
210
+ label: "Sign in again and pick the workspace you want",
211
+ command: "prisma auth login"
212
+ }]
213
+ });
214
+ }
215
+ /**
152
216
  * The env var that supplies a session is set to a blank value. The one
153
- * structured error for it, raised identically by currentSession(), the
154
- * needs check, and the engine's request path.
217
+ * structured error for it, raised identically by activeCredential(),
218
+ * the needs check, and the engine's request path.
155
219
  */
156
220
  function emptyServiceTokenError(spec) {
157
221
  return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
@@ -179,6 +243,10 @@ function noSessionForWorkspaceError(workspaceRef) {
179
243
  }] });
180
244
  }
181
245
  /**
246
+ * Module-private on purpose: `credentialRejectedError` is the one place
247
+ * wording differs by origin (§11.1), and exporting this would be a
248
+ * second door into the environment-specific text that bypasses it.
249
+ *
182
250
  * The management API rejected the env-supplied service token (401).
183
251
  * There is no refresh for it and nothing stored is cleared.
184
252
  */
@@ -204,7 +272,7 @@ function makeDebugLog(runtime) {
204
272
  }
205
273
  //#endregion
206
274
  //#region src/execution/api-client.ts
207
- const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
275
+ const SERVICE_TOKEN_ENV_VAR$1 = "PRISMA_SERVICE_TOKEN";
208
276
  /**
209
277
  * ctx.api: the ENGINE constructs and owns the management API client —
210
278
  * ONE client for the active credential, once per run (process pinning
@@ -322,11 +390,18 @@ async function mapRequestFailure(invocation, debug, probe, pinned, cause) {
322
390
  return authServiceError();
323
391
  }
324
392
  if (cameFromRefresh) debug(`refresh failed: refreshTokenInvalid=${String(authError.refreshTokenInvalid === true)} error=${endpointVerdict(authError.message)}`);
325
- if (authError.refreshTokenInvalid === true) return credentialsRequiredError("expired");
326
393
  const manager = invocation.runtime.credentialManager;
327
- if (manager === void 0 || pinned === void 0) return authServiceError();
328
- if (cameFromRefresh && await couldNeverHaveBeenRenewed(pinned.storage)) return credentialRejectedError(pinned.active.origin, SERVICE_TOKEN_ENV_VAR);
329
- return mapAgainstStoredState(manager, pinned.active, cause);
394
+ if (manager === void 0 || pinned === void 0) return authError.refreshTokenInvalid === true ? credentialsRequiredError("expired") : authServiceError();
395
+ const homeRecord = hasHomeRecord(pinned.active);
396
+ if (authError.refreshTokenInvalid === true) return homeRecord ? credentialsRequiredError("expired") : credentialRejectedError(pinned.active.origin, SERVICE_TOKEN_ENV_VAR$1);
397
+ if (cameFromRefresh && await couldNeverHaveBeenRenewed(pinned.storage)) return credentialRejectedError(pinned.active.origin, SERVICE_TOKEN_ENV_VAR$1);
398
+ return homeRecord ? mapAgainstStoredState(manager, pinned.active, cause) : authServiceError();
399
+ }
400
+ /** Whether this credential is backed by a stored session. The origin
401
+ * is the only thing that answers it, which is why the credential-
402
+ * rejected error is allowed to read it (§11.1). */
403
+ function hasHomeRecord(active) {
404
+ return active.origin.source === "stored";
330
405
  }
331
406
  /**
332
407
  * A 401 that could never have been renewed: the SDK refused to reach
@@ -399,6 +474,247 @@ function endpointVerdict(message) {
399
474
  return description === -1 ? message : message.slice(0, description);
400
475
  }
401
476
  //#endregion
477
+ //#region src/execution/shared-flags.ts
478
+ /** The engine-injected shared flag family. Commands cannot declare
479
+ * these names or aliases; handlers never see their values. */
480
+ const RESERVED_FLAG_NAMES = new Set([
481
+ "format",
482
+ "json",
483
+ "logLevel",
484
+ "verbose",
485
+ "quiet",
486
+ "yes",
487
+ "confirm",
488
+ "interactive",
489
+ "color",
490
+ "help",
491
+ "helpAll",
492
+ "version"
493
+ ]);
494
+ const RESERVED_ALIASES = new Set([
495
+ "v",
496
+ "q",
497
+ "y",
498
+ "h"
499
+ ]);
500
+ const SHARED_FLAG_PARAMETERS = {
501
+ format: {
502
+ kind: "enum",
503
+ values: ["human", "json"],
504
+ optional: true,
505
+ brief: "Output format"
506
+ },
507
+ json: {
508
+ kind: "boolean",
509
+ default: false,
510
+ brief: "Shorthand for --format json"
511
+ },
512
+ logLevel: {
513
+ kind: "enum",
514
+ values: [
515
+ "error",
516
+ "warn",
517
+ "info",
518
+ "verbose"
519
+ ],
520
+ optional: true,
521
+ brief: "Commentary verbosity"
522
+ },
523
+ verbose: {
524
+ kind: "boolean",
525
+ default: false,
526
+ brief: "Shorthand for --log-level verbose"
527
+ },
528
+ quiet: {
529
+ kind: "boolean",
530
+ default: false,
531
+ brief: "Shorthand for --log-level error"
532
+ },
533
+ yes: {
534
+ kind: "boolean",
535
+ default: false,
536
+ brief: "Accept prompt defaults without asking"
537
+ },
538
+ confirm: {
539
+ kind: "parsed",
540
+ parse: (input) => input,
541
+ placeholder: "value",
542
+ variadic: true,
543
+ optional: true,
544
+ brief: "Grant a consent prompt non-interactively by typing its token (repeatable)"
545
+ },
546
+ interactive: {
547
+ kind: "boolean",
548
+ optional: true,
549
+ withNegated: true,
550
+ brief: "Force interactive prompts on or off"
551
+ },
552
+ color: {
553
+ kind: "boolean",
554
+ optional: true,
555
+ withNegated: true,
556
+ brief: "Force ANSI color on or off"
557
+ }
558
+ };
559
+ const SHARED_ALIASES = {
560
+ v: "verbose",
561
+ q: "quiet",
562
+ y: "yes"
563
+ };
564
+ /** The pre-parse format decision: json framing must be in effect before
565
+ * stricli parses (its own failure output is framed too), so the format
566
+ * flags are scanned from raw argv. */
567
+ function sniffFormat(argv, runtime) {
568
+ return explicitFormat(argv) ?? (runtime.isTty.stdout ? "human" : "json");
569
+ }
570
+ /** The format requested by --json / --format / --format=<value>, if
571
+ * any. Arguments after a bare `--` are positionals, never flags. */
572
+ function explicitFormat(argv) {
573
+ for (const [index, argument] of argv.entries()) {
574
+ if (argument === "--") return;
575
+ if (argument === "--json" || argument === "--format=json") return "json";
576
+ if (argument === "--format=human") return "human";
577
+ if (argument === "--format") {
578
+ const value = argv[index + 1];
579
+ if (value === "json" || value === "human") return value;
580
+ }
581
+ }
582
+ }
583
+ function applySharedFlags(state, shared, runtime) {
584
+ state.format = shared.format ?? resolveAutoFormat(shared, runtime);
585
+ state.yes = shared.yes === true;
586
+ state.confirmValues = [...shared.confirm ?? []];
587
+ state.interactive = shared.interactive ?? defaultInteractive(runtime);
588
+ state.logLevel = resolveLogLevel(shared);
589
+ state.colorEnabled = shared.color ?? (runtime.isTty.stdout && runtime.env.NO_COLOR === void 0);
590
+ }
591
+ /** Interactive iff TTY stdin outside CI; --interactive and
592
+ * --no-interactive override in either direction. Format never decides
593
+ * interactivity (operator ruling, 2026-08-09): an interactive json run
594
+ * may prompt — the prompt UI writes to stderr, so stdout stays a clean
595
+ * frame stream. */
596
+ function defaultInteractive(runtime) {
597
+ return runtime.isTty.stdin && runtime.env.CI === void 0;
598
+ }
599
+ function resolveAutoFormat(shared, runtime) {
600
+ if (shared.json === true) return "json";
601
+ return runtime.isTty.stdout ? "human" : "json";
602
+ }
603
+ /** --quiet and --verbose are log-level shorthands; either one beats an
604
+ * explicit --log-level given alongside it. */
605
+ function resolveLogLevel(shared) {
606
+ if (shared.quiet === true) return "error";
607
+ if (shared.verbose === true) return "verbose";
608
+ return shared.logLevel ?? "info";
609
+ }
610
+ //#endregion
611
+ //#region src/execution/command-tree.ts
612
+ function constructionError(message) {
613
+ return /* @__PURE__ */ new Error(`@prisma/cli-engine: ${message}`);
614
+ }
615
+ const CAMEL_CASE = /^[a-z][a-zA-Z0-9]*$/;
616
+ const INTEGER_LIKE = /^\d+$/;
617
+ function validateFlags(path, def) {
618
+ const flags = def.args.flags;
619
+ const seenAliases = /* @__PURE__ */ new Set();
620
+ for (const [key, spec] of Object.entries(flags)) {
621
+ if (RESERVED_FLAG_NAMES.has(key)) throw constructionError(`command '${path}' declares reserved flag '${key}' (the shared flag family is engine-injected)`);
622
+ if (!CAMEL_CASE.test(key)) throw constructionError(`command '${path}' flag '${key}' must be camelCase (it transliterates to --kebab-case on the CLI)`);
623
+ const alias = flagRuntime(spec).alias;
624
+ if (alias === void 0) continue;
625
+ if (RESERVED_ALIASES.has(alias)) throw constructionError(`command '${path}' flag '${key}' uses reserved alias '-${alias}'`);
626
+ if (seenAliases.has(alias)) throw constructionError(`command '${path}' declares alias '-${alias}' twice`);
627
+ seenAliases.add(alias);
628
+ }
629
+ }
630
+ function validatePositionals(path, def) {
631
+ const entries = Object.entries(def.args.positionals);
632
+ let sawOptional = false;
633
+ for (const [index, [key, spec]] of entries.entries()) {
634
+ const runtime = positionalRuntime(spec);
635
+ if (INTEGER_LIKE.test(key)) throw constructionError(`command '${path}' positional key '${key}' must not be integer-like`);
636
+ if (runtime.type === "variadic" && index !== entries.length - 1) throw constructionError(`command '${path}' variadic positional '${key}' must be declared last`);
637
+ if (runtime.type === "optionalString") sawOptional = true;
638
+ if (runtime.type === "string" && sawOptional) throw constructionError(`command '${path}' required positional '${key}' may not follow an optional one`);
639
+ }
640
+ }
641
+ function validateExitCodes(path, def) {
642
+ if (def.kind !== "result-command") return;
643
+ for (const key of Object.keys(def.exitCodes)) {
644
+ const code = Number(key);
645
+ if (!Number.isInteger(code) || code < 4 || code > 99) throw constructionError(`command '${path}' documents exit code ${key}; documented codes must be integers in 4-99`);
646
+ }
647
+ }
648
+ function validateSpawnDeclarations(path, def) {
649
+ if (def.needs.credentials === "child" && !def.maySpawn) throw constructionError(`command '${path}' needs credentials for a child without declaring maySpawn (there is nothing to hand credentials to)`);
650
+ }
651
+ function emptyNode() {
652
+ return {
653
+ commands: /* @__PURE__ */ new Map(),
654
+ children: /* @__PURE__ */ new Map()
655
+ };
656
+ }
657
+ function insertCommand(root, path, def, docsBaseUrl) {
658
+ const segments = path.split(" ");
659
+ if (segments.some((segment) => segment.length === 0)) throw constructionError(`invalid command path '${path}'`);
660
+ let node = root;
661
+ for (const segment of segments.slice(0, -1)) {
662
+ if (node.commands.has(segment)) throw constructionError(`command path '${path}' collides with a command mounted at a prefix of it`);
663
+ let child = node.children.get(segment);
664
+ if (child === void 0) {
665
+ child = emptyNode();
666
+ node.children.set(segment, child);
667
+ }
668
+ node = child;
669
+ }
670
+ const leaf = segments[segments.length - 1];
671
+ if (node.commands.has(leaf) || node.children.has(leaf)) throw constructionError(`command path '${path}' collides with another mounted command`);
672
+ node.commands.set(leaf, {
673
+ def,
674
+ id: segments.join("."),
675
+ docsBaseUrl
676
+ });
677
+ }
678
+ /** A command belongs to the family whose commands record contains it
679
+ * (identity). Harness-mounted commands with no family are unowned. */
680
+ function commandFamilyOf(spec, def) {
681
+ return spec.commandFamilies.find((commandFamily) => Object.values(commandFamily.commands).includes(def));
682
+ }
683
+ function validateSectionOwnership(spec, path, def) {
684
+ const section = def.needs.config;
685
+ if (section === void 0) return;
686
+ const commandFamily = commandFamilyOf(spec, def);
687
+ if (commandFamily === void 0) return;
688
+ if (commandFamily.configSection !== section) throw constructionError(`command '${path}' needs the '${section.name}' config section, which is not its command family's section`);
689
+ }
690
+ function validateDocsBaseUrls(spec) {
691
+ for (const commandFamily of spec.commandFamilies) {
692
+ const base = commandFamily.docsBaseUrl;
693
+ if (base !== void 0 && !URL.canParse(base)) throw constructionError(`command family docsBaseUrl '${base}' is not a valid URL`);
694
+ }
695
+ }
696
+ function buildCommandTree(spec) {
697
+ const paths = Object.keys(spec.commands);
698
+ if (paths.length === 0) throw constructionError("createCli requires at least one mounted command");
699
+ validateDocsBaseUrls(spec);
700
+ const root = emptyNode();
701
+ for (const path of paths) {
702
+ const def = spec.commands[path];
703
+ validateFlags(path, def);
704
+ validatePositionals(path, def);
705
+ validateExitCodes(path, def);
706
+ validateSpawnDeclarations(path, def);
707
+ validateSectionOwnership(spec, path, def);
708
+ const segments = path.split(" ");
709
+ for (let depth = 1; depth < segments.length; depth += 1) {
710
+ const groupPath = segments.slice(0, depth).join(" ");
711
+ if (spec.groups[groupPath] === void 0) throw constructionError(`command path '${path}' references unknown group '${groupPath}' (declare it in createCli's groups)`);
712
+ }
713
+ insertCommand(root, path, def, commandFamilyOf(spec, def)?.docsBaseUrl);
714
+ }
715
+ return root;
716
+ }
717
+ //#endregion
402
718
  //#region src/execution/rendering.ts
403
719
  function firstLine(text) {
404
720
  const newline = text.indexOf("\n");
@@ -518,8 +834,6 @@ function renderCompletedHuman(invocation, presented) {
518
834
  for (const diagnostic of presented.diagnostics) writeDiagnostic(runtime.stderr, withDocsUrl(state, diagnostic));
519
835
  for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
520
836
  }
521
- //#endregion
522
- //#region src/execution/reporting.ts
523
837
  const SEVERITY_RANK = {
524
838
  error: 0,
525
839
  warn: 1,
@@ -546,6 +860,15 @@ function reportEvent(invocation, event) {
546
860
  reportAfterResolution(invocation);
547
861
  return;
548
862
  }
863
+ const terminal = state.delegatedTerminal;
864
+ if (terminal !== void 0) {
865
+ if (terminal.buffered.length >= 1e3) {
866
+ terminal.dropped += 1;
867
+ return;
868
+ }
869
+ terminal.buffered.push(event);
870
+ return;
871
+ }
549
872
  invocation.hooks.onEvent?.(event);
550
873
  const severity = eventDisplaySeverity(event);
551
874
  if (severity !== void 0 && SEVERITY_RANK[severity] > SEVERITY_RANK[state.logLevel]) return;
@@ -559,12 +882,18 @@ function reportEvent(invocation, event) {
559
882
  }
560
883
  renderEventHuman(invocation, event);
561
884
  }
885
+ function flushBufferedEvents(invocation, terminal) {
886
+ for (const event of terminal.buffered) reportEvent(invocation, event);
887
+ if (terminal.dropped > 0) reportEvent(invocation, {
888
+ kind: "message",
889
+ severity: "warn",
890
+ text: `${terminal.dropped} buffered event${terminal.dropped === 1 ? "" : "s"} dropped while a child owned the terminal`
891
+ });
892
+ }
562
893
  function emitFrame(invocation, frame) {
563
894
  invocation.runtime.stdout.write(`${JSON.stringify(frame)}\n`);
564
895
  invocation.hooks.onStreamEvent?.(frame);
565
896
  }
566
- //#endregion
567
- //#region src/execution/needs.ts
568
897
  function needsErrored(error, diagnostics = []) {
569
898
  return {
570
899
  kind: "errored",
@@ -589,12 +918,21 @@ function structuredErrorFromDiagnostic(diagnostic) {
589
918
  * success it carries the validated section value for ctx.config. */
590
919
  async function checkNeeds(def, invocation) {
591
920
  const needs = def.needs;
592
- const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation) ?? await checkCredentials(needs, invocation);
921
+ const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation);
593
922
  if (failure !== void 0) return failure;
594
- if (needs.config !== void 0) return checkConfiguration(needs.config, invocation);
923
+ const credentials = await checkCredentials(needs, invocation);
924
+ if (credentials.failure !== void 0) return credentials.failure;
925
+ if (needs.config !== void 0) {
926
+ const outcome = checkConfiguration(needs.config, invocation);
927
+ return outcome.kind === "ok" ? {
928
+ ...outcome,
929
+ spawnCredential: credentials.spawnCredential
930
+ } : outcome;
931
+ }
595
932
  return {
596
933
  kind: "ok",
597
- config: void 0
934
+ config: void 0,
935
+ spawnCredential: credentials.spawnCredential
598
936
  };
599
937
  }
600
938
  function checkInteraction(needs, invocation) {
@@ -617,18 +955,33 @@ function checkDependencies(needs, invocation) {
617
955
  * pass through verbatim so the needs check, ctx.activeCredential, and
618
956
  * ctx.api raise identically. A host with no manager wired has no
619
957
  * credentials at all.
958
+ *
959
+ * The `"child"` form resolves the same credential ONCE, additionally
960
+ * refuses a session about to expire — before the handler runs, not
961
+ * before the spawn: the work that precedes a spawn creates real
962
+ * platform resources, and the child cannot refresh the snapshot it is
963
+ * given — and carries the credential forward for the spawn path.
620
964
  */
621
965
  async function checkCredentials(needs, invocation) {
622
- if (!needs.credentials) return;
966
+ if (needs.credentials === false) return {};
623
967
  const manager = invocation.runtime.credentialManager;
624
- if (manager === void 0) return needsErrored(credentialsRequiredError());
968
+ if (manager === void 0) return { failure: needsErrored(credentialsRequiredError()) };
969
+ let credential;
625
970
  try {
626
- if (await manager.activeCredential() === null) return needsErrored(credentialsRequiredError());
627
- return;
971
+ credential = await manager.activeCredential();
628
972
  } catch (cause) {
629
- if (CliStructuredError.is(cause)) return needsErrored(cause);
973
+ if (CliStructuredError.is(cause)) return { failure: needsErrored(cause) };
630
974
  throw cause;
631
975
  }
976
+ if (credential === null) return { failure: needsErrored(credentialsRequiredError()) };
977
+ if (needs.credentials !== "child") return {};
978
+ const expiry = nearExpiryFailure(credential, invocation);
979
+ return expiry === void 0 ? { spawnCredential: credential } : { failure: expiry };
980
+ }
981
+ function nearExpiryFailure(credential, invocation) {
982
+ if (credential.expiresAt === void 0) return;
983
+ if (credential.expiresAt.getTime() - invocation.now().getTime() > 3e5) return;
984
+ return needsErrored(credentialsRequiredError("expiring-soon"));
632
985
  }
633
986
  function checkConfiguration(section, invocation) {
634
987
  const fileLevel = invocation.runtime.config.diagnostics.filter((entry) => entry.section === null);
@@ -656,7 +1009,8 @@ function validateConfigSection(section, invocation) {
656
1009
  writeSectionWarnings(invocation, validation.diagnostics);
657
1010
  return {
658
1011
  kind: "ok",
659
- config: validation.value
1012
+ config: validation.value,
1013
+ spawnCredential: void 0
660
1014
  };
661
1015
  }
662
1016
  /** Diagnostics on an OK validation are warnings: written to stderr as
@@ -971,7 +1325,13 @@ function makePromptSurface(invocation) {
971
1325
  if (typeof typed !== "string" || typed.trim() !== token) throw consentTokenMismatch(question, token, String(typed));
972
1326
  return true;
973
1327
  };
974
- return {
1328
+ /** A prompt writes to stderr and reads the engine's stdin — the same
1329
+ * terminal a live child inherited. Like ctx.present, prompting while
1330
+ * a child owns the terminal is a construction error. */
1331
+ const requireOwnTerminal = () => {
1332
+ if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.prompt while a child owned the terminal`);
1333
+ };
1334
+ const surface = {
975
1335
  confirm: async (question, opts) => {
976
1336
  const fallback = opts?.default;
977
1337
  if (state.yes || !state.interactive) {
@@ -1046,212 +1406,269 @@ function makePromptSurface(invocation) {
1046
1406
  }
1047
1407
  }
1048
1408
  };
1049
- }
1050
- //#endregion
1051
- //#region src/execution/command-context.ts
1052
- function makeUi(colorEnabled) {
1053
- if (!colorEnabled) return {
1054
- emphasize: (text) => text,
1055
- dim: (text) => text,
1056
- code: (text) => `\`${text}\``
1409
+ /** The claim is taken synchronously, before the prompt's first await:
1410
+ * a handler that starts a prompt without awaiting it has already
1411
+ * begun reading stdin, so ctx.spawn must not hand the same terminal
1412
+ * to a child. */
1413
+ const claimTerminal = async (prompt) => {
1414
+ requireOwnTerminal();
1415
+ state.activePrompts += 1;
1416
+ try {
1417
+ return await prompt();
1418
+ } finally {
1419
+ state.activePrompts -= 1;
1420
+ }
1057
1421
  };
1058
1422
  return {
1059
- emphasize: (text) => `\u001b[1m${text}\u001b[22m`,
1060
- dim: (text) => `\u001b[2m${text}\u001b[22m`,
1061
- code: (text) => `\`${text}\``
1423
+ confirm: (question, opts) => claimTerminal(() => surface.confirm(question, opts)),
1424
+ consent: (question, opts) => claimTerminal(() => surface.consent(question, opts)),
1425
+ select: (question, options, opts) => claimTerminal(() => surface.select(question, options, opts)),
1426
+ text: (question, opts) => claimTerminal(() => surface.text(question, opts)),
1427
+ browserWait: (request) => claimTerminal(() => surface.browserWait(request))
1062
1428
  };
1063
1429
  }
1064
- /** Materializes ONLY the active format's presentation functions, at the
1065
- * return site: human → human + stdout + next; json → json + next. */
1066
- function materializePresentation(state, ui, presentations) {
1067
- if (state.format === "json") return {
1068
- human: [],
1069
- stdout: [],
1070
- json: presentations.json?.(),
1071
- next: presentations.next?.() ?? []
1072
- };
1073
- return {
1074
- human: presentations.human(ui),
1075
- stdout: presentations.stdout?.() ?? [],
1076
- json: void 0,
1077
- next: presentations.next?.() ?? []
1430
+ //#endregion
1431
+ //#region src/execution/spawn.ts
1432
+ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
1433
+ const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
1434
+ /**
1435
+ * D1 ruling (S3): how long a child terminated by a programmatic abort
1436
+ * has to exit on its own after SIGTERM before the engine sends SIGKILL.
1437
+ */
1438
+ const CHILD_TERMINATION_GRACE_MS = 5e3;
1439
+ /** A signal delivered while a child owns the terminal: recorded for
1440
+ * replay, never acted on. SIGTERM has no native path to the child —
1441
+ * supervisors signal the engine's pid — so it is forwarded (a SIGTERM
1442
+ * recorded before the adapter has returned the child is forwarded the
1443
+ * moment it attaches). A SECOND recorded signal forwards SIGTERM too:
1444
+ * when the engine was signalled directly (no process group delivered
1445
+ * the first press to the child), the second press is the user's
1446
+ * escalation, and without the forward the child would be unreachable. */
1447
+ function recordSignalDuringSpawn(terminal, signal) {
1448
+ terminal.recorded.push(signal);
1449
+ if (signal === "SIGTERM" || terminal.recorded.length > 1) terminal.child?.kill("SIGTERM");
1450
+ }
1451
+ function makeSpawn(invocation, def) {
1452
+ return async (options) => {
1453
+ const state = invocation.state;
1454
+ if (!def.maySpawn) throw constructionError(`command '${state.commandId}' called ctx.spawn without declaring maySpawn`);
1455
+ if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.spawn while a child was still live (one live child per run)`);
1456
+ if (state.activePrompts > 0) throw constructionError(`command '${state.commandId}' called ctx.spawn while a prompt owned the terminal`);
1457
+ const spawnChild = invocation.runtime.spawn;
1458
+ if (spawnChild === void 0) throw new Error("@prisma/cli-engine: the command declares maySpawn but the Runtime supplies no spawn adapter");
1459
+ const terminal = {
1460
+ recorded: [],
1461
+ buffered: [],
1462
+ dropped: 0,
1463
+ child: void 0,
1464
+ termination: new AbortController(),
1465
+ ended: Promise.resolve()
1466
+ };
1467
+ state.delegatedTerminal = terminal;
1468
+ const running = runDelegated(invocation, def, terminal, spawnChild, options);
1469
+ terminal.ended = running.then(() => void 0, () => void 0);
1470
+ return await running;
1078
1471
  };
1079
1472
  }
1080
- function makeContext(invocation, config, managesCredentials) {
1473
+ async function runDelegated(invocation, def, terminal, spawnChild, options) {
1081
1474
  const state = invocation.state;
1082
- const ui = makeUi(state.colorEnabled);
1083
- const present = (outcome, presentations) => {
1084
- const exitCode = outcome.exitCode ?? 0;
1085
- const diagnostics = outcome.diagnostics ?? [];
1086
- 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");
1087
- return Object.freeze({
1088
- [PRESENTED]: true,
1089
- data: outcome.data,
1090
- exitCode,
1091
- diagnostics,
1092
- presentation: materializePresentation(state, ui, presentations)
1093
- });
1094
- };
1095
- let api;
1096
- const context = {
1097
- config,
1098
- present,
1099
- activeCredential: () => invocation.runtime.credentialManager?.activeCredential() ?? Promise.resolve(null),
1100
- get api() {
1101
- api ??= invocation.hooks.managementApi?.client ?? buildManagementApiClient(invocation);
1102
- return api;
1103
- },
1104
- report: (event) => reportEvent(invocation, event),
1105
- prompt: makePromptSurface(invocation),
1106
- openUrl: (request) => announceUrl(invocation, request),
1107
- signal: invocation.signal,
1108
- cwd: invocation.runtime.cwd,
1109
- env: invocation.runtime.env,
1110
- requireDependency: async (specifier) => dependencyResolvable(specifier, invocation.runtime.cwd) ? okVoid() : notOk(missingDependencyError(specifier, invocation.runtime.packageManager))
1111
- };
1112
- if (managesCredentials) Object.defineProperty(context, "credentialManager", {
1113
- enumerable: true,
1114
- get() {
1115
- const manager = invocation.runtime.credentialManager;
1116
- if (manager === void 0) throw new Error("@prisma/cli-engine: the command declares managesCredentials but the Runtime supplies no credentialManager");
1117
- return manager;
1475
+ const debug = makeDebugLog(invocation.runtime);
1476
+ try {
1477
+ const request = {
1478
+ command: options.command,
1479
+ args: options.args ?? [],
1480
+ cwd: options.cwd ?? invocation.runtime.cwd,
1481
+ env: await composeChildEnv(invocation, def, options.env)
1482
+ };
1483
+ debug(`spawn: ${request.command} ${request.args.join(" ")} (cwd ${request.cwd})`);
1484
+ const result = await runChild(invocation, terminal, spawnChild, request);
1485
+ debug(`spawn ended: exitCode=${String(result.exitCode)} signal=${String(result.signal)} recorded=[${terminal.recorded.join(",")}]`);
1486
+ return result;
1487
+ } finally {
1488
+ state.delegatedTerminal = void 0;
1489
+ if (!state.resolved) {
1490
+ flushBufferedEvents(invocation, terminal);
1491
+ replayRecordedSignals(invocation, terminal.recorded);
1118
1492
  }
1119
- });
1120
- return context;
1121
- }
1122
- //#endregion
1123
- //#region src/execution/shared-flags.ts
1124
- /** The engine-injected shared flag family. Commands cannot declare
1125
- * these names or aliases; handlers never see their values. */
1126
- const RESERVED_FLAG_NAMES = new Set([
1127
- "format",
1128
- "json",
1129
- "logLevel",
1130
- "verbose",
1131
- "quiet",
1132
- "yes",
1133
- "confirm",
1134
- "interactive",
1135
- "color",
1136
- "help",
1137
- "helpAll",
1138
- "version"
1139
- ]);
1140
- const RESERVED_ALIASES = new Set([
1141
- "v",
1142
- "q",
1143
- "y",
1144
- "h"
1145
- ]);
1146
- const SHARED_FLAG_PARAMETERS = {
1147
- format: {
1148
- kind: "enum",
1149
- values: ["human", "json"],
1150
- optional: true,
1151
- brief: "Output format"
1152
- },
1153
- json: {
1154
- kind: "boolean",
1155
- default: false,
1156
- brief: "Shorthand for --format json"
1157
- },
1158
- logLevel: {
1159
- kind: "enum",
1160
- values: [
1161
- "error",
1162
- "warn",
1163
- "info",
1164
- "verbose"
1165
- ],
1166
- optional: true,
1167
- brief: "Commentary verbosity"
1168
- },
1169
- verbose: {
1170
- kind: "boolean",
1171
- default: false,
1172
- brief: "Shorthand for --log-level verbose"
1173
- },
1174
- quiet: {
1175
- kind: "boolean",
1176
- default: false,
1177
- brief: "Shorthand for --log-level error"
1178
- },
1179
- yes: {
1180
- kind: "boolean",
1181
- default: false,
1182
- brief: "Accept prompt defaults without asking"
1183
- },
1184
- confirm: {
1185
- kind: "parsed",
1186
- parse: (input) => input,
1187
- placeholder: "value",
1188
- variadic: true,
1189
- optional: true,
1190
- brief: "Grant a consent prompt non-interactively by typing its token (repeatable)"
1191
- },
1192
- interactive: {
1193
- kind: "boolean",
1194
- optional: true,
1195
- withNegated: true,
1196
- brief: "Force interactive prompts on or off"
1197
- },
1198
- color: {
1199
- kind: "boolean",
1200
- optional: true,
1201
- withNegated: true,
1202
- brief: "Force ANSI color on or off"
1203
1493
  }
1204
- };
1205
- const SHARED_ALIASES = {
1206
- v: "verbose",
1207
- q: "quiet",
1208
- y: "yes"
1209
- };
1210
- /** The pre-parse format decision: json framing must be in effect before
1211
- * stricli parses (its own failure output is framed too), so the format
1212
- * flags are scanned from raw argv. */
1213
- function sniffFormat(argv, runtime) {
1214
- return explicitFormat(argv) ?? (runtime.isTty.stdout ? "human" : "json");
1215
1494
  }
1216
- /** The format requested by --json / --format / --format=<value>, if
1217
- * any. Arguments after a bare `--` are positionals, never flags. */
1218
- function explicitFormat(argv) {
1219
- for (const [index, argument] of argv.entries()) {
1220
- if (argument === "--") return;
1221
- if (argument === "--json" || argument === "--format=json") return "json";
1222
- if (argument === "--format=human") return "human";
1223
- if (argument === "--format") {
1224
- const value = argv[index + 1];
1225
- if (value === "json" || value === "human") return value;
1495
+ /** A handler that resolved or threw with its child still live: the
1496
+ * engine ends the child on the abort ladder and waits for it, because
1497
+ * the engine outliving the child is not negotiable. */
1498
+ async function endAbandonedChild(terminal) {
1499
+ terminal.termination.abort();
1500
+ await terminal.ended;
1501
+ }
1502
+ async function runChild(invocation, terminal, spawnChild, request) {
1503
+ let child;
1504
+ try {
1505
+ child = spawnChild(request);
1506
+ } catch (cause) {
1507
+ throw spawnFailedError(request.command, cause);
1508
+ }
1509
+ terminal.child = child;
1510
+ if (terminal.recorded.includes("SIGTERM") || terminal.recorded.length > 1) child.kill("SIGTERM");
1511
+ const ended = new AbortController();
1512
+ armTerminationLadder(invocation, terminal, child, ended.signal);
1513
+ try {
1514
+ return await child.ended;
1515
+ } catch (cause) {
1516
+ throw spawnFailedError(request.command, cause);
1517
+ } finally {
1518
+ ended.abort();
1519
+ }
1520
+ }
1521
+ /** A programmatic abort of ctx.signal (a delivered signal is recorded
1522
+ * instead), or the engine ending a child the handler abandoned,
1523
+ * terminates the child: SIGTERM, the grace period, SIGKILL. */
1524
+ function armTerminationLadder(invocation, terminal, child, ended) {
1525
+ const debug = makeDebugLog(invocation.runtime);
1526
+ const terminate = async () => {
1527
+ if (ended.aborted) return;
1528
+ debug(`spawn abort ladder: SIGTERM, ${CHILD_TERMINATION_GRACE_MS}ms grace`);
1529
+ child.kill("SIGTERM");
1530
+ await invocation.delay(CHILD_TERMINATION_GRACE_MS, ended);
1531
+ if (!ended.aborted) {
1532
+ debug("spawn abort ladder: grace elapsed, SIGKILL");
1533
+ child.kill("SIGKILL");
1226
1534
  }
1535
+ };
1536
+ const trigger = AbortSignal.any([invocation.signal, terminal.termination.signal]);
1537
+ if (trigger.aborted) {
1538
+ terminate();
1539
+ return;
1227
1540
  }
1541
+ trigger.addEventListener("abort", () => void terminate(), {
1542
+ once: true,
1543
+ signal: ended
1544
+ });
1228
1545
  }
1229
- function applySharedFlags(state, shared, runtime) {
1230
- state.format = shared.format ?? resolveAutoFormat(shared, runtime);
1231
- state.yes = shared.yes === true;
1232
- state.confirmValues = [...shared.confirm ?? []];
1233
- state.interactive = shared.interactive ?? defaultInteractive(runtime);
1234
- state.logLevel = resolveLogLevel(shared);
1235
- state.colorEnabled = shared.color ?? (runtime.isTty.stdout && runtime.env.NO_COLOR === void 0);
1546
+ /** The recorded signals enter the engine's normal ladder: the first
1547
+ * aborts ctx.signal as if just delivered, so the handler resumes from
1548
+ * ctx.spawn already aborted. A signal past that point arms the force
1549
+ * exit, which fires once the run has settled — the turn the handler's
1550
+ * cleanup was owed, with telemetry delivered. When ctx.signal already
1551
+ * aborted BEFORE the spawn, the first recorded signal is effectively
1552
+ * the second overall and arms the force exit the same way: no path
1553
+ * force-exits from inside ctx.spawn. */
1554
+ function replayRecordedSignals(invocation, recorded) {
1555
+ if (recorded.length === 0) return;
1556
+ const state = invocation.state;
1557
+ if (invocation.signal.aborted) {
1558
+ state.pendingForceExit ??= recorded[0];
1559
+ return;
1560
+ }
1561
+ invocation.deliverSignal(recorded[0]);
1562
+ if (recorded.length > 1) state.pendingForceExit = recorded[1];
1236
1563
  }
1237
- /** Interactive iff TTY stdin outside CI; --interactive and
1238
- * --no-interactive override in either direction. Format never decides
1239
- * interactivity (operator ruling, 2026-08-09): an interactive json run
1240
- * may prompt — the prompt UI writes to stderr, so stdout stays a clean
1241
- * frame stream. */
1242
- function defaultInteractive(runtime) {
1243
- return runtime.isTty.stdin && runtime.env.CI === void 0;
1564
+ async function composeChildEnv(invocation, def, additions) {
1565
+ const env = {
1566
+ ...invocation.runtime.env,
1567
+ ...additions
1568
+ };
1569
+ if (def.needs.credentials !== "child") return env;
1570
+ const credential = invocation.state.spawnCredential;
1571
+ if (credential === void 0) throw credentialsRequiredError();
1572
+ env[SERVICE_TOKEN_ENV_VAR] = await spawnToken(invocation);
1573
+ if (credential.workspaceId !== void 0) env[WORKSPACE_ID_ENV_VAR] = credential.workspaceId;
1574
+ else delete env[WORKSPACE_ID_ENV_VAR];
1575
+ return env;
1244
1576
  }
1245
- function resolveAutoFormat(shared, runtime) {
1246
- if (shared.json === true) return "json";
1247
- return runtime.isTty.stdout ? "human" : "json";
1577
+ /**
1578
+ * The child's copy of the credential: the manager's activeAccessToken()
1579
+ * operation, read at spawn time. The refresh token is never injected:
1580
+ * the child runs on a snapshot it cannot refresh.
1581
+ */
1582
+ async function spawnToken(invocation) {
1583
+ const manager = invocation.runtime.credentialManager;
1584
+ if (manager === void 0) throw credentialsRequiredError();
1585
+ const accessToken = await manager.activeAccessToken();
1586
+ if (accessToken === null) throw credentialsRequiredError("session-ended");
1587
+ return accessToken;
1248
1588
  }
1249
- /** --quiet and --verbose are log-level shorthands; either one beats an
1250
- * explicit --log-level given alongside it. */
1251
- function resolveLogLevel(shared) {
1252
- if (shared.quiet === true) return "error";
1253
- if (shared.verbose === true) return "verbose";
1254
- return shared.logLevel ?? "info";
1589
+ function spawnFailedError(command, cause) {
1590
+ return new CliStructuredError("CLI.SPAWN_FAILED", `The program '${command}' could not be started.`, {
1591
+ why: firstLine(cause instanceof Error ? cause.message : String(cause)),
1592
+ nextActions: [{
1593
+ kind: "user-choice",
1594
+ label: `Make sure '${command}' is installed and on your PATH, then run the command again.`
1595
+ }],
1596
+ meta: { command }
1597
+ });
1598
+ }
1599
+ //#endregion
1600
+ //#region src/execution/command-context.ts
1601
+ function makeUi(colorEnabled) {
1602
+ if (!colorEnabled) return {
1603
+ emphasize: (text) => text,
1604
+ dim: (text) => text,
1605
+ code: (text) => `\`${text}\``
1606
+ };
1607
+ return {
1608
+ emphasize: (text) => `\u001b[1m${text}\u001b[22m`,
1609
+ dim: (text) => `\u001b[2m${text}\u001b[22m`,
1610
+ code: (text) => `\`${text}\``
1611
+ };
1612
+ }
1613
+ /** Materializes ONLY the active format's presentation functions, at the
1614
+ * return site: human → human + stdout + next; json → json + next. */
1615
+ function materializePresentation(state, ui, presentations) {
1616
+ if (state.format === "json") return {
1617
+ human: [],
1618
+ stdout: [],
1619
+ json: presentations.json?.(),
1620
+ next: presentations.next?.() ?? []
1621
+ };
1622
+ return {
1623
+ human: presentations.human(ui),
1624
+ stdout: presentations.stdout?.() ?? [],
1625
+ json: void 0,
1626
+ next: presentations.next?.() ?? []
1627
+ };
1628
+ }
1629
+ function makeContext(invocation, def, config, managesCredentials) {
1630
+ const state = invocation.state;
1631
+ const ui = makeUi(state.colorEnabled);
1632
+ const present = (outcome, presentations) => {
1633
+ if (state.delegatedTerminal !== void 0) throw constructionError(`command '${state.commandId}' called ctx.present while a child owned the terminal`);
1634
+ const exitCode = outcome.exitCode ?? 0;
1635
+ const diagnostics = outcome.diagnostics ?? [];
1636
+ 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");
1637
+ return Object.freeze({
1638
+ [PRESENTED]: true,
1639
+ data: outcome.data,
1640
+ exitCode,
1641
+ diagnostics,
1642
+ presentation: materializePresentation(state, ui, presentations)
1643
+ });
1644
+ };
1645
+ let api;
1646
+ const context = {
1647
+ config,
1648
+ present,
1649
+ activeCredential: () => invocation.runtime.credentialManager?.activeCredential() ?? Promise.resolve(null),
1650
+ get api() {
1651
+ api ??= invocation.hooks.managementApi?.client ?? buildManagementApiClient(invocation);
1652
+ return api;
1653
+ },
1654
+ spawn: makeSpawn(invocation, def),
1655
+ report: (event) => reportEvent(invocation, event),
1656
+ prompt: makePromptSurface(invocation),
1657
+ openUrl: (request) => announceUrl(invocation, request),
1658
+ signal: invocation.signal,
1659
+ cwd: invocation.runtime.cwd,
1660
+ env: invocation.runtime.env,
1661
+ requireDependency: async (specifier) => dependencyResolvable(specifier, invocation.runtime.cwd) ? okVoid() : notOk(missingDependencyError(specifier, invocation.runtime.packageManager))
1662
+ };
1663
+ if (managesCredentials) Object.defineProperty(context, "credentialManager", {
1664
+ enumerable: true,
1665
+ get() {
1666
+ const manager = invocation.runtime.credentialManager;
1667
+ if (manager === void 0) throw new Error("@prisma/cli-engine: the command declares managesCredentials but the Runtime supplies no credentialManager");
1668
+ return manager;
1669
+ }
1670
+ });
1671
+ return context;
1255
1672
  }
1256
1673
  //#endregion
1257
1674
  //#region src/execution/command-snapshot.ts
@@ -1332,109 +1749,6 @@ function buildCommandSnapshot(entryId, def, argv, positionalValues) {
1332
1749
  };
1333
1750
  }
1334
1751
  //#endregion
1335
- //#region src/execution/command-tree.ts
1336
- function constructionError(message) {
1337
- return /* @__PURE__ */ new Error(`@prisma/cli-engine: ${message}`);
1338
- }
1339
- const CAMEL_CASE = /^[a-z][a-zA-Z0-9]*$/;
1340
- const INTEGER_LIKE = /^\d+$/;
1341
- function validateFlags(path, def) {
1342
- const flags = def.args.flags;
1343
- const seenAliases = /* @__PURE__ */ new Set();
1344
- for (const [key, spec] of Object.entries(flags)) {
1345
- if (RESERVED_FLAG_NAMES.has(key)) throw constructionError(`command '${path}' declares reserved flag '${key}' (the shared flag family is engine-injected)`);
1346
- if (!CAMEL_CASE.test(key)) throw constructionError(`command '${path}' flag '${key}' must be camelCase (it transliterates to --kebab-case on the CLI)`);
1347
- const alias = flagRuntime(spec).alias;
1348
- if (alias === void 0) continue;
1349
- if (RESERVED_ALIASES.has(alias)) throw constructionError(`command '${path}' flag '${key}' uses reserved alias '-${alias}'`);
1350
- if (seenAliases.has(alias)) throw constructionError(`command '${path}' declares alias '-${alias}' twice`);
1351
- seenAliases.add(alias);
1352
- }
1353
- }
1354
- function validatePositionals(path, def) {
1355
- const entries = Object.entries(def.args.positionals);
1356
- let sawOptional = false;
1357
- for (const [index, [key, spec]] of entries.entries()) {
1358
- const runtime = positionalRuntime(spec);
1359
- if (INTEGER_LIKE.test(key)) throw constructionError(`command '${path}' positional key '${key}' must not be integer-like`);
1360
- if (runtime.type === "variadic" && index !== entries.length - 1) throw constructionError(`command '${path}' variadic positional '${key}' must be declared last`);
1361
- if (runtime.type === "optionalString") sawOptional = true;
1362
- if (runtime.type === "string" && sawOptional) throw constructionError(`command '${path}' required positional '${key}' may not follow an optional one`);
1363
- }
1364
- }
1365
- function validateExitCodes(path, def) {
1366
- if (def.kind !== "result-command") return;
1367
- for (const key of Object.keys(def.exitCodes)) {
1368
- const code = Number(key);
1369
- if (!Number.isInteger(code) || code < 4 || code > 99) throw constructionError(`command '${path}' documents exit code ${key}; documented codes must be integers in 4-99`);
1370
- }
1371
- }
1372
- function emptyNode() {
1373
- return {
1374
- commands: /* @__PURE__ */ new Map(),
1375
- children: /* @__PURE__ */ new Map()
1376
- };
1377
- }
1378
- function insertCommand(root, path, def, docsBaseUrl) {
1379
- const segments = path.split(" ");
1380
- if (segments.some((segment) => segment.length === 0)) throw constructionError(`invalid command path '${path}'`);
1381
- let node = root;
1382
- for (const segment of segments.slice(0, -1)) {
1383
- if (node.commands.has(segment)) throw constructionError(`command path '${path}' collides with a command mounted at a prefix of it`);
1384
- let child = node.children.get(segment);
1385
- if (child === void 0) {
1386
- child = emptyNode();
1387
- node.children.set(segment, child);
1388
- }
1389
- node = child;
1390
- }
1391
- const leaf = segments[segments.length - 1];
1392
- if (node.commands.has(leaf) || node.children.has(leaf)) throw constructionError(`command path '${path}' collides with another mounted command`);
1393
- node.commands.set(leaf, {
1394
- def,
1395
- id: segments.join("."),
1396
- docsBaseUrl
1397
- });
1398
- }
1399
- /** A command belongs to the family whose commands record contains it
1400
- * (identity). Harness-mounted commands with no family are unowned. */
1401
- function commandFamilyOf(spec, def) {
1402
- return spec.commandFamilies.find((commandFamily) => Object.values(commandFamily.commands).includes(def));
1403
- }
1404
- function validateSectionOwnership(spec, path, def) {
1405
- const section = def.needs.config;
1406
- if (section === void 0) return;
1407
- const commandFamily = commandFamilyOf(spec, def);
1408
- if (commandFamily === void 0) return;
1409
- if (commandFamily.configSection !== section) throw constructionError(`command '${path}' needs the '${section.name}' config section, which is not its command family's section`);
1410
- }
1411
- function validateDocsBaseUrls(spec) {
1412
- for (const commandFamily of spec.commandFamilies) {
1413
- const base = commandFamily.docsBaseUrl;
1414
- if (base !== void 0 && !URL.canParse(base)) throw constructionError(`command family docsBaseUrl '${base}' is not a valid URL`);
1415
- }
1416
- }
1417
- function buildCommandTree(spec) {
1418
- const paths = Object.keys(spec.commands);
1419
- if (paths.length === 0) throw constructionError("createCli requires at least one mounted command");
1420
- validateDocsBaseUrls(spec);
1421
- const root = emptyNode();
1422
- for (const path of paths) {
1423
- const def = spec.commands[path];
1424
- validateFlags(path, def);
1425
- validatePositionals(path, def);
1426
- validateExitCodes(path, def);
1427
- validateSectionOwnership(spec, path, def);
1428
- const segments = path.split(" ");
1429
- for (let depth = 1; depth < segments.length; depth += 1) {
1430
- const groupPath = segments.slice(0, depth).join(" ");
1431
- if (spec.groups[groupPath] === void 0) throw constructionError(`command path '${path}' references unknown group '${groupPath}' (declare it in createCli's groups)`);
1432
- }
1433
- insertCommand(root, path, def, commandFamilyOf(spec, def)?.docsBaseUrl);
1434
- }
1435
- return root;
1436
- }
1437
- //#endregion
1438
1752
  //#region src/execution/stricli-adapter.ts
1439
1753
  /**
1440
1754
  * The stricli boundary — fully internal: no stricli type appears in the
@@ -1546,9 +1860,13 @@ function commandParameters(def) {
1546
1860
  function resolveExample(example, cliName) {
1547
1861
  return example.includes("{bin}") ? example.replaceAll("{bin}", cliName) : `${cliName} ${example}`;
1548
1862
  }
1863
+ /** The --json refusal is stated in help, so a machine consumer learns
1864
+ * it without running the command. */
1865
+ const NO_JSON_NOTE = "This command hands the terminal to another program and does not support --json.";
1549
1866
  function commandDocs(def, cliName) {
1550
1867
  const examples = def.help.examples.map((example) => resolveExample(example, cliName));
1551
- if (examples.length === 0) return {
1868
+ const notes = def.maySpawn ? ["", NO_JSON_NOTE] : [];
1869
+ if (examples.length === 0 && notes.length === 0) return {
1552
1870
  brief: def.help.summary,
1553
1871
  fullDescription: def.help.description
1554
1872
  };
@@ -1556,9 +1874,12 @@ function commandDocs(def, cliName) {
1556
1874
  brief: def.help.summary,
1557
1875
  fullDescription: [
1558
1876
  def.help.description ?? def.help.summary,
1559
- "",
1560
- "Examples:",
1561
- ...examples.map((example) => ` ${example}`)
1877
+ ...notes,
1878
+ ...examples.length === 0 ? [] : [
1879
+ "",
1880
+ "Examples:",
1881
+ ...examples.map((example) => ` ${example}`)
1882
+ ]
1562
1883
  ].join("\n")
1563
1884
  };
1564
1885
  }
@@ -1696,6 +2017,30 @@ function settleAborted(invocation) {
1696
2017
  nextActions: []
1697
2018
  });
1698
2019
  }
2020
+ /**
2021
+ * Settle an exit code the engine did not author, verbatim, with no
2022
+ * envelope and no presentation: something other than this CLI's code
2023
+ * space produced it. The two callers are the child-status settlement
2024
+ * and the server-command handoff.
2025
+ */
2026
+ function settleVerbatimExitCode(invocation, exitCode) {
2027
+ invocation.state.settledExitCode = exitCode;
2028
+ }
2029
+ /**
2030
+ * The child owned the terminal, so its status becomes the run's
2031
+ * verbatim. This is the one path on which a session command settles
2032
+ * non-zero without erroring, and the one path on which a result
2033
+ * command settles a code it never documented: neither is the handler's
2034
+ * own conclusion, it is the child's. Only a command that hands the
2035
+ * terminal to another program may settle this way — reachable from a
2036
+ * non-declaring handler it would also end a json stream without its
2037
+ * terminal result frame.
2038
+ */
2039
+ function settleChildStatus(invocation, def, settlement) {
2040
+ if (!def.maySpawn) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without declaring maySpawn — only a command that hands the terminal to another program may settle with that program's status`);
2041
+ for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action)}\n`);
2042
+ settleVerbatimExitCode(invocation, settlement.exitCode);
2043
+ }
1699
2044
  /** A session command that returned ok — including after the signal
1700
2045
  * fired — shut down cleanly: exit 0, no presentation. In json mode the
1701
2046
  * stream still terminates with exactly one result frame. */
@@ -1854,26 +2199,39 @@ var EngineImpl = class {
1854
2199
  stricliStderr: "",
1855
2200
  stdinIterator: void 0,
1856
2201
  argv,
1857
- snapshot: void 0
2202
+ snapshot: void 0,
2203
+ delegatedTerminal: void 0,
2204
+ activePrompts: 0,
2205
+ pendingForceExit: void 0,
2206
+ spawnCredential: void 0
1858
2207
  };
1859
2208
  const startedAtMs = this.now().getTime();
1860
2209
  const controller = new AbortController();
1861
2210
  let signalDelivered = false;
1862
- const unsubscribe = runtime.onSignal((signal) => {
2211
+ /** The engine neither aborts nor exits while a child owns the
2212
+ * terminal: it records, and the affordance replays on child exit,
2213
+ * so the engine always outlives the child. */
2214
+ const deliverSignal = (signal) => {
2215
+ if (state.delegatedTerminal !== void 0) {
2216
+ recordSignalDuringSpawn(state.delegatedTerminal, signal);
2217
+ return;
2218
+ }
1863
2219
  if (signalDelivered) {
1864
2220
  runtime.exit(signal === "SIGTERM" ? 143 : 130);
1865
2221
  return;
1866
2222
  }
1867
2223
  signalDelivered = true;
1868
2224
  controller.abort(signal);
1869
- });
2225
+ };
2226
+ const unsubscribe = runtime.onSignal(deliverSignal);
1870
2227
  const invocation = {
1871
2228
  runtime,
1872
2229
  hooks: { ...hooks },
1873
2230
  now: this.now,
1874
2231
  delay: this.delay,
1875
2232
  state,
1876
- signal: controller.signal
2233
+ signal: controller.signal,
2234
+ deliverSignal
1877
2235
  };
1878
2236
  if (versionRequested(argv)) {
1879
2237
  unsubscribe();
@@ -1917,6 +2275,7 @@ var EngineImpl = class {
1917
2275
  }
1918
2276
  const exitCode = state.settledExitCode !== void 0 ? state.settledExitCode : settleUnhandled(this.spec, invocation, stricliProcess.exitCode);
1919
2277
  this.fireOnSettled(invocation, exitCode, startedAtMs);
2278
+ if (state.pendingForceExit !== void 0) runtime.exit(state.pendingForceExit === "SIGTERM" ? 143 : 130);
1920
2279
  return exitCode;
1921
2280
  }
1922
2281
  /** The onSettled delivery: once per run, after the exit code is
@@ -1945,9 +2304,20 @@ var EngineImpl = class {
1945
2304
  await this.executeServer(invocation, entry, rawFlags);
1946
2305
  return;
1947
2306
  }
2307
+ if (entry.def.maySpawn && explicitFormat(state.argv) === "json") {
2308
+ state.format = "human";
2309
+ settleErrored(invocation, jsonUnsupportedError(entry.id));
2310
+ return;
2311
+ }
2312
+ if (entry.def.maySpawn && invocation.runtime.spawn === void 0) {
2313
+ state.format = "human";
2314
+ settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
2315
+ return;
2316
+ }
1948
2317
  let needsOutcome;
1949
2318
  try {
1950
2319
  applySharedFlags(state, rawFlags, invocation.runtime);
2320
+ if (entry.def.maySpawn) state.format = "human";
1951
2321
  needsOutcome = await checkNeeds(entry.def, invocation);
1952
2322
  } catch (cause) {
1953
2323
  settleBug(invocation, cause);
@@ -1961,19 +2331,23 @@ var EngineImpl = class {
1961
2331
  settleBug(invocation, needsOutcome.cause);
1962
2332
  return;
1963
2333
  }
2334
+ state.spawnCredential = needsOutcome.spawnCredential;
1964
2335
  const handler = entry.def.handler;
1965
2336
  const args = {
1966
2337
  flags: declaredFlags(entry.def, rawFlags),
1967
2338
  positionals: distributePositionals(entry.def, values)
1968
2339
  };
1969
- const ctx = makeContext(invocation, needsOutcome.config, entry.def.kind === "result-command" && entry.def.managesCredentials);
2340
+ const ctx = makeContext(invocation, entry.def, needsOutcome.config, entry.def.kind === "result-command" && entry.def.managesCredentials);
1970
2341
  if (entry.def.kind === "session-command") {
1971
2342
  try {
1972
2343
  const result = await handler(args, ctx);
2344
+ if (await this.settleAbandonedChild(invocation, false)) return;
1973
2345
  state.resolved = true;
1974
- if (result.ok) settleSessionCompleted(invocation);
1975
- else settleErrored(invocation, result.failure);
2346
+ if (!result.ok) settleErrored(invocation, result.failure);
2347
+ else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
2348
+ else settleSessionCompleted(invocation);
1976
2349
  } catch (cause) {
2350
+ if (await this.settleAbandonedChild(invocation, true, cause)) return;
1977
2351
  state.resolved = true;
1978
2352
  settleThrown(invocation, cause);
1979
2353
  }
@@ -1981,14 +2355,31 @@ var EngineImpl = class {
1981
2355
  }
1982
2356
  try {
1983
2357
  const result = await handler(args, ctx);
2358
+ if (await this.settleAbandonedChild(invocation, false)) return;
1984
2359
  state.resolved = true;
1985
- if (result.ok) settleCompleted(invocation, entry.def, result.value);
1986
- else settleErrored(invocation, result.failure);
2360
+ if (!result.ok) settleErrored(invocation, result.failure);
2361
+ else if (isChildStatusSettlement(result.value)) settleChildStatus(invocation, entry.def, result.value);
2362
+ else settleCompleted(invocation, entry.def, result.value);
1987
2363
  } catch (cause) {
2364
+ if (await this.settleAbandonedChild(invocation, true, cause)) return;
1988
2365
  state.resolved = true;
1989
2366
  settleThrown(invocation, cause);
1990
2367
  }
1991
2368
  }
2369
+ /** The handler resolved or threw with its child still live. The
2370
+ * engine ends that child — SIGTERM, the ruled grace period, then
2371
+ * SIGKILL — and waits for it to exit before settling the run as a
2372
+ * construction error, so no run finishes under a live child. */
2373
+ async settleAbandonedChild(invocation, threw, cause) {
2374
+ const state = invocation.state;
2375
+ const terminal = state.delegatedTerminal;
2376
+ if (terminal === void 0) return false;
2377
+ await endAbandonedChild(terminal);
2378
+ state.resolved = true;
2379
+ const how = threw ? ` (the handler threw: ${String(cause instanceof Error ? cause.message : cause).split("\n")[0]})` : "";
2380
+ settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${state.commandId}' resolved while a child was still live — a handler must stay suspended on the ctx.spawn promise until the child ends${how}`));
2381
+ return true;
2382
+ }
1992
2383
  /** The stdio handoff: a foreign client owns the conversation, so the
1993
2384
  * engine hands over the streams and stays out of stdout. The handler
1994
2385
  * returns the exit code directly; there is no envelope. */
@@ -2030,12 +2421,24 @@ var EngineImpl = class {
2030
2421
  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`));
2031
2422
  return;
2032
2423
  }
2033
- state.settledExitCode = exitCode;
2424
+ settleVerbatimExitCode(invocation, exitCode);
2034
2425
  } catch (cause) {
2035
2426
  settleThrown(invocation, cause);
2036
2427
  }
2037
2428
  }
2038
2429
  };
2430
+ /** A command that may hand the terminal to a child cannot frame its
2431
+ * output, so json is refused as soon as the command is known — before
2432
+ * the needs check and before anything runs. */
2433
+ function jsonUnsupportedError(commandId) {
2434
+ return new CliStructuredError("CLI.JSON_UNSUPPORTED", `The '${commandId.replaceAll(".", " ")}' command does not support json output.`, {
2435
+ why: "It hands the terminal to another program, whose output cannot be framed as a json stream.",
2436
+ nextActions: [{
2437
+ kind: "user-choice",
2438
+ label: "Run it without --json or --format json."
2439
+ }]
2440
+ });
2441
+ }
2039
2442
  function versionRequested(argv) {
2040
2443
  for (const argument of argv) {
2041
2444
  if (argument === "--") return false;
@@ -2061,4 +2464,67 @@ function distributePositionals(def, values) {
2061
2464
  return positionals;
2062
2465
  }
2063
2466
  //#endregion
2064
- export { emptyServiceTokenError as a, PRESENTED as c, credentialsRequiredError as i, flag as l, authServiceError as n, noSessionForWorkspaceError as o, credentialRejectedError as r, serviceTokenRejectedError as s, buildEngine as t, positional as u };
2467
+ //#region src/token-claims.ts
2468
+ /**
2469
+ * Reading a credential's own claims. This lives in the engine and is
2470
+ * shared rather than reimplemented, because both credential managers
2471
+ * need it and the two copies had already drifted: one knew a service
2472
+ * token names its workspace through `sub`, the other did not, so a
2473
+ * token that worked in production could not be reproduced in a test.
2474
+ *
2475
+ * Decoding only. Nothing here verifies a signature — the claims are the
2476
+ * issuer's word, used for display and for keying, never for authorizing.
2477
+ */
2478
+ /** A service token's subject is its workspace, not a person. */
2479
+ const WORKSPACE_SUBJECT_PREFIX = "workspace:";
2480
+ function decodeTokenClaims(token) {
2481
+ const payload = token.split(".")[1];
2482
+ if (payload === void 0) return void 0;
2483
+ try {
2484
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
2485
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
2486
+ } catch {
2487
+ return;
2488
+ }
2489
+ }
2490
+ function claimedString(claims, name) {
2491
+ const value = claims?.[name];
2492
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2493
+ }
2494
+ /** The `workspace_id` claim, which is what sessions are keyed by. */
2495
+ function claimedWorkspaceId(token) {
2496
+ return claimedString(decodeTokenClaims(token), "workspace_id");
2497
+ }
2498
+ /** The workspace a credential names: its `workspace_id` claim, or the
2499
+ * workspace its subject names when it is a service token. */
2500
+ function credentialWorkspaceId(token) {
2501
+ const claims = decodeTokenClaims(token);
2502
+ const fromClaim = claimedString(claims, "workspace_id");
2503
+ if (fromClaim !== void 0) return fromClaim;
2504
+ const subject = claimedString(claims, "sub");
2505
+ if (subject === void 0 || !subject.startsWith(WORKSPACE_SUBJECT_PREFIX)) return;
2506
+ const derived = subject.slice(10).trim();
2507
+ return derived.length > 0 ? derived : void 0;
2508
+ }
2509
+ function claimedExpiresAt(token) {
2510
+ const exp = decodeTokenClaims(token)?.exp;
2511
+ return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
2512
+ }
2513
+ /**
2514
+ * Who a credential belongs to, from its own claims. A service token's
2515
+ * subject names a workspace rather than a person, so it yields no user
2516
+ * — reporting `workspace:ws_1` as a user id was a real defect.
2517
+ */
2518
+ function claimedIdentity(token) {
2519
+ const claims = decodeTokenClaims(token);
2520
+ const subject = claimedString(claims, "sub");
2521
+ const userId = subject?.startsWith(WORKSPACE_SUBJECT_PREFIX) ? void 0 : subject;
2522
+ const email = claimedString(claims, "email");
2523
+ return userId === void 0 && email === void 0 ? void 0 : {
2524
+ userId,
2525
+ email,
2526
+ name: void 0
2527
+ };
2528
+ }
2529
+ //#endregion
2530
+ export { buildEngine as a, credentialWorkspaceMismatchError as c, noSessionForWorkspaceError as d, PRESENTED as f, positional as h, credentialWorkspaceId as i, credentialsRequiredError as l, flag as m, claimedIdentity as n, authServiceError as o, exitWithChildStatus as p, claimedWorkspaceId as r, credentialRejectedError as s, claimedExpiresAt as t, emptyServiceTokenError as u };