@prisma/cli-engine 0.0.1 → 0.0.2

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.
@@ -97,6 +97,308 @@ const positional = {
97
97
  //#region src/presentation.ts
98
98
  const PRESENTED = Symbol.for("prisma.cli-engine.presented");
99
99
  //#endregion
100
+ //#region src/credential-errors.ts
101
+ const signInAction = {
102
+ kind: "user-choice",
103
+ label: "Sign in, then run the command again."
104
+ };
105
+ const useSessionAction = {
106
+ kind: "run-command",
107
+ label: "Make one of your workspace sessions current",
108
+ command: "prisma auth workspace use"
109
+ };
110
+ /**
111
+ * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
112
+ * identically by the needs check, ctx.session, and the engine's
113
+ * request path.
114
+ */
115
+ function credentialsRequiredError(reason = "unauthenticated") {
116
+ switch (reason) {
117
+ case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
118
+ case "expired": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session has expired — sign in again.", { nextActions: [signInAction] });
119
+ case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
120
+ why: "It was ended while the command was running (for example by another prisma process).",
121
+ nextActions: [useSessionAction, signInAction]
122
+ });
123
+ case "sessions-held-none-selected": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "No workspace session is current.", {
124
+ why: "You have workspace sessions but none is current.",
125
+ nextActions: [useSessionAction, signInAction]
126
+ });
127
+ }
128
+ }
129
+ /**
130
+ * A refresh attempt failed transiently (the auth service, not the
131
+ * credentials): nothing was cleared, and signing in again is not the
132
+ * fix.
133
+ */
134
+ function authServiceError() {
135
+ return new CliStructuredError("CLI.AUTH_SERVICE_ERROR", "The authentication service could not refresh your session.", {
136
+ why: "The refresh attempt failed transiently; your stored credentials were left untouched.",
137
+ nextActions: [{
138
+ kind: "user-choice",
139
+ label: "Run the command again; sign in again only if the problem persists."
140
+ }]
141
+ });
142
+ }
143
+ /**
144
+ * The credential in force was rejected and could never be renewed — it
145
+ * carries no refresh token. The ONE place wording differs by origin;
146
+ * nothing else compares against `origin.source`.
147
+ */
148
+ function credentialRejectedError(origin, envVar) {
149
+ return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
150
+ }
151
+ /**
152
+ * 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.
155
+ */
156
+ function emptyServiceTokenError(spec) {
157
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
158
+ why: `A blank token authenticates nothing, and ${spec.envVar} overrides your stored workspace sessions while it is set.`,
159
+ nextActions: [{
160
+ kind: "run-command",
161
+ label: `Unset ${spec.envVar}`,
162
+ command: `unset ${spec.envVar}`
163
+ }, {
164
+ kind: "user-choice",
165
+ label: `Or set ${spec.envVar} to a valid service token.`
166
+ }]
167
+ });
168
+ }
169
+ /**
170
+ * No session exists for the named workspace. Sessions are created by
171
+ * `prisma auth login` alone — `workspace use` selects among the ones
172
+ * you have.
173
+ */
174
+ function noSessionForWorkspaceError(workspaceRef) {
175
+ return new CliStructuredError("AUTH.NO_SESSION_FOR_WORKSPACE", `You have no session for workspace '${workspaceRef}'.`, { nextActions: [{
176
+ kind: "run-command",
177
+ label: `Sign in and pick '${workspaceRef}' in the browser`,
178
+ command: "prisma auth login"
179
+ }] });
180
+ }
181
+ /**
182
+ * The management API rejected the env-supplied service token (401).
183
+ * There is no refresh for it and nothing stored is cleared.
184
+ */
185
+ function serviceTokenRejectedError(spec) {
186
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_REJECTED", `The management API rejected the service token from ${spec.envVar}.`, { nextActions: [{
187
+ kind: "user-choice",
188
+ label: `Replace ${spec.envVar} with a valid service token, or unset it to use your stored sessions.`
189
+ }] });
190
+ }
191
+ //#endregion
192
+ //#region src/execution/debug.ts
193
+ const DEBUG_ENV_VAR = "PRISMA_NEXT_DEBUG";
194
+ /**
195
+ * The engine's debug valve: silent unless PRISMA_NEXT_DEBUG=1 in the
196
+ * injected env (never process.env), writing to the injected stderr.
197
+ * Token material never reaches it.
198
+ */
199
+ function makeDebugLog(runtime) {
200
+ if (runtime.env[DEBUG_ENV_VAR] !== "1") return () => {};
201
+ return (message) => {
202
+ runtime.stderr.write(`[cli-engine] ${message}\n`);
203
+ };
204
+ }
205
+ //#endregion
206
+ //#region src/execution/api-client.ts
207
+ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
208
+ /**
209
+ * ctx.api: the ENGINE constructs and owns the management API client —
210
+ * ONE client for the active credential, once per run (process pinning
211
+ * makes the memoization correct). Nothing resolves until the first
212
+ * method CALL, so a run that never issues a request never pays for —
213
+ * or depends on — the SDK module load. The client is always the SDK's
214
+ * refreshing one over the storage the manager hands out, whatever the
215
+ * credential's origin: a credential refreshes if it has a refresh
216
+ * token. Every request failure passes through the engine-side mapping
217
+ * below. The returned client is a Proxy whose method wrappers await
218
+ * the lazy construction before applying the call — every client method
219
+ * is async, so the deferral is invisible to callers.
220
+ */
221
+ function buildManagementApiClient(invocation) {
222
+ const debug = makeDebugLog(invocation.runtime);
223
+ const probe = { failure: void 0 };
224
+ let pinned;
225
+ let clientPromise;
226
+ const resolveClient = () => {
227
+ clientPromise ??= constructClient(invocation, debug, probe).then((constructed) => {
228
+ pinned = constructed.pinned;
229
+ return constructed.client;
230
+ });
231
+ return clientPromise;
232
+ };
233
+ return new Proxy({}, { get(_target, property) {
234
+ if (typeof property === "symbol" || property === "then") return;
235
+ return async (...args) => {
236
+ try {
237
+ const client = await resolveClient();
238
+ const value = Reflect.get(client, property);
239
+ if (typeof value !== "function") throw new TypeError(`@prisma/cli-engine: ctx.api.${property} is not a function`);
240
+ return await Reflect.apply(value, client, args);
241
+ } catch (cause) {
242
+ throw await mapRequestFailure(invocation, debug, probe, pinned, cause);
243
+ }
244
+ };
245
+ } });
246
+ }
247
+ async function constructClient(invocation, debug, probe) {
248
+ const manager = invocation.runtime.credentialManager;
249
+ if (manager === void 0) throw credentialsRequiredError();
250
+ const active = await manager.activeCredential();
251
+ if (active === null) throw credentialsRequiredError();
252
+ const config = invocation.runtime.managementApiClientConfig;
253
+ if (config === void 0) throw new Error("@prisma/cli-engine: ctx.api requires Runtime.managementApiClientConfig when a credentialManager is wired");
254
+ const storage = observedTokenStorage(await manager.activeCredentialStorage(), active, debug, probe);
255
+ const { createManagementApiSdk } = await import("@prisma/management-api-sdk");
256
+ return {
257
+ client: createManagementApiSdk({
258
+ clientId: config.clientId,
259
+ redirectUri: config.redirectUri,
260
+ apiBaseUrl: config.apiBaseUrl,
261
+ authBaseUrl: config.authBaseUrl,
262
+ tokenStorage: storage
263
+ }).client,
264
+ pinned: {
265
+ active,
266
+ storage
267
+ }
268
+ };
269
+ }
270
+ /**
271
+ * The manager's storage, with the refresh path observed. The SDK enters
272
+ * withRefreshLock only from its refresh routine, so it marks both the
273
+ * debug valve's "refresh attempted" line and the boundary whose throws
274
+ * count as refresh-path failures.
275
+ */
276
+ function observedTokenStorage(storage, active, debug, probe) {
277
+ const label = active.workspaceId ?? "(no workspace)";
278
+ const observedRefresh = async (fn) => {
279
+ debug(`refresh attempted for session ${label}`);
280
+ try {
281
+ return await fn();
282
+ } catch (failure) {
283
+ probe.failure = failure;
284
+ throw failure;
285
+ }
286
+ };
287
+ return {
288
+ getTokens: () => storage.getTokens(),
289
+ setTokens: (tokens) => storage.setTokens(tokens),
290
+ clearTokens: () => storage.clearTokens(),
291
+ ...storage.clearTokensIfCurrent === void 0 ? {} : { clearTokensIfCurrent: (tokens) => storage.clearTokensIfCurrent(tokens) },
292
+ withRefreshLock: (fn) => storage.withRefreshLock === void 0 ? observedRefresh(fn) : storage.withRefreshLock(() => observedRefresh(fn))
293
+ };
294
+ }
295
+ /**
296
+ * The engine-side request-failure mapping. A structured error raised
297
+ * inside the pipeline (the SDK wraps non-SDK errors into
298
+ * FetchError(cause), so the cause chain is walked for BOTH AuthError
299
+ * and CLI structured errors) is rethrown unwrapped so it settles as
300
+ * itself. An SDK AuthError is discriminated by STATE, never by message
301
+ * parsing: refreshTokenInvalid === true (the SDK's definitive
302
+ * invalid_grant signal, already cleared by compare-and-clear) maps to
303
+ * the expired CLI.CREDENTIALS_REQUIRED; a refresh the SDK refused
304
+ * because the token set carries no refresh token maps to the
305
+ * credential-rejected error, since that credential could never have
306
+ * been renewed; any other AuthError triggers a re-read of the stored
307
+ * state for the credential's own workspace — that session gone means
308
+ * the session-ended CLI.CREDENTIALS_REQUIRED, otherwise the failure was
309
+ * the auth service's and nothing was cleared. A failure that came out
310
+ * of the refresh path without being an AuthError (the SDK throws a
311
+ * plain Error when a rotated token will not decode) is transient too:
312
+ * nothing was cleared, and signing in again is not the fix.
313
+ */
314
+ async function mapRequestFailure(invocation, debug, probe, pinned, cause) {
315
+ const structured = structuredCause(cause);
316
+ if (structured !== void 0) return structured;
317
+ const cameFromRefresh = refreshPathFailed(probe, cause);
318
+ const authError = sdkAuthErrorInCauseChain(cause);
319
+ if (authError === void 0) {
320
+ if (!cameFromRefresh) return cause;
321
+ debug(`refresh failed without an AuthError (${errorTypeOf(probe.failure)})`);
322
+ return authServiceError();
323
+ }
324
+ if (cameFromRefresh) debug(`refresh failed: refreshTokenInvalid=${String(authError.refreshTokenInvalid === true)} error=${endpointVerdict(authError.message)}`);
325
+ if (authError.refreshTokenInvalid === true) return credentialsRequiredError("expired");
326
+ 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);
330
+ }
331
+ /**
332
+ * A 401 that could never have been renewed: the SDK refused to reach
333
+ * the token endpoint at all because the token set carries no refresh
334
+ * token. Read from the storage's own state — never from the SDK's
335
+ * message.
336
+ */
337
+ async function couldNeverHaveBeenRenewed(storage) {
338
+ try {
339
+ const tokens = await storage.getTokens();
340
+ return tokens !== null && !tokens.refreshToken;
341
+ } catch {
342
+ return false;
343
+ }
344
+ }
345
+ async function mapAgainstStoredState(manager, active, cause) {
346
+ const workspaceId = active.workspaceId;
347
+ if (workspaceId === void 0) return authServiceError();
348
+ let stored;
349
+ try {
350
+ stored = await manager.sessions();
351
+ } catch (stateCause) {
352
+ return CliStructuredError.is(stateCause) ? stateCause : cause;
353
+ }
354
+ if (!stored.sessions.some((session) => session.workspaceId === workspaceId)) return credentialsRequiredError("session-ended");
355
+ return authServiceError();
356
+ }
357
+ /** Cause chains can be cyclic (an Error whose `cause` eventually points
358
+ * back at itself); track visited nodes with a depth cap as a backstop
359
+ * so the walk always terminates. */
360
+ const CAUSE_CHAIN_DEPTH_CAP = 32;
361
+ function* causeChain(error) {
362
+ const visited = /* @__PURE__ */ new Set();
363
+ for (let current = error; current instanceof Error && !visited.has(current) && visited.size < CAUSE_CHAIN_DEPTH_CAP; current = current.cause) {
364
+ visited.add(current);
365
+ yield current;
366
+ }
367
+ }
368
+ function structuredCause(error) {
369
+ for (const current of causeChain(error)) if (CliStructuredError.is(current)) return current;
370
+ }
371
+ /** Structural match (name discriminator plus the refreshTokenInvalid
372
+ * field) rather than instanceof, so a duplicate SDK module instance
373
+ * cannot defeat the mapping — and so this check never forces the SDK
374
+ * module to load. */
375
+ function sdkAuthErrorInCauseChain(error) {
376
+ for (const current of causeChain(error)) if (current.name === "AuthError") return current;
377
+ }
378
+ /** The request failure carries the refresh attempt's own throw, so the
379
+ * failure arose in the refresh path rather than in the request. */
380
+ function refreshPathFailed(probe, cause) {
381
+ if (probe.failure === void 0) return false;
382
+ if (cause === probe.failure) return true;
383
+ for (const current of causeChain(cause)) if (current === probe.failure) return true;
384
+ return false;
385
+ }
386
+ function errorTypeOf(error) {
387
+ return error instanceof Error ? error.name : typeof error;
388
+ }
389
+ /**
390
+ * The endpoint's verdict, without its free text. The SDK builds a
391
+ * refresh AuthError's message either as `<error>: <error_description>`
392
+ * from the token endpoint's body or as one of its own fixed strings
393
+ * (which carry the HTTP status). Only the part before the description
394
+ * is logged: the description is text the auth service chose, and the
395
+ * debug valve must never become a way for it to reach a log.
396
+ */
397
+ function endpointVerdict(message) {
398
+ const description = message.indexOf(": ");
399
+ return description === -1 ? message : message.slice(0, description);
400
+ }
401
+ //#endregion
100
402
  //#region src/execution/rendering.ts
101
403
  function firstLine(text) {
102
404
  const newline = text.indexOf("\n");
@@ -185,8 +487,15 @@ function writeDiagnostic(stream, diagnostic) {
185
487
  for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action)}\n`);
186
488
  if (diagnostic.docsUrl !== void 0) stream.write(` docs: ${diagnostic.docsUrl}\n`);
187
489
  }
490
+ /** `label` is required, so a mapper building an action out of a bare
491
+ * command string — a legacy error's follow-up step, with no prose
492
+ * beside it — has nothing to put in the label but the command itself.
493
+ * Only the renderer sees both fields, so only it can tell they are the
494
+ * same string and print it once. */
188
495
  function renderNextAction(action) {
189
- return `→ ${action.label}${action.command === void 0 ? "" : `: ${action.command}`}`;
496
+ const target = action.command ?? action.url;
497
+ const repeatsTheLabel = target === void 0 || target === action.label;
498
+ return `→ ${action.label}${repeatsTheLabel ? "" : `: ${target}`}`;
190
499
  }
191
500
  /** Populates docsUrl from the owning family's docsBaseUrl (base + code)
192
501
  * when the diagnostic does not carry its own — a per-raise docsUrl wins. */
@@ -301,29 +610,25 @@ function checkInteraction(needs, invocation) {
301
610
  function checkDependencies(needs, invocation) {
302
611
  for (const specifier of needs.dependencies) if (!dependencyResolvable(specifier, invocation.runtime.cwd)) return needsErrored(missingDependencyError(specifier, invocation.runtime.packageManager));
303
612
  }
613
+ /**
614
+ * The credentials need, single-sourced from the credential manager:
615
+ * activeCredential() is the local-only truth (the process pin), and
616
+ * its structured errors (sessions held none selected, blank env token)
617
+ * pass through verbatim so the needs check, ctx.activeCredential, and
618
+ * ctx.api raise identically. A host with no manager wired has no
619
+ * credentials at all.
620
+ */
304
621
  async function checkCredentials(needs, invocation) {
305
622
  if (!needs.credentials) return;
306
- let credentials;
623
+ const manager = invocation.runtime.credentialManager;
624
+ if (manager === void 0) return needsErrored(credentialsRequiredError());
307
625
  try {
308
- credentials = await invocation.runtime.getCredentials();
626
+ if (await manager.activeCredential() === null) return needsErrored(credentialsRequiredError());
627
+ return;
309
628
  } 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
- }));
629
+ if (CliStructuredError.is(cause)) return needsErrored(cause);
630
+ throw cause;
317
631
  }
318
- if (credentials === void 0) return needsErrored(credentialsRequiredError());
319
- }
320
- /** The single source of the sign-in error: raised by the needs check
321
- * and by an unauthenticated ctx.api request. */
322
- function credentialsRequiredError() {
323
- return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [{
324
- kind: "user-choice",
325
- label: "Sign in, then run the command again."
326
- }] });
327
632
  }
328
633
  function checkConfiguration(section, invocation) {
329
634
  const fileLevel = invocation.runtime.config.diagnostics.filter((entry) => entry.section === null);
@@ -401,90 +706,22 @@ function missingDependencyError(specifier, packageManager) {
401
706
  });
402
707
  }
403
708
  //#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;
709
+ //#region src/execution/open-url.ts
710
+ async function announceUrl(invocation, request) {
711
+ reportEvent(invocation, {
712
+ kind: "endpoint",
713
+ name: request.message,
714
+ url: request.url
715
+ });
716
+ const open = invocation.runtime.openUrl;
717
+ if (!invocation.state.interactive || open === void 0) return { opened: false };
718
+ try {
719
+ await open(request.url);
720
+ return { opened: true };
721
+ } catch {
722
+ return { opened: false };
476
723
  }
477
724
  }
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
725
  //#endregion
489
726
  //#region src/execution/clack-renderer.ts
490
727
  /**
@@ -538,6 +775,13 @@ async function makeClackRenderer(stdin, stderr) {
538
775
  message: question,
539
776
  initialValue: false
540
777
  }),
778
+ confirmToken: (question, token) => clack.text({
779
+ input,
780
+ output,
781
+ message: `${question} Type ${token} to confirm.`,
782
+ placeholder: token,
783
+ validate: (value) => value === token ? void 0 : `Type ${token} exactly, or press Ctrl-C.`
784
+ }),
541
785
  select: (question, options, initial) => clack.select({
542
786
  input,
543
787
  output,
@@ -560,6 +804,16 @@ async function makeClackRenderer(stdin, stderr) {
560
804
  }
561
805
  //#endregion
562
806
  //#region src/execution/prompts.ts
807
+ /** How often browserWait asks whether the user has finished. */
808
+ const BROWSER_WAIT_POLL_INTERVAL_MS = 1e3;
809
+ /** A `--confirm` value grants at most one consent: the matched value is
810
+ * removed, so two consents on the same token need two --confirms. */
811
+ function consumeConfirmValue(state, token) {
812
+ const index = state.confirmValues.indexOf(token);
813
+ if (index === -1) return false;
814
+ state.confirmValues.splice(index, 1);
815
+ return true;
816
+ }
563
817
  function makeLineReader(stdin, invocation) {
564
818
  const iterator = stdin[Symbol.asyncIterator]();
565
819
  invocation.state.stdinIterator = iterator;
@@ -600,15 +854,53 @@ function promptUnanswerable(question, state) {
600
854
  label: "Run the command from an interactive terminal, or pass a flag that answers the prompt."
601
855
  }] });
602
856
  }
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: [{
857
+ function consentUnavailable(question, state, token) {
858
+ const situation = state.yes ? `"${question}" requires explicit consent, which --yes cannot grant.` : `"${question}" requires explicit consent, and the session is not interactive.`;
859
+ if (token === void 0) return new CliStructuredError("CLI.CONSENT_REQUIRED", situation, { nextActions: [{
605
860
  kind: "user-choice",
606
- label: "Run the command interactively, or pass the command's explicit consent flag if it documents one."
861
+ label: "Run the command interactively. Consent can only be granted outside an interactive terminal when the command declares a consent token."
607
862
  }] });
863
+ return new CliStructuredError("CLI.CONSENT_REQUIRED", `${situation} Grant it by passing --confirm ${token}.`, {
864
+ nextActions: [{
865
+ kind: "user-choice",
866
+ label: `Run the command interactively and type ${token}, or pass --confirm ${token}.`
867
+ }],
868
+ meta: { consentToken: token }
869
+ });
608
870
  }
609
871
  function promptInvalid(question, raw) {
610
872
  return new CliStructuredError("CLI.PROMPT_INVALID", `"${raw}" is not a valid answer to "${question}".`);
611
873
  }
874
+ /** A consent whose token was typed wrong where re-prompting is not
875
+ * possible (scripted answers, piped stdin). */
876
+ function consentTokenMismatch(question, token, raw) {
877
+ return new CliStructuredError("CLI.PROMPT_INVALID", `"${raw}" does not confirm "${question}": the answer must be exactly ${token}.`, { meta: { consentToken: token } });
878
+ }
879
+ /** browserWait outside an interactive terminal: nothing is opened and
880
+ * nothing is polled, so the URL travels in the error instead. */
881
+ function browserWaitUnavailable(message, url) {
882
+ return new CliStructuredError("CLI.INTERACTION_REQUIRED", `${message} requires an interactive terminal: it waits for you to finish at ${url}.`, {
883
+ 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.",
884
+ nextActions: [{
885
+ kind: "user-choice",
886
+ label: `Open ${url} and finish there, then run the command again from an interactive terminal (or pass --interactive).`
887
+ }],
888
+ meta: { url }
889
+ });
890
+ }
891
+ function browserWaitTimedOut(message, url, timeout) {
892
+ return new CliStructuredError("CLI.BROWSER_WAIT_TIMEOUT", `${message} was not finished within ${Math.round(timeout / 1e3)}s.`, {
893
+ why: `The command waited for ${url} and stopped waiting before it completed.`,
894
+ nextActions: [{
895
+ kind: "user-choice",
896
+ label: "Run the command again and finish in the browser."
897
+ }],
898
+ meta: {
899
+ url,
900
+ timeoutMs: timeout
901
+ }
902
+ });
903
+ }
612
904
  function isExplicitYes(raw) {
613
905
  if (typeof raw === "boolean") return raw;
614
906
  return [
@@ -667,6 +959,18 @@ function makePromptSurface(invocation) {
667
959
  if (line === void 0) throw promptCancelled(question);
668
960
  return line;
669
961
  };
962
+ /** The interactive rendering of a consent that declares a token: the
963
+ * user types the token itself. Clack lets them try again; the line
964
+ * renderer cannot, so a wrong answer there is structural. */
965
+ const confirmByTyping = async (question, token) => {
966
+ if (useClack()) {
967
+ await renderWithClack(question, (r) => r.confirmToken(question, token));
968
+ return true;
969
+ }
970
+ const typed = await ask(question, `? ${question} (type ${token} to confirm) `);
971
+ if (typeof typed !== "string" || typed.trim() !== token) throw consentTokenMismatch(question, token, String(typed));
972
+ return true;
973
+ };
670
974
  return {
671
975
  confirm: async (question, opts) => {
672
976
  const fallback = opts?.default;
@@ -680,8 +984,13 @@ function makePromptSurface(invocation) {
680
984
  else if (fallback === false) hint = "(y/N)";
681
985
  return parseBooleanAnswer(await ask(question, `? ${question} ${hint} `), fallback, question);
682
986
  },
683
- consent: async (question) => {
684
- if (state.yes || !state.interactive) throw consentUnavailable(question, state);
987
+ consent: async (question, opts) => {
988
+ const token = opts?.token;
989
+ if (state.yes || !state.interactive) {
990
+ if (token !== void 0 && consumeConfirmValue(state, token)) return true;
991
+ throw consentUnavailable(question, state, token);
992
+ }
993
+ if (token !== void 0) return confirmByTyping(question, token);
685
994
  if (useClack()) return renderWithClack(question, (r) => r.consent(question));
686
995
  return isExplicitYes(await ask(question, `? ${question} (y/n) `));
687
996
  },
@@ -721,6 +1030,20 @@ function makePromptSurface(invocation) {
721
1030
  if (typeof raw !== "string") throw promptInvalid(question, String(raw));
722
1031
  if (raw === "") return fallback ?? "";
723
1032
  return raw;
1033
+ },
1034
+ browserWait: async ({ url, message, poll, timeout, interval }) => {
1035
+ if (!state.interactive) throw browserWaitUnavailable(message, url);
1036
+ await announceUrl(invocation, {
1037
+ url,
1038
+ message
1039
+ });
1040
+ const deadline = invocation.now().getTime() + timeout;
1041
+ for (;;) {
1042
+ if (invocation.signal.aborted) throw promptCancelled(message);
1043
+ if (await poll(invocation.signal)) return;
1044
+ if (invocation.now().getTime() >= deadline) throw browserWaitTimedOut(message, url, timeout);
1045
+ await invocation.delay(interval ?? BROWSER_WAIT_POLL_INTERVAL_MS, invocation.signal);
1046
+ }
724
1047
  }
725
1048
  };
726
1049
  }
@@ -754,7 +1077,7 @@ function materializePresentation(state, ui, presentations) {
754
1077
  next: presentations.next?.() ?? []
755
1078
  };
756
1079
  }
757
- function makeContext(invocation, config) {
1080
+ function makeContext(invocation, config, managesCredentials) {
758
1081
  const state = invocation.state;
759
1082
  const ui = makeUi(state.colorEnabled);
760
1083
  const present = (outcome, presentations) => {
@@ -770,21 +1093,31 @@ function makeContext(invocation, config) {
770
1093
  });
771
1094
  };
772
1095
  let api;
773
- return {
1096
+ const context = {
774
1097
  config,
775
1098
  present,
776
- getCredentials: () => invocation.runtime.getCredentials(),
1099
+ activeCredential: () => invocation.runtime.credentialManager?.activeCredential() ?? Promise.resolve(null),
777
1100
  get api() {
778
1101
  api ??= invocation.hooks.managementApi?.client ?? buildManagementApiClient(invocation);
779
1102
  return api;
780
1103
  },
781
1104
  report: (event) => reportEvent(invocation, event),
782
1105
  prompt: makePromptSurface(invocation),
1106
+ openUrl: (request) => announceUrl(invocation, request),
783
1107
  signal: invocation.signal,
784
1108
  cwd: invocation.runtime.cwd,
785
1109
  env: invocation.runtime.env,
786
1110
  requireDependency: async (specifier) => dependencyResolvable(specifier, invocation.runtime.cwd) ? okVoid() : notOk(missingDependencyError(specifier, invocation.runtime.packageManager))
787
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;
1118
+ }
1119
+ });
1120
+ return context;
788
1121
  }
789
1122
  //#endregion
790
1123
  //#region src/execution/shared-flags.ts
@@ -797,6 +1130,7 @@ const RESERVED_FLAG_NAMES = new Set([
797
1130
  "verbose",
798
1131
  "quiet",
799
1132
  "yes",
1133
+ "confirm",
800
1134
  "interactive",
801
1135
  "color",
802
1136
  "help",
@@ -847,6 +1181,14 @@ const SHARED_FLAG_PARAMETERS = {
847
1181
  default: false,
848
1182
  brief: "Accept prompt defaults without asking"
849
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
+ },
850
1192
  interactive: {
851
1193
  kind: "boolean",
852
1194
  optional: true,
@@ -887,6 +1229,7 @@ function explicitFormat(argv) {
887
1229
  function applySharedFlags(state, shared, runtime) {
888
1230
  state.format = shared.format ?? resolveAutoFormat(shared, runtime);
889
1231
  state.yes = shared.yes === true;
1232
+ state.confirmValues = [...shared.confirm ?? []];
890
1233
  state.interactive = shared.interactive ?? defaultInteractive(runtime);
891
1234
  state.logLevel = resolveLogLevel(shared);
892
1235
  state.colorEnabled = shared.color ?? (runtime.isTty.stdout && runtime.env.NO_COLOR === void 0);
@@ -1466,15 +1809,31 @@ function settleUnhandled(spec, invocation, stricliExitCode) {
1466
1809
  //#endregion
1467
1810
  //#region src/execution/engine.ts
1468
1811
  function buildEngine(spec, options) {
1469
- return new EngineImpl(spec, options?.now);
1812
+ return new EngineImpl(spec, options?.now, options?.delay);
1813
+ }
1814
+ /** Resolves on the timer OR on the signal, whichever comes first — the
1815
+ * caller decides what an abort means, and no timer outlives the run. */
1816
+ function waitFor(ms, signal) {
1817
+ if (signal.aborted) return Promise.resolve();
1818
+ return new Promise((resolve) => {
1819
+ const finish = () => {
1820
+ clearTimeout(timer);
1821
+ signal.removeEventListener("abort", finish);
1822
+ resolve();
1823
+ };
1824
+ const timer = setTimeout(finish, ms);
1825
+ signal.addEventListener("abort", finish, { once: true });
1826
+ });
1470
1827
  }
1471
1828
  var EngineImpl = class {
1472
1829
  spec;
1473
1830
  root;
1474
1831
  now;
1475
- constructor(spec, now = () => /* @__PURE__ */ new Date()) {
1832
+ delay;
1833
+ constructor(spec, now = () => /* @__PURE__ */ new Date(), delay = waitFor) {
1476
1834
  this.spec = spec;
1477
1835
  this.now = now;
1836
+ this.delay = delay;
1478
1837
  this.root = buildRoutes(spec, buildCommandTree(spec), "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
1479
1838
  }
1480
1839
  async execute(argv, runtime, hooks) {
@@ -1485,6 +1844,7 @@ var EngineImpl = class {
1485
1844
  format: sniffFormat(argv, runtime),
1486
1845
  logLevel: "info",
1487
1846
  yes: false,
1847
+ confirmValues: [],
1488
1848
  interactive: defaultInteractive(runtime),
1489
1849
  colorEnabled: false,
1490
1850
  resolved: false,
@@ -1511,6 +1871,7 @@ var EngineImpl = class {
1511
1871
  runtime,
1512
1872
  hooks: { ...hooks },
1513
1873
  now: this.now,
1874
+ delay: this.delay,
1514
1875
  state,
1515
1876
  signal: controller.signal
1516
1877
  };
@@ -1605,7 +1966,7 @@ var EngineImpl = class {
1605
1966
  flags: declaredFlags(entry.def, rawFlags),
1606
1967
  positionals: distributePositionals(entry.def, values)
1607
1968
  };
1608
- const ctx = makeContext(invocation, needsOutcome.config);
1969
+ const ctx = makeContext(invocation, needsOutcome.config, entry.def.kind === "result-command" && entry.def.managesCredentials);
1609
1970
  if (entry.def.kind === "session-command") {
1610
1971
  try {
1611
1972
  const result = await handler(args, ctx);
@@ -1700,4 +2061,4 @@ function distributePositionals(def, values) {
1700
2061
  return positionals;
1701
2062
  }
1702
2063
  //#endregion
1703
- export { positional as i, PRESENTED as n, flag as r, buildEngine as t };
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 };