@prisma/cli-engine 0.0.1 → 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,9 +95,626 @@ 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
144
+ //#region src/credential-errors.ts
145
+ const signInAction = {
146
+ kind: "user-choice",
147
+ label: "Sign in, then run the command again."
148
+ };
149
+ const useSessionAction = {
150
+ kind: "run-command",
151
+ label: "Make one of your workspace sessions current",
152
+ command: "prisma auth workspace use"
153
+ };
154
+ /**
155
+ * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
156
+ * identically by the needs check, ctx.activeCredential, and the
157
+ * engine's request path.
158
+ */
159
+ function credentialsRequiredError(reason = "unauthenticated") {
160
+ switch (reason) {
161
+ case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
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
+ });
167
+ case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
168
+ why: "It was ended while the command was running (for example by another prisma process).",
169
+ nextActions: [useSessionAction, signInAction]
170
+ });
171
+ case "sessions-held-none-selected": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "No workspace session is current.", {
172
+ why: "You have workspace sessions but none is current.",
173
+ nextActions: [useSessionAction, signInAction]
174
+ });
175
+ }
176
+ }
177
+ /**
178
+ * A refresh attempt failed transiently (the auth service, not the
179
+ * credentials): nothing was cleared, and signing in again is not the
180
+ * fix.
181
+ */
182
+ function authServiceError() {
183
+ return new CliStructuredError("CLI.AUTH_SERVICE_ERROR", "The authentication service could not refresh your session.", {
184
+ why: "The refresh attempt failed transiently; your stored credentials were left untouched.",
185
+ nextActions: [{
186
+ kind: "user-choice",
187
+ label: "Run the command again; sign in again only if the problem persists."
188
+ }]
189
+ });
190
+ }
191
+ /**
192
+ * The credential in force was rejected and could never be renewed — it
193
+ * carries no refresh token. The ONE place wording differs by origin;
194
+ * nothing else compares against `origin.source`.
195
+ */
196
+ function credentialRejectedError(origin, envVar) {
197
+ return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
198
+ }
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
+ /**
216
+ * The env var that supplies a session is set to a blank value. The one
217
+ * structured error for it, raised identically by activeCredential(),
218
+ * the needs check, and the engine's request path.
219
+ */
220
+ function emptyServiceTokenError(spec) {
221
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
222
+ why: `A blank token authenticates nothing, and ${spec.envVar} overrides your stored workspace sessions while it is set.`,
223
+ nextActions: [{
224
+ kind: "run-command",
225
+ label: `Unset ${spec.envVar}`,
226
+ command: `unset ${spec.envVar}`
227
+ }, {
228
+ kind: "user-choice",
229
+ label: `Or set ${spec.envVar} to a valid service token.`
230
+ }]
231
+ });
232
+ }
233
+ /**
234
+ * No session exists for the named workspace. Sessions are created by
235
+ * `prisma auth login` alone — `workspace use` selects among the ones
236
+ * you have.
237
+ */
238
+ function noSessionForWorkspaceError(workspaceRef) {
239
+ return new CliStructuredError("AUTH.NO_SESSION_FOR_WORKSPACE", `You have no session for workspace '${workspaceRef}'.`, { nextActions: [{
240
+ kind: "run-command",
241
+ label: `Sign in and pick '${workspaceRef}' in the browser`,
242
+ command: "prisma auth login"
243
+ }] });
244
+ }
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
+ *
250
+ * The management API rejected the env-supplied service token (401).
251
+ * There is no refresh for it and nothing stored is cleared.
252
+ */
253
+ function serviceTokenRejectedError(spec) {
254
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_REJECTED", `The management API rejected the service token from ${spec.envVar}.`, { nextActions: [{
255
+ kind: "user-choice",
256
+ label: `Replace ${spec.envVar} with a valid service token, or unset it to use your stored sessions.`
257
+ }] });
258
+ }
259
+ //#endregion
260
+ //#region src/execution/debug.ts
261
+ const DEBUG_ENV_VAR = "PRISMA_NEXT_DEBUG";
262
+ /**
263
+ * The engine's debug valve: silent unless PRISMA_NEXT_DEBUG=1 in the
264
+ * injected env (never process.env), writing to the injected stderr.
265
+ * Token material never reaches it.
266
+ */
267
+ function makeDebugLog(runtime) {
268
+ if (runtime.env[DEBUG_ENV_VAR] !== "1") return () => {};
269
+ return (message) => {
270
+ runtime.stderr.write(`[cli-engine] ${message}\n`);
271
+ };
272
+ }
273
+ //#endregion
274
+ //#region src/execution/api-client.ts
275
+ const SERVICE_TOKEN_ENV_VAR$1 = "PRISMA_SERVICE_TOKEN";
276
+ /**
277
+ * ctx.api: the ENGINE constructs and owns the management API client —
278
+ * ONE client for the active credential, once per run (process pinning
279
+ * makes the memoization correct). Nothing resolves until the first
280
+ * method CALL, so a run that never issues a request never pays for —
281
+ * or depends on — the SDK module load. The client is always the SDK's
282
+ * refreshing one over the storage the manager hands out, whatever the
283
+ * credential's origin: a credential refreshes if it has a refresh
284
+ * token. Every request failure passes through the engine-side mapping
285
+ * below. The returned client is a Proxy whose method wrappers await
286
+ * the lazy construction before applying the call — every client method
287
+ * is async, so the deferral is invisible to callers.
288
+ */
289
+ function buildManagementApiClient(invocation) {
290
+ const debug = makeDebugLog(invocation.runtime);
291
+ const probe = { failure: void 0 };
292
+ let pinned;
293
+ let clientPromise;
294
+ const resolveClient = () => {
295
+ clientPromise ??= constructClient(invocation, debug, probe).then((constructed) => {
296
+ pinned = constructed.pinned;
297
+ return constructed.client;
298
+ });
299
+ return clientPromise;
300
+ };
301
+ return new Proxy({}, { get(_target, property) {
302
+ if (typeof property === "symbol" || property === "then") return;
303
+ return async (...args) => {
304
+ try {
305
+ const client = await resolveClient();
306
+ const value = Reflect.get(client, property);
307
+ if (typeof value !== "function") throw new TypeError(`@prisma/cli-engine: ctx.api.${property} is not a function`);
308
+ return await Reflect.apply(value, client, args);
309
+ } catch (cause) {
310
+ throw await mapRequestFailure(invocation, debug, probe, pinned, cause);
311
+ }
312
+ };
313
+ } });
314
+ }
315
+ async function constructClient(invocation, debug, probe) {
316
+ const manager = invocation.runtime.credentialManager;
317
+ if (manager === void 0) throw credentialsRequiredError();
318
+ const active = await manager.activeCredential();
319
+ if (active === null) throw credentialsRequiredError();
320
+ const config = invocation.runtime.managementApiClientConfig;
321
+ if (config === void 0) throw new Error("@prisma/cli-engine: ctx.api requires Runtime.managementApiClientConfig when a credentialManager is wired");
322
+ const storage = observedTokenStorage(await manager.activeCredentialStorage(), active, debug, probe);
323
+ const { createManagementApiSdk } = await import("@prisma/management-api-sdk");
324
+ return {
325
+ client: createManagementApiSdk({
326
+ clientId: config.clientId,
327
+ redirectUri: config.redirectUri,
328
+ apiBaseUrl: config.apiBaseUrl,
329
+ authBaseUrl: config.authBaseUrl,
330
+ tokenStorage: storage
331
+ }).client,
332
+ pinned: {
333
+ active,
334
+ storage
335
+ }
336
+ };
337
+ }
338
+ /**
339
+ * The manager's storage, with the refresh path observed. The SDK enters
340
+ * withRefreshLock only from its refresh routine, so it marks both the
341
+ * debug valve's "refresh attempted" line and the boundary whose throws
342
+ * count as refresh-path failures.
343
+ */
344
+ function observedTokenStorage(storage, active, debug, probe) {
345
+ const label = active.workspaceId ?? "(no workspace)";
346
+ const observedRefresh = async (fn) => {
347
+ debug(`refresh attempted for session ${label}`);
348
+ try {
349
+ return await fn();
350
+ } catch (failure) {
351
+ probe.failure = failure;
352
+ throw failure;
353
+ }
354
+ };
355
+ return {
356
+ getTokens: () => storage.getTokens(),
357
+ setTokens: (tokens) => storage.setTokens(tokens),
358
+ clearTokens: () => storage.clearTokens(),
359
+ ...storage.clearTokensIfCurrent === void 0 ? {} : { clearTokensIfCurrent: (tokens) => storage.clearTokensIfCurrent(tokens) },
360
+ withRefreshLock: (fn) => storage.withRefreshLock === void 0 ? observedRefresh(fn) : storage.withRefreshLock(() => observedRefresh(fn))
361
+ };
362
+ }
363
+ /**
364
+ * The engine-side request-failure mapping. A structured error raised
365
+ * inside the pipeline (the SDK wraps non-SDK errors into
366
+ * FetchError(cause), so the cause chain is walked for BOTH AuthError
367
+ * and CLI structured errors) is rethrown unwrapped so it settles as
368
+ * itself. An SDK AuthError is discriminated by STATE, never by message
369
+ * parsing: refreshTokenInvalid === true (the SDK's definitive
370
+ * invalid_grant signal, already cleared by compare-and-clear) maps to
371
+ * the expired CLI.CREDENTIALS_REQUIRED; a refresh the SDK refused
372
+ * because the token set carries no refresh token maps to the
373
+ * credential-rejected error, since that credential could never have
374
+ * been renewed; any other AuthError triggers a re-read of the stored
375
+ * state for the credential's own workspace — that session gone means
376
+ * the session-ended CLI.CREDENTIALS_REQUIRED, otherwise the failure was
377
+ * the auth service's and nothing was cleared. A failure that came out
378
+ * of the refresh path without being an AuthError (the SDK throws a
379
+ * plain Error when a rotated token will not decode) is transient too:
380
+ * nothing was cleared, and signing in again is not the fix.
381
+ */
382
+ async function mapRequestFailure(invocation, debug, probe, pinned, cause) {
383
+ const structured = structuredCause(cause);
384
+ if (structured !== void 0) return structured;
385
+ const cameFromRefresh = refreshPathFailed(probe, cause);
386
+ const authError = sdkAuthErrorInCauseChain(cause);
387
+ if (authError === void 0) {
388
+ if (!cameFromRefresh) return cause;
389
+ debug(`refresh failed without an AuthError (${errorTypeOf(probe.failure)})`);
390
+ return authServiceError();
391
+ }
392
+ if (cameFromRefresh) debug(`refresh failed: refreshTokenInvalid=${String(authError.refreshTokenInvalid === true)} error=${endpointVerdict(authError.message)}`);
393
+ const manager = invocation.runtime.credentialManager;
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";
405
+ }
406
+ /**
407
+ * A 401 that could never have been renewed: the SDK refused to reach
408
+ * the token endpoint at all because the token set carries no refresh
409
+ * token. Read from the storage's own state — never from the SDK's
410
+ * message.
411
+ */
412
+ async function couldNeverHaveBeenRenewed(storage) {
413
+ try {
414
+ const tokens = await storage.getTokens();
415
+ return tokens !== null && !tokens.refreshToken;
416
+ } catch {
417
+ return false;
418
+ }
419
+ }
420
+ async function mapAgainstStoredState(manager, active, cause) {
421
+ const workspaceId = active.workspaceId;
422
+ if (workspaceId === void 0) return authServiceError();
423
+ let stored;
424
+ try {
425
+ stored = await manager.sessions();
426
+ } catch (stateCause) {
427
+ return CliStructuredError.is(stateCause) ? stateCause : cause;
428
+ }
429
+ if (!stored.sessions.some((session) => session.workspaceId === workspaceId)) return credentialsRequiredError("session-ended");
430
+ return authServiceError();
431
+ }
432
+ /** Cause chains can be cyclic (an Error whose `cause` eventually points
433
+ * back at itself); track visited nodes with a depth cap as a backstop
434
+ * so the walk always terminates. */
435
+ const CAUSE_CHAIN_DEPTH_CAP = 32;
436
+ function* causeChain(error) {
437
+ const visited = /* @__PURE__ */ new Set();
438
+ for (let current = error; current instanceof Error && !visited.has(current) && visited.size < CAUSE_CHAIN_DEPTH_CAP; current = current.cause) {
439
+ visited.add(current);
440
+ yield current;
441
+ }
442
+ }
443
+ function structuredCause(error) {
444
+ for (const current of causeChain(error)) if (CliStructuredError.is(current)) return current;
445
+ }
446
+ /** Structural match (name discriminator plus the refreshTokenInvalid
447
+ * field) rather than instanceof, so a duplicate SDK module instance
448
+ * cannot defeat the mapping — and so this check never forces the SDK
449
+ * module to load. */
450
+ function sdkAuthErrorInCauseChain(error) {
451
+ for (const current of causeChain(error)) if (current.name === "AuthError") return current;
452
+ }
453
+ /** The request failure carries the refresh attempt's own throw, so the
454
+ * failure arose in the refresh path rather than in the request. */
455
+ function refreshPathFailed(probe, cause) {
456
+ if (probe.failure === void 0) return false;
457
+ if (cause === probe.failure) return true;
458
+ for (const current of causeChain(cause)) if (current === probe.failure) return true;
459
+ return false;
460
+ }
461
+ function errorTypeOf(error) {
462
+ return error instanceof Error ? error.name : typeof error;
463
+ }
464
+ /**
465
+ * The endpoint's verdict, without its free text. The SDK builds a
466
+ * refresh AuthError's message either as `<error>: <error_description>`
467
+ * from the token endpoint's body or as one of its own fixed strings
468
+ * (which carry the HTTP status). Only the part before the description
469
+ * is logged: the description is text the auth service chose, and the
470
+ * debug valve must never become a way for it to reach a log.
471
+ */
472
+ function endpointVerdict(message) {
473
+ const description = message.indexOf(": ");
474
+ return description === -1 ? message : message.slice(0, description);
475
+ }
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
100
718
  //#region src/execution/rendering.ts
101
719
  function firstLine(text) {
102
720
  const newline = text.indexOf("\n");
@@ -185,8 +803,15 @@ function writeDiagnostic(stream, diagnostic) {
185
803
  for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action)}\n`);
186
804
  if (diagnostic.docsUrl !== void 0) stream.write(` docs: ${diagnostic.docsUrl}\n`);
187
805
  }
806
+ /** `label` is required, so a mapper building an action out of a bare
807
+ * command string — a legacy error's follow-up step, with no prose
808
+ * beside it — has nothing to put in the label but the command itself.
809
+ * Only the renderer sees both fields, so only it can tell they are the
810
+ * same string and print it once. */
188
811
  function renderNextAction(action) {
189
- return `→ ${action.label}${action.command === void 0 ? "" : `: ${action.command}`}`;
812
+ const target = action.command ?? action.url;
813
+ const repeatsTheLabel = target === void 0 || target === action.label;
814
+ return `→ ${action.label}${repeatsTheLabel ? "" : `: ${target}`}`;
190
815
  }
191
816
  /** Populates docsUrl from the owning family's docsBaseUrl (base + code)
192
817
  * when the diagnostic does not carry its own — a per-raise docsUrl wins. */
@@ -209,8 +834,6 @@ function renderCompletedHuman(invocation, presented) {
209
834
  for (const diagnostic of presented.diagnostics) writeDiagnostic(runtime.stderr, withDocsUrl(state, diagnostic));
210
835
  for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
211
836
  }
212
- //#endregion
213
- //#region src/execution/reporting.ts
214
837
  const SEVERITY_RANK = {
215
838
  error: 0,
216
839
  warn: 1,
@@ -237,6 +860,15 @@ function reportEvent(invocation, event) {
237
860
  reportAfterResolution(invocation);
238
861
  return;
239
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
+ }
240
872
  invocation.hooks.onEvent?.(event);
241
873
  const severity = eventDisplaySeverity(event);
242
874
  if (severity !== void 0 && SEVERITY_RANK[severity] > SEVERITY_RANK[state.logLevel]) return;
@@ -250,12 +882,18 @@ function reportEvent(invocation, event) {
250
882
  }
251
883
  renderEventHuman(invocation, event);
252
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
+ }
253
893
  function emitFrame(invocation, frame) {
254
894
  invocation.runtime.stdout.write(`${JSON.stringify(frame)}\n`);
255
895
  invocation.hooks.onStreamEvent?.(frame);
256
896
  }
257
- //#endregion
258
- //#region src/execution/needs.ts
259
897
  function needsErrored(error, diagnostics = []) {
260
898
  return {
261
899
  kind: "errored",
@@ -280,12 +918,21 @@ function structuredErrorFromDiagnostic(diagnostic) {
280
918
  * success it carries the validated section value for ctx.config. */
281
919
  async function checkNeeds(def, invocation) {
282
920
  const needs = def.needs;
283
- const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation) ?? await checkCredentials(needs, invocation);
921
+ const failure = checkInteraction(needs, invocation) ?? checkDependencies(needs, invocation);
284
922
  if (failure !== void 0) return failure;
285
- 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
+ }
286
932
  return {
287
933
  kind: "ok",
288
- config: void 0
934
+ config: void 0,
935
+ spawnCredential: credentials.spawnCredential
289
936
  };
290
937
  }
291
938
  function checkInteraction(needs, invocation) {
@@ -301,29 +948,40 @@ function checkInteraction(needs, invocation) {
301
948
  function checkDependencies(needs, invocation) {
302
949
  for (const specifier of needs.dependencies) if (!dependencyResolvable(specifier, invocation.runtime.cwd)) return needsErrored(missingDependencyError(specifier, invocation.runtime.packageManager));
303
950
  }
951
+ /**
952
+ * The credentials need, single-sourced from the credential manager:
953
+ * activeCredential() is the local-only truth (the process pin), and
954
+ * its structured errors (sessions held none selected, blank env token)
955
+ * pass through verbatim so the needs check, ctx.activeCredential, and
956
+ * ctx.api raise identically. A host with no manager wired has no
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.
964
+ */
304
965
  async function checkCredentials(needs, invocation) {
305
- if (!needs.credentials) return;
306
- let credentials;
966
+ if (needs.credentials === false) return {};
967
+ const manager = invocation.runtime.credentialManager;
968
+ if (manager === void 0) return { failure: needsErrored(credentialsRequiredError()) };
969
+ let credential;
307
970
  try {
308
- credentials = await invocation.runtime.getCredentials();
971
+ credential = await manager.activeCredential();
309
972
  } 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
- }));
973
+ if (CliStructuredError.is(cause)) return { failure: needsErrored(cause) };
974
+ throw cause;
317
975
  }
318
- if (credentials === void 0) return needsErrored(credentialsRequiredError());
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 };
319
980
  }
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
- }] });
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"));
327
985
  }
328
986
  function checkConfiguration(section, invocation) {
329
987
  const fileLevel = invocation.runtime.config.diagnostics.filter((entry) => entry.section === null);
@@ -351,7 +1009,8 @@ function validateConfigSection(section, invocation) {
351
1009
  writeSectionWarnings(invocation, validation.diagnostics);
352
1010
  return {
353
1011
  kind: "ok",
354
- config: validation.value
1012
+ config: validation.value,
1013
+ spawnCredential: void 0
355
1014
  };
356
1015
  }
357
1016
  /** Diagnostics on an OK validation are warnings: written to stderr as
@@ -401,90 +1060,22 @@ function missingDependencyError(specifier, packageManager) {
401
1060
  });
402
1061
  }
403
1062
  //#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;
1063
+ //#region src/execution/open-url.ts
1064
+ async function announceUrl(invocation, request) {
1065
+ reportEvent(invocation, {
1066
+ kind: "endpoint",
1067
+ name: request.message,
1068
+ url: request.url
1069
+ });
1070
+ const open = invocation.runtime.openUrl;
1071
+ if (!invocation.state.interactive || open === void 0) return { opened: false };
1072
+ try {
1073
+ await open(request.url);
1074
+ return { opened: true };
1075
+ } catch {
1076
+ return { opened: false };
476
1077
  }
477
1078
  }
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
1079
  //#endregion
489
1080
  //#region src/execution/clack-renderer.ts
490
1081
  /**
@@ -538,6 +1129,13 @@ async function makeClackRenderer(stdin, stderr) {
538
1129
  message: question,
539
1130
  initialValue: false
540
1131
  }),
1132
+ confirmToken: (question, token) => clack.text({
1133
+ input,
1134
+ output,
1135
+ message: `${question} Type ${token} to confirm.`,
1136
+ placeholder: token,
1137
+ validate: (value) => value === token ? void 0 : `Type ${token} exactly, or press Ctrl-C.`
1138
+ }),
541
1139
  select: (question, options, initial) => clack.select({
542
1140
  input,
543
1141
  output,
@@ -560,6 +1158,16 @@ async function makeClackRenderer(stdin, stderr) {
560
1158
  }
561
1159
  //#endregion
562
1160
  //#region src/execution/prompts.ts
1161
+ /** How often browserWait asks whether the user has finished. */
1162
+ const BROWSER_WAIT_POLL_INTERVAL_MS = 1e3;
1163
+ /** A `--confirm` value grants at most one consent: the matched value is
1164
+ * removed, so two consents on the same token need two --confirms. */
1165
+ function consumeConfirmValue(state, token) {
1166
+ const index = state.confirmValues.indexOf(token);
1167
+ if (index === -1) return false;
1168
+ state.confirmValues.splice(index, 1);
1169
+ return true;
1170
+ }
563
1171
  function makeLineReader(stdin, invocation) {
564
1172
  const iterator = stdin[Symbol.asyncIterator]();
565
1173
  invocation.state.stdinIterator = iterator;
@@ -600,15 +1208,53 @@ function promptUnanswerable(question, state) {
600
1208
  label: "Run the command from an interactive terminal, or pass a flag that answers the prompt."
601
1209
  }] });
602
1210
  }
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: [{
1211
+ function consentUnavailable(question, state, token) {
1212
+ const situation = state.yes ? `"${question}" requires explicit consent, which --yes cannot grant.` : `"${question}" requires explicit consent, and the session is not interactive.`;
1213
+ if (token === void 0) return new CliStructuredError("CLI.CONSENT_REQUIRED", situation, { nextActions: [{
605
1214
  kind: "user-choice",
606
- label: "Run the command interactively, or pass the command's explicit consent flag if it documents one."
1215
+ label: "Run the command interactively. Consent can only be granted outside an interactive terminal when the command declares a consent token."
607
1216
  }] });
1217
+ return new CliStructuredError("CLI.CONSENT_REQUIRED", `${situation} Grant it by passing --confirm ${token}.`, {
1218
+ nextActions: [{
1219
+ kind: "user-choice",
1220
+ label: `Run the command interactively and type ${token}, or pass --confirm ${token}.`
1221
+ }],
1222
+ meta: { consentToken: token }
1223
+ });
608
1224
  }
609
1225
  function promptInvalid(question, raw) {
610
1226
  return new CliStructuredError("CLI.PROMPT_INVALID", `"${raw}" is not a valid answer to "${question}".`);
611
1227
  }
1228
+ /** A consent whose token was typed wrong where re-prompting is not
1229
+ * possible (scripted answers, piped stdin). */
1230
+ function consentTokenMismatch(question, token, raw) {
1231
+ return new CliStructuredError("CLI.PROMPT_INVALID", `"${raw}" does not confirm "${question}": the answer must be exactly ${token}.`, { meta: { consentToken: token } });
1232
+ }
1233
+ /** browserWait outside an interactive terminal: nothing is opened and
1234
+ * nothing is polled, so the URL travels in the error instead. */
1235
+ function browserWaitUnavailable(message, url) {
1236
+ return new CliStructuredError("CLI.INTERACTION_REQUIRED", `${message} requires an interactive terminal: it waits for you to finish at ${url}.`, {
1237
+ why: "The session is not interactive (no TTY stdin, CI, or --no-interactive), so the browser cannot be opened and the wait would never end.",
1238
+ nextActions: [{
1239
+ kind: "user-choice",
1240
+ label: `Open ${url} and finish there, then run the command again from an interactive terminal (or pass --interactive).`
1241
+ }],
1242
+ meta: { url }
1243
+ });
1244
+ }
1245
+ function browserWaitTimedOut(message, url, timeout) {
1246
+ return new CliStructuredError("CLI.BROWSER_WAIT_TIMEOUT", `${message} was not finished within ${Math.round(timeout / 1e3)}s.`, {
1247
+ why: `The command waited for ${url} and stopped waiting before it completed.`,
1248
+ nextActions: [{
1249
+ kind: "user-choice",
1250
+ label: "Run the command again and finish in the browser."
1251
+ }],
1252
+ meta: {
1253
+ url,
1254
+ timeoutMs: timeout
1255
+ }
1256
+ });
1257
+ }
612
1258
  function isExplicitYes(raw) {
613
1259
  if (typeof raw === "boolean") return raw;
614
1260
  return [
@@ -667,7 +1313,25 @@ function makePromptSurface(invocation) {
667
1313
  if (line === void 0) throw promptCancelled(question);
668
1314
  return line;
669
1315
  };
670
- return {
1316
+ /** The interactive rendering of a consent that declares a token: the
1317
+ * user types the token itself. Clack lets them try again; the line
1318
+ * renderer cannot, so a wrong answer there is structural. */
1319
+ const confirmByTyping = async (question, token) => {
1320
+ if (useClack()) {
1321
+ await renderWithClack(question, (r) => r.confirmToken(question, token));
1322
+ return true;
1323
+ }
1324
+ const typed = await ask(question, `? ${question} (type ${token} to confirm) `);
1325
+ if (typeof typed !== "string" || typed.trim() !== token) throw consentTokenMismatch(question, token, String(typed));
1326
+ return true;
1327
+ };
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 = {
671
1335
  confirm: async (question, opts) => {
672
1336
  const fallback = opts?.default;
673
1337
  if (state.yes || !state.interactive) {
@@ -680,8 +1344,13 @@ function makePromptSurface(invocation) {
680
1344
  else if (fallback === false) hint = "(y/N)";
681
1345
  return parseBooleanAnswer(await ask(question, `? ${question} ${hint} `), fallback, question);
682
1346
  },
683
- consent: async (question) => {
684
- if (state.yes || !state.interactive) throw consentUnavailable(question, state);
1347
+ consent: async (question, opts) => {
1348
+ const token = opts?.token;
1349
+ if (state.yes || !state.interactive) {
1350
+ if (token !== void 0 && consumeConfirmValue(state, token)) return true;
1351
+ throw consentUnavailable(question, state, token);
1352
+ }
1353
+ if (token !== void 0) return confirmByTyping(question, token);
685
1354
  if (useClack()) return renderWithClack(question, (r) => r.consent(question));
686
1355
  return isExplicitYes(await ask(question, `? ${question} (y/n) `));
687
1356
  },
@@ -721,194 +1390,285 @@ function makePromptSurface(invocation) {
721
1390
  if (typeof raw !== "string") throw promptInvalid(question, String(raw));
722
1391
  if (raw === "") return fallback ?? "";
723
1392
  return raw;
1393
+ },
1394
+ browserWait: async ({ url, message, poll, timeout, interval }) => {
1395
+ if (!state.interactive) throw browserWaitUnavailable(message, url);
1396
+ await announceUrl(invocation, {
1397
+ url,
1398
+ message
1399
+ });
1400
+ const deadline = invocation.now().getTime() + timeout;
1401
+ for (;;) {
1402
+ if (invocation.signal.aborted) throw promptCancelled(message);
1403
+ if (await poll(invocation.signal)) return;
1404
+ if (invocation.now().getTime() >= deadline) throw browserWaitTimedOut(message, url, timeout);
1405
+ await invocation.delay(interval ?? BROWSER_WAIT_POLL_INTERVAL_MS, invocation.signal);
1406
+ }
724
1407
  }
725
1408
  };
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}\``
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
+ }
734
1421
  };
735
1422
  return {
736
- emphasize: (text) => `\u001b[1m${text}\u001b[22m`,
737
- dim: (text) => `\u001b[2m${text}\u001b[22m`,
738
- 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))
739
1428
  };
740
1429
  }
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?.() ?? []
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;
755
1471
  };
756
1472
  }
757
- function makeContext(invocation, config) {
1473
+ async function runDelegated(invocation, def, terminal, spawnChild, options) {
758
1474
  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");
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);
1492
+ }
1493
+ }
873
1494
  }
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;
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");
884
1534
  }
1535
+ };
1536
+ const trigger = AbortSignal.any([invocation.signal, terminal.termination.signal]);
1537
+ if (trigger.aborted) {
1538
+ terminate();
1539
+ return;
885
1540
  }
1541
+ trigger.addEventListener("abort", () => void terminate(), {
1542
+ once: true,
1543
+ signal: ended
1544
+ });
886
1545
  }
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);
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];
893
1563
  }
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;
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;
901
1576
  }
902
- function resolveAutoFormat(shared, runtime) {
903
- if (shared.json === true) return "json";
904
- 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;
1588
+ }
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
+ });
905
1598
  }
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";
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;
912
1672
  }
913
1673
  //#endregion
914
1674
  //#region src/execution/command-snapshot.ts
@@ -989,109 +1749,6 @@ function buildCommandSnapshot(entryId, def, argv, positionalValues) {
989
1749
  };
990
1750
  }
991
1751
  //#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
1752
  //#region src/execution/stricli-adapter.ts
1096
1753
  /**
1097
1754
  * The stricli boundary — fully internal: no stricli type appears in the
@@ -1203,9 +1860,13 @@ function commandParameters(def) {
1203
1860
  function resolveExample(example, cliName) {
1204
1861
  return example.includes("{bin}") ? example.replaceAll("{bin}", cliName) : `${cliName} ${example}`;
1205
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.";
1206
1866
  function commandDocs(def, cliName) {
1207
1867
  const examples = def.help.examples.map((example) => resolveExample(example, cliName));
1208
- if (examples.length === 0) return {
1868
+ const notes = def.maySpawn ? ["", NO_JSON_NOTE] : [];
1869
+ if (examples.length === 0 && notes.length === 0) return {
1209
1870
  brief: def.help.summary,
1210
1871
  fullDescription: def.help.description
1211
1872
  };
@@ -1213,9 +1874,12 @@ function commandDocs(def, cliName) {
1213
1874
  brief: def.help.summary,
1214
1875
  fullDescription: [
1215
1876
  def.help.description ?? def.help.summary,
1216
- "",
1217
- "Examples:",
1218
- ...examples.map((example) => ` ${example}`)
1877
+ ...notes,
1878
+ ...examples.length === 0 ? [] : [
1879
+ "",
1880
+ "Examples:",
1881
+ ...examples.map((example) => ` ${example}`)
1882
+ ]
1219
1883
  ].join("\n")
1220
1884
  };
1221
1885
  }
@@ -1353,6 +2017,30 @@ function settleAborted(invocation) {
1353
2017
  nextActions: []
1354
2018
  });
1355
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
+ }
1356
2044
  /** A session command that returned ok — including after the signal
1357
2045
  * fired — shut down cleanly: exit 0, no presentation. In json mode the
1358
2046
  * stream still terminates with exactly one result frame. */
@@ -1466,15 +2154,31 @@ function settleUnhandled(spec, invocation, stricliExitCode) {
1466
2154
  //#endregion
1467
2155
  //#region src/execution/engine.ts
1468
2156
  function buildEngine(spec, options) {
1469
- return new EngineImpl(spec, options?.now);
2157
+ return new EngineImpl(spec, options?.now, options?.delay);
2158
+ }
2159
+ /** Resolves on the timer OR on the signal, whichever comes first — the
2160
+ * caller decides what an abort means, and no timer outlives the run. */
2161
+ function waitFor(ms, signal) {
2162
+ if (signal.aborted) return Promise.resolve();
2163
+ return new Promise((resolve) => {
2164
+ const finish = () => {
2165
+ clearTimeout(timer);
2166
+ signal.removeEventListener("abort", finish);
2167
+ resolve();
2168
+ };
2169
+ const timer = setTimeout(finish, ms);
2170
+ signal.addEventListener("abort", finish, { once: true });
2171
+ });
1470
2172
  }
1471
2173
  var EngineImpl = class {
1472
2174
  spec;
1473
2175
  root;
1474
2176
  now;
1475
- constructor(spec, now = () => /* @__PURE__ */ new Date()) {
2177
+ delay;
2178
+ constructor(spec, now = () => /* @__PURE__ */ new Date(), delay = waitFor) {
1476
2179
  this.spec = spec;
1477
2180
  this.now = now;
2181
+ this.delay = delay;
1478
2182
  this.root = buildRoutes(spec, buildCommandTree(spec), "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
1479
2183
  }
1480
2184
  async execute(argv, runtime, hooks) {
@@ -1485,6 +2189,7 @@ var EngineImpl = class {
1485
2189
  format: sniffFormat(argv, runtime),
1486
2190
  logLevel: "info",
1487
2191
  yes: false,
2192
+ confirmValues: [],
1488
2193
  interactive: defaultInteractive(runtime),
1489
2194
  colorEnabled: false,
1490
2195
  resolved: false,
@@ -1494,25 +2199,39 @@ var EngineImpl = class {
1494
2199
  stricliStderr: "",
1495
2200
  stdinIterator: void 0,
1496
2201
  argv,
1497
- snapshot: void 0
2202
+ snapshot: void 0,
2203
+ delegatedTerminal: void 0,
2204
+ activePrompts: 0,
2205
+ pendingForceExit: void 0,
2206
+ spawnCredential: void 0
1498
2207
  };
1499
2208
  const startedAtMs = this.now().getTime();
1500
2209
  const controller = new AbortController();
1501
2210
  let signalDelivered = false;
1502
- 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
+ }
1503
2219
  if (signalDelivered) {
1504
2220
  runtime.exit(signal === "SIGTERM" ? 143 : 130);
1505
2221
  return;
1506
2222
  }
1507
2223
  signalDelivered = true;
1508
2224
  controller.abort(signal);
1509
- });
2225
+ };
2226
+ const unsubscribe = runtime.onSignal(deliverSignal);
1510
2227
  const invocation = {
1511
2228
  runtime,
1512
2229
  hooks: { ...hooks },
1513
2230
  now: this.now,
2231
+ delay: this.delay,
1514
2232
  state,
1515
- signal: controller.signal
2233
+ signal: controller.signal,
2234
+ deliverSignal
1516
2235
  };
1517
2236
  if (versionRequested(argv)) {
1518
2237
  unsubscribe();
@@ -1556,6 +2275,7 @@ var EngineImpl = class {
1556
2275
  }
1557
2276
  const exitCode = state.settledExitCode !== void 0 ? state.settledExitCode : settleUnhandled(this.spec, invocation, stricliProcess.exitCode);
1558
2277
  this.fireOnSettled(invocation, exitCode, startedAtMs);
2278
+ if (state.pendingForceExit !== void 0) runtime.exit(state.pendingForceExit === "SIGTERM" ? 143 : 130);
1559
2279
  return exitCode;
1560
2280
  }
1561
2281
  /** The onSettled delivery: once per run, after the exit code is
@@ -1584,9 +2304,20 @@ var EngineImpl = class {
1584
2304
  await this.executeServer(invocation, entry, rawFlags);
1585
2305
  return;
1586
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
+ }
1587
2317
  let needsOutcome;
1588
2318
  try {
1589
2319
  applySharedFlags(state, rawFlags, invocation.runtime);
2320
+ if (entry.def.maySpawn) state.format = "human";
1590
2321
  needsOutcome = await checkNeeds(entry.def, invocation);
1591
2322
  } catch (cause) {
1592
2323
  settleBug(invocation, cause);
@@ -1600,19 +2331,23 @@ var EngineImpl = class {
1600
2331
  settleBug(invocation, needsOutcome.cause);
1601
2332
  return;
1602
2333
  }
2334
+ state.spawnCredential = needsOutcome.spawnCredential;
1603
2335
  const handler = entry.def.handler;
1604
2336
  const args = {
1605
2337
  flags: declaredFlags(entry.def, rawFlags),
1606
2338
  positionals: distributePositionals(entry.def, values)
1607
2339
  };
1608
- const ctx = makeContext(invocation, needsOutcome.config);
2340
+ const ctx = makeContext(invocation, entry.def, needsOutcome.config, entry.def.kind === "result-command" && entry.def.managesCredentials);
1609
2341
  if (entry.def.kind === "session-command") {
1610
2342
  try {
1611
2343
  const result = await handler(args, ctx);
2344
+ if (await this.settleAbandonedChild(invocation, false)) return;
1612
2345
  state.resolved = true;
1613
- if (result.ok) settleSessionCompleted(invocation);
1614
- 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);
1615
2349
  } catch (cause) {
2350
+ if (await this.settleAbandonedChild(invocation, true, cause)) return;
1616
2351
  state.resolved = true;
1617
2352
  settleThrown(invocation, cause);
1618
2353
  }
@@ -1620,14 +2355,31 @@ var EngineImpl = class {
1620
2355
  }
1621
2356
  try {
1622
2357
  const result = await handler(args, ctx);
2358
+ if (await this.settleAbandonedChild(invocation, false)) return;
1623
2359
  state.resolved = true;
1624
- if (result.ok) settleCompleted(invocation, entry.def, result.value);
1625
- 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);
1626
2363
  } catch (cause) {
2364
+ if (await this.settleAbandonedChild(invocation, true, cause)) return;
1627
2365
  state.resolved = true;
1628
2366
  settleThrown(invocation, cause);
1629
2367
  }
1630
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
+ }
1631
2383
  /** The stdio handoff: a foreign client owns the conversation, so the
1632
2384
  * engine hands over the streams and stays out of stdout. The handler
1633
2385
  * returns the exit code directly; there is no envelope. */
@@ -1669,12 +2421,24 @@ var EngineImpl = class {
1669
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`));
1670
2422
  return;
1671
2423
  }
1672
- state.settledExitCode = exitCode;
2424
+ settleVerbatimExitCode(invocation, exitCode);
1673
2425
  } catch (cause) {
1674
2426
  settleThrown(invocation, cause);
1675
2427
  }
1676
2428
  }
1677
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
+ }
1678
2442
  function versionRequested(argv) {
1679
2443
  for (const argument of argv) {
1680
2444
  if (argument === "--") return false;
@@ -1700,4 +2464,67 @@ function distributePositionals(def, values) {
1700
2464
  return positionals;
1701
2465
  }
1702
2466
  //#endregion
1703
- export { positional as i, PRESENTED as n, flag as r, buildEngine as t };
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 };