@prisma/cli-engine 0.0.3 → 0.0.5

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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as ActiveCredential, A as OpenUrlOutcome, B as exitWithChildStatus, C as InputStream, D as Runtime, E as PRISMA_CONFIG_VERSION, F as ExitWithChildStatusOptions, G as Presentations, H as Format, I as SpawnChild, J as Ui, K as PresentedResult, L as SpawnOptions, M as PromptSurface, N as ChildResult, O as BrowserWaitRequest, P as ChildStatusSettlement, Q as StreamMeta, R as SpawnRequest, S as HostProcess, T as OutputStream, U as Outcome, V as Block, W as PRESENTED, X as Severity, Y as EngineEvent, Z as StreamEvent, _ as SessionCommandDefinition, _t as PositionalSpec, a as defineCommandFamily, at as StoredSessions, b as defineServerCommand, c as CommandHandler, ct as TokenStorage, d as CompletedEnvelope, dt as defineConfigSection, et as Credential, f as ErroredEnvelope, ft as Args, g as ServerCommandDefinition, gt as FlagSpec, h as NeedsSpec, ht as CommandArgs, i as MountedTree, it as Session, j as OpenUrlRequest, k as CommandContext, l as CommandHelp, lt as ConfigSection, m as HelpSpec, mt as Char, n as RunSummary, nt as CredentialManager, o as AnyCommand, ot as ManagementApiClient, p as Handler, pt as ArgsSpec, q as TreeNode, r as CommandFamily, rt as CredentialOrigin, s as CommandDefinition, st as ManagementApiClientConfig, t as EngineCommandSnapshot, tt as CredentialIdentity, u as CommandNeeds, ut as SectionValidation, v as SpawnDeclarations, vt as flag, w as LoadedConfig, x as defineSessionCommand, y as defineCommand, yt as positional, z as SpawnedChild } from "./run-summary-DMFNIvjx.js";
1
+ import { $ as ActiveCredential, A as OpenUrlOutcome, B as exitWithChildStatus, C as InputStream, D as Runtime, E as PRISMA_CONFIG_VERSION, F as ExitWithChildStatusOptions, G as Presentations, H as Format, I as SpawnChild, J as Ui, K as PresentedResult, L as SpawnOptions, M as PromptSurface, N as ChildResult, O as BrowserWaitRequest, P as ChildStatusSettlement, Q as StreamMeta, R as SpawnRequest, S as HostProcess, T as OutputStream, U as Outcome, V as Block, W as PRESENTED, X as Severity, Y as EngineEvent, Z as StreamEvent, _ as SessionCommandDefinition, _t as FlagSpec, a as defineCommandFamily, at as Session, b as defineServerCommand, bt as positional, c as CommandHandler, ct as ManagementApiClientConfig, d as CompletedEnvelope, dt as SectionValidation, et as Credential, f as ErroredEnvelope, ft as defineConfigSection, g as ServerCommandDefinition, gt as CommandArgs, h as NeedsSpec, ht as Char, i as MountedTree, it as SERVICE_TOKEN_ENV_VAR, j as OpenUrlRequest, k as CommandContext, l as CommandHelp, lt as TokenStorage, m as HelpSpec, mt as ArgsSpec, n as RunSummary, nt as CredentialManager, o as AnyCommand, ot as StoredSessions, p as Handler, pt as Args, q as TreeNode, r as CommandFamily, rt as CredentialOrigin, s as CommandDefinition, st as ManagementApiClient, t as EngineCommandSnapshot, tt as CredentialIdentity, u as CommandNeeds, ut as ConfigSection, v as SpawnDeclarations, vt as PositionalSpec, w as LoadedConfig, x as defineSessionCommand, y as defineCommand, yt as flag, z as SpawnedChild } from "./run-summary-CLpl1gmC.js";
2
2
  import { n as CliStructuredError } from "./protocol-CpZLdxML.js";
3
3
 
4
4
  //#region src/cli.d.ts
@@ -41,19 +41,20 @@ declare function createCli(spec: {
41
41
  //#endregion
42
42
  //#region src/config-loader.d.ts
43
43
  /**
44
- * Attaches the version marker to a prisma.config.ts export. Top-level
45
- * keys are the config sections. Never throws — bad section values are
46
- * the section validator's problem, not defineConfig's.
44
+ * Attaches the version marker to a prisma.config.ts export. Each
45
+ * top-level key names a config section, and the recognised section
46
+ * names are exactly the ones the CLI's command families declare. Never
47
+ * throws — bad section values are the section validator's problem, not
48
+ * defineConfig's.
47
49
  */
48
50
  declare function defineConfig<T extends Record<string, unknown>>(config: T): T & {
49
51
  readonly $prismaConfig: number;
50
52
  };
51
53
  /**
52
- * The real-disk loader behind Runtime.config: reads prisma.config.ts
53
- * from cwd (cwd only — no walking up) and produces LoadedConfig. The
54
- * bin builds Runtime.config with this; tests hand in fixtures.
54
+ * The real-disk loader behind Runtime.loadConfig. The bin binds it to
55
+ * the process cwd; tests hand in fixtures.
55
56
  */
56
- declare function loadConfig(cwd: string): Promise<LoadedConfig>;
57
+ declare function loadConfig(cwd: string, configPath?: string): Promise<LoadedConfig>;
57
58
  //#endregion
58
59
  //#region src/credential-errors.d.ts
59
60
  type CredentialsRequiredReason = "unauthenticated" | "expired" | "expiring-soon" | "session-ended" | "sessions-held-none-selected";
@@ -116,10 +117,15 @@ declare class EnvironmentCredentialManager implements CredentialManager {
116
117
  }
117
118
  //#endregion
118
119
  //#region src/token-claims.d.ts
119
- /** The `workspace_id` claim, which is what sessions are keyed by. */
120
- declare function claimedWorkspaceId(token: string): string | undefined;
121
- /** The workspace a credential names: its `workspace_id` claim, or the
122
- * workspace its subject names when it is a service token. */
120
+ /**
121
+ * The workspace a credential names. One derivation, because a token
122
+ * says it one of two ways and every caller wants the same answer: an
123
+ * OAuth token carries `workspace_id`, while a service token names its
124
+ * workspace through `sub` and carries no `workspace_id` at all. Reading
125
+ * only the claim was a second path that happened to work because
126
+ * service tokens reached it by a different route — a split nothing
127
+ * enforced.
128
+ */
123
129
  declare function credentialWorkspaceId(token: string): string | undefined;
124
130
  declare function claimedExpiresAt(token: string): Date | undefined;
125
131
  /**
@@ -129,4 +135,4 @@ declare function claimedExpiresAt(token: string): Date | undefined;
129
135
  */
130
136
  declare function claimedIdentity(token: string): CredentialIdentity | undefined;
131
137
  //#endregion
132
- export { type ActiveCredential, type AnyCommand, type Args, type ArgsSpec, type Block, type BrowserWaitRequest, type Char, type ChildResult, type ChildStatusSettlement, type Cli, type CliRunHooks, type CommandArgs, type CommandContext, type CommandDefinition, type CommandFamily, type CommandHandler, type CommandHelp, type CommandNeeds, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, EnvironmentCredentialManager, type ErroredEnvelope, type ExitWithChildStatusOptions, type FlagSpec, type Format, type Handler, type HelpSpec, type HostProcess, type InputStream, type LoadedConfig, type ManagementApiClient, type ManagementApiClientConfig, type MountedTree, type NeedsSpec, type OpenUrlOutcome, type OpenUrlRequest, type Outcome, type OutputStream, PRESENTED, PRISMA_CONFIG_VERSION, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RunSummary, type Runtime, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type SpawnChild, type SpawnDeclarations, type SpawnOptions, type SpawnRequest, type SpawnedChild, type StoredSessions, type StreamEvent, type StreamMeta, type TokenStorage, type TreeNode, type Ui, authServiceError, claimedExpiresAt, claimedIdentity, claimedWorkspaceId, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
138
+ export { type ActiveCredential, type AnyCommand, type Args, type ArgsSpec, type Block, type BrowserWaitRequest, type Char, type ChildResult, type ChildStatusSettlement, type Cli, type CliRunHooks, type CommandArgs, type CommandContext, type CommandDefinition, type CommandFamily, type CommandHandler, type CommandHelp, type CommandNeeds, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, EnvironmentCredentialManager, type ErroredEnvelope, type ExitWithChildStatusOptions, type FlagSpec, type Format, type Handler, type HelpSpec, type HostProcess, type InputStream, type LoadedConfig, type ManagementApiClient, type ManagementApiClientConfig, type MountedTree, type NeedsSpec, type OpenUrlOutcome, type OpenUrlRequest, type Outcome, type OutputStream, PRESENTED, PRISMA_CONFIG_VERSION, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RunSummary, type Runtime, SERVICE_TOKEN_ENV_VAR, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type SpawnChild, type SpawnDeclarations, type SpawnOptions, type SpawnRequest, type SpawnedChild, type StoredSessions, type StreamEvent, type StreamMeta, type TokenStorage, type TreeNode, type Ui, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
package/dist/index.js CHANGED
@@ -1,8 +1,5 @@
1
- import { a as buildEngine, c as credentialWorkspaceMismatchError, d as noSessionForWorkspaceError, f as PRESENTED, h as positional, i as credentialWorkspaceId, l as credentialsRequiredError, m as flag, n as claimedIdentity, o as authServiceError, p as exitWithChildStatus, r as claimedWorkspaceId, s as credentialRejectedError, t as claimedExpiresAt, u as emptyServiceTokenError } from "./token-claims-DXO0q52l.js";
1
+ import { _ as PRESENTED, b as positional, c as PRISMA_CONFIG_VERSION, d as authServiceError, f as credentialRejectedError, g as noSessionForWorkspaceError, h as emptyServiceTokenError, i as buildEngine, l as SERVICE_TOKEN_ENV_VAR, m as credentialsRequiredError, n as claimedIdentity, o as defineConfig, p as credentialWorkspaceMismatchError, r as credentialWorkspaceId, s as loadConfig, t as claimedExpiresAt, u as WORKSPACE_ID_ENV_VAR, v as exitWithChildStatus, y as flag } from "./token-claims-Bpb1vA2N.js";
2
2
  import { t as CliStructuredError } from "./protocol-C1JQcGl9.js";
3
- import { join } from "node:path";
4
- import { existsSync } from "node:fs";
5
- import { pathToFileURL } from "node:url";
6
3
  //#region src/cli.ts
7
4
  /**
8
5
  * Shell-side construction. Group help is declared with the mount.
@@ -79,121 +76,6 @@ function defineServerCommand(def) {
79
76
  });
80
77
  }
81
78
  //#endregion
82
- //#region src/runtime.ts
83
- /**
84
- * The config contract version defineConfig writes as the structural
85
- * `$prismaConfig` marker; the loader checks it before interpreting
86
- * anything.
87
- */
88
- const PRISMA_CONFIG_VERSION = 1;
89
- //#endregion
90
- //#region src/config-loader.ts
91
- /**
92
- * The minimal prisma.config.ts loader behind Runtime.config:
93
- * discover the file in cwd (cwd only — no walking up), evaluate it,
94
- * check the defineConfig version marker, and produce LoadedConfig.
95
- *
96
- * Absence is not an error: section validators own absence, so a missing
97
- * file is an empty LoadedConfig. An evaluated file WITHOUT the marker (a
98
- * classic Prisma 7 config, which uses the same filename) fails early
99
- * with one typed diagnostic — the loader never partially interprets an
100
- * unmarked file, and never guesses.
101
- */
102
- const CONFIG_FILE_NAME = "prisma.config.ts";
103
- const MARKER_KEY = "$prismaConfig";
104
- /**
105
- * Attaches the version marker to a prisma.config.ts export. Top-level
106
- * keys are the config sections. Never throws — bad section values are
107
- * the section validator's problem, not defineConfig's.
108
- */
109
- function defineConfig(config) {
110
- return Object.freeze({
111
- ...config,
112
- $prismaConfig: 1
113
- });
114
- }
115
- function hasVersionMarker(value) {
116
- return typeof value === "object" && value !== null && typeof value[MARKER_KEY] === "number";
117
- }
118
- function fileLevelConfig(diagnostic) {
119
- return {
120
- sections: {},
121
- diagnostics: [{
122
- section: null,
123
- diagnostic
124
- }]
125
- };
126
- }
127
- function missingMarkerDiagnostic(path) {
128
- return {
129
- code: "CLI.CONFIG_MISSING_MARKER",
130
- severity: "error",
131
- summary: "This prisma.config.ts was not written for this version of the Prisma CLI, so it cannot be used.",
132
- why: "Configs for this CLI are created with defineConfig, which records a version marker on the exported object. This file's default export has no marker — it is most likely a Prisma 7 config, which uses the same filename — and the CLI stops rather than misread it.",
133
- nextActions: [{
134
- kind: "user-choice",
135
- label: "Migrate the file: wrap the exported object in defineConfig from @prisma/cli-engine and export the result as the default export."
136
- }],
137
- where: { path }
138
- };
139
- }
140
- function firstLine(text) {
141
- const newline = text.indexOf("\n");
142
- return (newline === -1 ? text : text.slice(0, newline)).trim();
143
- }
144
- function unsupportedVersionDiagnostic(path, found) {
145
- return {
146
- code: "CLI.CONFIG_INVALID",
147
- severity: "error",
148
- summary: `prisma.config.ts declares config version ${found}, but this CLI supports only version 1.`,
149
- nextActions: [{
150
- kind: "user-choice",
151
- label: "Regenerate the config with a defineConfig matching this CLI, or update the CLI to a version that supports the declared config version."
152
- }],
153
- where: { path }
154
- };
155
- }
156
- function unreadableDiagnostic(path, cause) {
157
- return {
158
- code: "CLI.CONFIG_UNREADABLE",
159
- severity: "error",
160
- summary: `prisma.config.ts could not be evaluated: ${firstLine(cause instanceof Error ? cause.message : String(cause))}`,
161
- nextActions: [{
162
- kind: "user-choice",
163
- label: "Fix the error in the file, then run the command again."
164
- }],
165
- where: { path }
166
- };
167
- }
168
- /**
169
- * The real-disk loader behind Runtime.config: reads prisma.config.ts
170
- * from cwd (cwd only — no walking up) and produces LoadedConfig. The
171
- * bin builds Runtime.config with this; tests hand in fixtures.
172
- */
173
- async function loadConfig(cwd) {
174
- const path = join(cwd, CONFIG_FILE_NAME);
175
- if (!existsSync(path)) return {
176
- sections: {},
177
- diagnostics: []
178
- };
179
- let loaded;
180
- try {
181
- loaded = await import(pathToFileURL(path).href);
182
- } catch (cause) {
183
- return fileLevelConfig(unreadableDiagnostic(path, cause));
184
- }
185
- const exported = loaded.default;
186
- if (!hasVersionMarker(exported)) return fileLevelConfig(missingMarkerDiagnostic(path));
187
- const version = exported[MARKER_KEY];
188
- if (version !== 1) return fileLevelConfig(unsupportedVersionDiagnostic(path, version));
189
- const sections = {};
190
- for (const [key, value] of Object.entries(exported)) if (key !== MARKER_KEY) sections[key] = value;
191
- return {
192
- sections,
193
- diagnostics: []
194
- };
195
- }
196
- //#endregion
197
79
  //#region src/config-section.ts
198
80
  function defineConfigSection(spec) {
199
81
  return Object.freeze({
@@ -211,8 +93,6 @@ function defineConfigSection(spec) {
211
93
  * refuses with a structured error. Env is a construction input; nothing
212
94
  * here reads process.env.
213
95
  */
214
- const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
215
- const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
216
96
  /** The SDK's Tokens requires a workspace id; an environment credential
217
97
  * that names none is given this instead. It never leaves the manager
218
98
  * and is never the empty string. */
@@ -315,4 +195,4 @@ var EnvironmentCredentialManager = class {
315
195
  }
316
196
  };
317
197
  //#endregion
318
- export { EnvironmentCredentialManager, PRESENTED, PRISMA_CONFIG_VERSION, authServiceError, claimedExpiresAt, claimedIdentity, claimedWorkspaceId, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
198
+ export { EnvironmentCredentialManager, PRESENTED, PRISMA_CONFIG_VERSION, SERVICE_TOKEN_ENV_VAR, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, defineServerCommand, defineSessionCommand, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional };
@@ -154,6 +154,11 @@ interface ManagementApiClientConfig {
154
154
  }
155
155
  //#endregion
156
156
  //#region src/credential-manager.d.ts
157
+ /** The environment variables that supply a credential to a process: a
158
+ * service token, plus the workspace it acts in when the token's own
159
+ * claims name none. EnvironmentCredentialManager reads the pair; the
160
+ * spawn path writes it into a child's environment. */
161
+ declare const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
157
162
  /**
158
163
  * The proof material. Seen by the login flow (which mints it),
159
164
  * createSession (which stores it), and the engine (which authenticates
@@ -519,8 +524,9 @@ declare const CHILD_STATUS: unique symbol;
519
524
  * The sanctioned settlement outcome for "exit with the child's status
520
525
  * verbatim": no envelope, the same settlement bypass server commands
521
526
  * use. Built exclusively by exitWithChildStatus, and only settled by a
522
- * command that declares maySpawn. `nextActions` render to stderr before
523
- * the process exits with the child's code.
527
+ * command that declares maySpawn, from a child result the engine
528
+ * itself produced. `nextActions` render to stderr before the process
529
+ * exits with the child's code.
524
530
  */
525
531
  interface ChildStatusSettlement {
526
532
  readonly [CHILD_STATUS]: true;
@@ -532,10 +538,10 @@ interface ExitWithChildStatusOptions {
532
538
  * failed converge's reproduce hint. The envelope stays absent. */
533
539
  readonly nextActions?: readonly NextAction[];
534
540
  }
535
- /** A signal-killed child settles 128 + the signal number; otherwise the
536
- * child's own exit code, verbatim. Unknown is never success: a signal
537
- * outside the portable table, or an adapter that cannot say how the
538
- * child ended (exitCode and signal both null), settles 1. */
541
+ /** Settles the run with the status of the child `ctx.spawn` returned.
542
+ * A result the engine did not produce is a construction error at
543
+ * settlement: this is how a real child's status reaches the exit code,
544
+ * not how a handler picks one. */
539
545
  declare function exitWithChildStatus(child: ChildResult, options?: ExitWithChildStatusOptions): ChildStatusSettlement;
540
546
  //#endregion
541
547
  //#region src/context.d.ts
@@ -609,6 +615,10 @@ interface CommandContext<TConfig = undefined, TCode extends number = never> {
609
615
  * Fires on Ctrl-C/SIGTERM (engine-owned; a second signal force-exits
610
616
  * through the runtime's exit proxy). Session commands run until it
611
617
  * fires.
618
+ *
619
+ * Once it has fired the engine settles the run at 130/143 from its
620
+ * own record of the signal, whatever the handler goes on to return —
621
+ * so cleanup code never states an exit code of its own.
612
622
  */
613
623
  readonly signal: AbortSignal;
614
624
  /** Where the user invoked the CLI. Handlers never read process.cwd(). */
@@ -752,10 +762,15 @@ interface Runtime {
752
762
  */
753
763
  readonly onSignal: (cb: (signal: "SIGINT" | "SIGTERM") => void) => () => void;
754
764
  /**
755
- * Loaded config + file-level diagnostics; the shell builds this via
756
- * the unified loader. Tests hand in fixtures.
765
+ * Reads prisma.config.ts, on demand. The engine calls it only when
766
+ * the command it is about to run declares a config section, so a run
767
+ * that needs no config never touches the file. `configPath` is the
768
+ * file `--config` named: the loader resolves it against the runtime's
769
+ * cwd and reports its absence. Absent means look for prisma.config.ts
770
+ * in cwd, where absence is not an error. The bin wires the real disk
771
+ * loader; tests hand in fixtures.
757
772
  */
758
- readonly config: LoadedConfig;
773
+ readonly loadConfig: (configPath?: string) => Promise<LoadedConfig>;
759
774
  /**
760
775
  * The credential manager the bin wires. It is the only source of
761
776
  * the needs check, ctx.activeCredential, and ctx.api; absent means
@@ -822,9 +837,19 @@ interface HostProcess {
822
837
  exit(code: number): never;
823
838
  }
824
839
  interface LoadedConfig {
840
+ /**
841
+ * The file this config came from, absolute: the one `--config` named,
842
+ * or prisma.config.ts in cwd. A loader that found no file still names
843
+ * the file it looked for — with no file there are no sections, and
844
+ * the engine reads the path only to name the file when it reports a
845
+ * top-level key that is not one of the CLI's sections.
846
+ */
847
+ readonly path: string;
825
848
  /**
826
849
  * Raw section values by name; validation happens per command via its
827
- * command family's section token.
850
+ * command family's section token. The engine, not the loader, checks
851
+ * these names against the sections the CLI declares, so the closed
852
+ * set holds whatever loader a host wires.
828
853
  */
829
854
  readonly sections: Readonly<Record<string, unknown>>;
830
855
  /**
@@ -992,9 +1017,10 @@ declare function defineCommand<TFlags extends Record<string, FlagSpec<unknown>>
992
1017
  * UNLESS it declares `maySpawn`, in which case it rejects --json as soon
993
1018
  * as the command is known, before anything runs (S3): output delegated
994
1019
  * to a child process cannot be framed. A session that returns
995
- * ok(undefined) exits 0; one that returns ok(exitWithChildStatus(child))
996
- * exits with the child's status, which is the only way a session
997
- * settles non-zero without erroring.
1020
+ * ok(undefined) exits 0 — or 130/143 when a signal ended the run, which
1021
+ * the engine settles from its own record of that signal, not from
1022
+ * anything the handler returns; one that returns
1023
+ * ok(exitWithChildStatus(child)) exits with the child's status.
998
1024
  */
999
1025
  interface SessionCommandDefinition<TFlags extends Record<string, FlagSpec<unknown>> = Record<never, FlagSpec<unknown>>, TPositionals extends Record<string, PositionalSpec<unknown>> = Record<never, PositionalSpec<unknown>>, TConfig = undefined> {
1000
1026
  readonly kind: "session-command";
@@ -1164,4 +1190,4 @@ interface RunSummary {
1164
1190
  readonly snapshot: EngineCommandSnapshot;
1165
1191
  }
1166
1192
  //#endregion
1167
- export { ActiveCredential as $, OpenUrlOutcome as A, exitWithChildStatus as B, InputStream as C, Runtime as D, PRISMA_CONFIG_VERSION as E, ExitWithChildStatusOptions as F, Presentations as G, Format as H, SpawnChild as I, Ui as J, PresentedResult as K, SpawnOptions as L, PromptSurface as M, ChildResult as N, BrowserWaitRequest as O, ChildStatusSettlement as P, StreamMeta as Q, SpawnRequest as R, HostProcess as S, OutputStream as T, Outcome as U, Block as V, PRESENTED as W, Severity as X, EngineEvent as Y, StreamEvent as Z, SessionCommandDefinition as _, PositionalSpec as _t, defineCommandFamily as a, StoredSessions as at, defineServerCommand as b, CommandHandler as c, TokenStorage$1 as ct, CompletedEnvelope as d, defineConfigSection as dt, Credential as et, ErroredEnvelope as f, Args as ft, ServerCommandDefinition as g, FlagSpec as gt, NeedsSpec as h, CommandArgs as ht, MountedTree as i, Session as it, OpenUrlRequest as j, CommandContext as k, CommandHelp as l, ConfigSection as lt, HelpSpec as m, Char as mt, RunSummary as n, CredentialManager as nt, AnyCommand as o, ManagementApiClient$1 as ot, Handler as p, ArgsSpec as pt, TreeNode as q, CommandFamily as r, CredentialOrigin as rt, CommandDefinition as s, ManagementApiClientConfig as st, EngineCommandSnapshot as t, CredentialIdentity as tt, CommandNeeds as u, SectionValidation as ut, SpawnDeclarations as v, flag as vt, LoadedConfig as w, defineSessionCommand as x, defineCommand as y, positional as yt, SpawnedChild as z };
1193
+ export { ActiveCredential as $, OpenUrlOutcome as A, exitWithChildStatus as B, InputStream as C, Runtime as D, PRISMA_CONFIG_VERSION as E, ExitWithChildStatusOptions as F, Presentations as G, Format as H, SpawnChild as I, Ui as J, PresentedResult as K, SpawnOptions as L, PromptSurface as M, ChildResult as N, BrowserWaitRequest as O, ChildStatusSettlement as P, StreamMeta as Q, SpawnRequest as R, HostProcess as S, OutputStream as T, Outcome as U, Block as V, PRESENTED as W, Severity as X, EngineEvent as Y, StreamEvent as Z, SessionCommandDefinition as _, FlagSpec as _t, defineCommandFamily as a, Session as at, defineServerCommand as b, positional as bt, CommandHandler as c, ManagementApiClientConfig as ct, CompletedEnvelope as d, SectionValidation as dt, Credential as et, ErroredEnvelope as f, defineConfigSection as ft, ServerCommandDefinition as g, CommandArgs as gt, NeedsSpec as h, Char as ht, MountedTree as i, SERVICE_TOKEN_ENV_VAR as it, OpenUrlRequest as j, CommandContext as k, CommandHelp as l, TokenStorage$1 as lt, HelpSpec as m, ArgsSpec as mt, RunSummary as n, CredentialManager as nt, AnyCommand as o, StoredSessions as ot, Handler as p, Args as pt, TreeNode as q, CommandFamily as r, CredentialOrigin as rt, CommandDefinition as s, ManagementApiClient$1 as st, EngineCommandSnapshot as t, CredentialIdentity as tt, CommandNeeds as u, ConfigSection as ut, SpawnDeclarations as v, PositionalSpec as vt, LoadedConfig as w, defineSessionCommand as x, defineCommand as y, flag as yt, SpawnedChild as z };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as ActiveCredential, I as SpawnChild, K as PresentedResult, N as ChildResult, R as SpawnRequest, Y as EngineEvent, Z as StreamEvent, at as StoredSessions, ct as TokenStorage, et as Credential, i as MountedTree, it as Session, n as RunSummary, nt as CredentialManager, ot as ManagementApiClient, r as CommandFamily, st as ManagementApiClientConfig } from "./run-summary-DMFNIvjx.js";
1
+ import { $ as ActiveCredential, D as Runtime, I as SpawnChild, K as PresentedResult, N as ChildResult, R as SpawnRequest, Y as EngineEvent, Z as StreamEvent, at as Session, ct as ManagementApiClientConfig, et as Credential, i as MountedTree, lt as TokenStorage, n as RunSummary, nt as CredentialManager, ot as StoredSessions, r as CommandFamily, st as ManagementApiClient } from "./run-summary-CLpl1gmC.js";
2
2
 
3
3
  //#region src/in-memory-credential-manager.d.ts
4
4
  /** A stored session with its credential material — what the manager
@@ -158,7 +158,15 @@ declare function createTestCli(spec: {
158
158
  readonly groups?: Readonly<Record<string, {
159
159
  readonly brief: string;
160
160
  }>>;
161
+ /** Seeds the sections the config file would have held. The engine
162
+ * asks for them only when the command declares a config section, and
163
+ * checks them as it would a real file's: a section name no mounted
164
+ * command declares fails the run. */
161
165
  readonly config?: Readonly<Record<string, unknown>>;
166
+ /** Replaces the loader outright — to assert what --config asked for,
167
+ * to return file-level diagnostics, or to prove a run never reads
168
+ * the config at all. Wins over `config` when both are given. */
169
+ readonly loadConfig?: Runtime["loadConfig"];
162
170
  /** Convenience manager seed: createSession runs its real claims
163
171
  * derivation on this credential (mint the token with mintTestJwt). */
164
172
  readonly credential?: Credential; /** Stored sessions, mirroring the state file's records. */
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as buildEngine, c as credentialWorkspaceMismatchError, d as noSessionForWorkspaceError, i as credentialWorkspaceId, l as credentialsRequiredError, n as claimedIdentity, r as claimedWorkspaceId, t as claimedExpiresAt } from "./token-claims-DXO0q52l.js";
1
+ import { g as noSessionForWorkspaceError, i as buildEngine, m as credentialsRequiredError, n as claimedIdentity, p as credentialWorkspaceMismatchError, r as credentialWorkspaceId, t as claimedExpiresAt } from "./token-claims-Bpb1vA2N.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/in-memory-credential-manager.ts
4
4
  /**
@@ -102,7 +102,7 @@ var InMemoryCredentialManager = class {
102
102
  this.selection = seed.selectedWorkspaceId;
103
103
  this.environmentCredential = seed.environmentCredential;
104
104
  if (seed.credential !== void 0) {
105
- const workspaceId = claimedWorkspaceId(seed.credential.token);
105
+ const workspaceId = credentialWorkspaceId(seed.credential.token);
106
106
  if (workspaceId === void 0) throw new Error("@prisma/cli-engine/testing: the `credential` seed runs createSession's claims derivation — the token must be a JWT with `workspace_id` (use mintTestJwt)");
107
107
  this.applyCreateSession(seed.credential, workspaceId);
108
108
  }
@@ -194,7 +194,7 @@ var InMemoryCredentialManager = class {
194
194
  },
195
195
  setTokens: async (tokens) => {
196
196
  if (pinnedRecord() === void 0) throw credentialsRequiredError("session-ended");
197
- const claimed = claimedWorkspaceId(tokens.accessToken);
197
+ const claimed = credentialWorkspaceId(tokens.accessToken);
198
198
  if (claimed !== void 0 && claimed !== workspaceId) throw credentialWorkspaceMismatchError(workspaceId);
199
199
  this.storedSessions = this.storedSessions.map((stored) => stored.workspaceId === workspaceId ? {
200
200
  ...stored,
@@ -254,7 +254,7 @@ var InMemoryCredentialManager = class {
254
254
  return credential;
255
255
  }
256
256
  applyCreateSession(credential, workspaceId) {
257
- const claimed = claimedWorkspaceId(credential.token);
257
+ const claimed = credentialWorkspaceId(credential.token);
258
258
  if (claimed !== void 0 && claimed !== workspaceId) throw credentialWorkspaceMismatchError(workspaceId);
259
259
  const record = {
260
260
  workspaceId,
@@ -401,10 +401,11 @@ function createTestCli(spec) {
401
401
  signalListeners.delete(cb);
402
402
  };
403
403
  },
404
- config: {
404
+ loadConfig: spec.loadConfig ?? (async (configPath) => ({
405
+ path: configPath ?? "prisma.config.ts",
405
406
  sections: spec.config ?? {},
406
407
  diagnostics: []
407
- },
408
+ })),
408
409
  credentialManager,
409
410
  managementApiClientConfig,
410
411
  spawn: recordingSpawn(spec.spawn ?? scriptedSpawn(spec.spawnScript ?? (() => ({
@@ -1,7 +1,8 @@
1
1
  import { i as okVoid, n as notOk, t as CliStructuredError } from "./protocol-C1JQcGl9.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
4
- import { resolve } from "node:path";
4
+ import { existsSync, realpathSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
5
6
  import { Readable, Writable } from "node:stream";
6
7
  import { Buffer } from "node:buffer";
7
8
  //#region src/args.ts
@@ -97,6 +98,26 @@ const positional = {
97
98
  //#endregion
98
99
  //#region src/spawn.ts
99
100
  const CHILD_STATUS = Symbol.for("@prisma/cli-engine.childStatus");
101
+ /** Marks a ChildResult the engine watched a real child produce. */
102
+ const ENGINE_SPAWNED = Symbol.for("@prisma/cli-engine.engineSpawned");
103
+ function markEngineSpawned(value) {
104
+ return Object.freeze(Object.defineProperty(value, ENGINE_SPAWNED, { value: true }));
105
+ }
106
+ function isEngineSpawned(value) {
107
+ return value[ENGINE_SPAWNED] === true;
108
+ }
109
+ /**
110
+ * The child result ctx.spawn hands back: the engine mints it from what
111
+ * the adapter reported, so a handler cannot pass off an invented one as
112
+ * a child's status. exitWithChildStatus carries the mark onto its
113
+ * settlement and the settlement refuses an unmarked one.
114
+ */
115
+ function engineSpawnedResult(result) {
116
+ return markEngineSpawned({
117
+ exitCode: result.exitCode,
118
+ signal: result.signal
119
+ });
120
+ }
100
121
  /** Signal numbers shared by Linux, macOS and the BSDs. Numbers that
101
122
  * differ by platform (SIGBUS, SIGUSR1, SIGUSR2, …) are deliberately
102
123
  * absent — a wrong 128+n is worse than the unknown-signal fallback. */
@@ -118,21 +139,22 @@ const SIGNAL_NUMBERS = {
118
139
  * child's own exit code, verbatim. Unknown is never success: a signal
119
140
  * outside the portable table, or an adapter that cannot say how the
120
141
  * child ended (exitCode and signal both null), settles 1. */
142
+ function childExitCode(child) {
143
+ if (child.signal === null) return child.exitCode ?? 1;
144
+ const signalNumber = SIGNAL_NUMBERS[child.signal];
145
+ return signalNumber === void 0 ? 1 : 128 + signalNumber;
146
+ }
147
+ /** Settles the run with the status of the child `ctx.spawn` returned.
148
+ * A result the engine did not produce is a construction error at
149
+ * settlement: this is how a real child's status reaches the exit code,
150
+ * not how a handler picks one. */
121
151
  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({
152
+ const settlement = {
132
153
  [CHILD_STATUS]: true,
133
- exitCode: child.exitCode ?? 1,
134
- nextActions
135
- });
154
+ exitCode: childExitCode(child),
155
+ nextActions: Object.freeze([...options?.nextActions ?? []])
156
+ };
157
+ return isEngineSpawned(child) ? markEngineSpawned(settlement) : Object.freeze(settlement);
136
158
  }
137
159
  function isChildStatusSettlement(value) {
138
160
  return typeof value === "object" && value !== null && value[CHILD_STATUS] === true;
@@ -257,6 +279,14 @@ function serviceTokenRejectedError(spec) {
257
279
  }] });
258
280
  }
259
281
  //#endregion
282
+ //#region src/credential-manager.ts
283
+ /** The environment variables that supply a credential to a process: a
284
+ * service token, plus the workspace it acts in when the token's own
285
+ * claims name none. EnvironmentCredentialManager reads the pair; the
286
+ * spawn path writes it into a child's environment. */
287
+ const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
288
+ const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
289
+ //#endregion
260
290
  //#region src/execution/debug.ts
261
291
  const DEBUG_ENV_VAR = "PRISMA_NEXT_DEBUG";
262
292
  /**
@@ -272,7 +302,6 @@ function makeDebugLog(runtime) {
272
302
  }
273
303
  //#endregion
274
304
  //#region src/execution/api-client.ts
275
- const SERVICE_TOKEN_ENV_VAR$1 = "PRISMA_SERVICE_TOKEN";
276
305
  /**
277
306
  * ctx.api: the ENGINE constructs and owns the management API client —
278
307
  * ONE client for the active credential, once per run (process pinning
@@ -393,8 +422,8 @@ async function mapRequestFailure(invocation, debug, probe, pinned, cause) {
393
422
  const manager = invocation.runtime.credentialManager;
394
423
  if (manager === void 0 || pinned === void 0) return authError.refreshTokenInvalid === true ? credentialsRequiredError("expired") : authServiceError();
395
424
  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);
425
+ if (authError.refreshTokenInvalid === true) return homeRecord ? credentialsRequiredError("expired") : credentialRejectedError(pinned.active.origin, SERVICE_TOKEN_ENV_VAR);
426
+ if (cameFromRefresh && await couldNeverHaveBeenRenewed(pinned.storage)) return credentialRejectedError(pinned.active.origin, SERVICE_TOKEN_ENV_VAR);
398
427
  return homeRecord ? mapAgainstStoredState(manager, pinned.active, cause) : authServiceError();
399
428
  }
400
429
  /** Whether this credential is backed by a stored session. The origin
@@ -474,6 +503,277 @@ function endpointVerdict(message) {
474
503
  return description === -1 ? message : message.slice(0, description);
475
504
  }
476
505
  //#endregion
506
+ //#region src/runtime.ts
507
+ /**
508
+ * The config contract version defineConfig writes as the structural
509
+ * `$prismaConfig` marker; the loader checks it before interpreting
510
+ * anything.
511
+ */
512
+ const PRISMA_CONFIG_VERSION = 1;
513
+ //#endregion
514
+ //#region src/config-loader.ts
515
+ /**
516
+ * The prisma.config.ts loader behind Runtime.loadConfig: resolve the
517
+ * file (the one `--config` named, otherwise prisma.config.ts in cwd —
518
+ * cwd only, no walking up), evaluate it, check the defineConfig version
519
+ * marker, and produce LoadedConfig.
520
+ *
521
+ * Which section names a CLI recognises is not this module's business:
522
+ * it hands back every top-level key the file had, and the engine — not
523
+ * a Runtime member a host can replace — checks them against the
524
+ * sections the mounted commands declare.
525
+ *
526
+ * Absence of an undiscovered file is not an error: section validators
527
+ * own absence, so no prisma.config.ts in cwd yields no sections and no
528
+ * diagnostics.
529
+ * Absence of a file the user NAMED with --config is an error — they
530
+ * said which file to read and it was not there. An evaluated file
531
+ * WITHOUT the marker (a classic Prisma 7 config, which uses the same
532
+ * filename) fails early with one typed diagnostic — the loader never
533
+ * partially interprets an unmarked file, and never guesses.
534
+ *
535
+ * Evaluation goes through c12, the same loader prisma/prisma and
536
+ * prisma/composer use, because the shipped CLI runs on ordinary Node,
537
+ * which cannot import a .ts file. c12 transpiles it with jiti first.
538
+ * Every c12 feature beyond "evaluate this one file" is switched off
539
+ * below so discovery and merging stay exactly as they were.
540
+ */
541
+ const CONFIG_FILE_NAME = "prisma.config.ts";
542
+ const MARKER_KEY = "$prismaConfig";
543
+ /**
544
+ * Top-level keys the config file format keeps for itself, so no
545
+ * section may be named one of them; buildCommandTree rejects the
546
+ * declaration at construction.
547
+ *
548
+ * `$`-prefixed keys are metadata: `$prismaConfig` is the version
549
+ * marker, and config loaders read `$env`, `$<NODE_ENV>` and `$meta` —
550
+ * c12 deletes `$meta` from the config object whatever else it is told.
551
+ * `extends` is the key config loaders take as "merge another file into
552
+ * this one". This loader switches that off (`extend: false`), so a key
553
+ * by that name does reach the config object. It stays reserved anyway:
554
+ * the file format has no layering of its own, `extends` is the name it
555
+ * would want if it gained some, and a section called `extends` would
556
+ * disappear the moment anything switched merging back on.
557
+ *
558
+ * `__proto__` is reserved for the reason `$meta` is: c12 merges layers
559
+ * with defu, which drops the key rather than let a config file reach an
560
+ * object's prototype, so a section by that name could never be read.
561
+ */
562
+ function reservedConfigSectionName(name) {
563
+ return name === "extends" || name === "__proto__" || name.startsWith("$");
564
+ }
565
+ /**
566
+ * Attaches the version marker to a prisma.config.ts export. Each
567
+ * top-level key names a config section, and the recognised section
568
+ * names are exactly the ones the CLI's command families declare. Never
569
+ * throws — bad section values are the section validator's problem, not
570
+ * defineConfig's.
571
+ */
572
+ function defineConfig(config) {
573
+ return Object.freeze({
574
+ ...config,
575
+ $prismaConfig: 1
576
+ });
577
+ }
578
+ function hasVersionMarker(value) {
579
+ return typeof value === "object" && value !== null && typeof value[MARKER_KEY] === "number";
580
+ }
581
+ function fileLevelConfig(path, diagnostic) {
582
+ return {
583
+ path,
584
+ sections: {},
585
+ diagnostics: [{
586
+ section: null,
587
+ diagnostic
588
+ }]
589
+ };
590
+ }
591
+ function missingMarkerDiagnostic(path) {
592
+ return {
593
+ code: "CLI.CONFIG_MISSING_MARKER",
594
+ severity: "error",
595
+ summary: `${path} was not written for this version of the Prisma CLI, so it cannot be used.`,
596
+ why: "Configs for this CLI are created with defineConfig, which records a version marker on the exported object. This file's default export has no marker — it is most likely a Prisma 7 config, which uses the same filename — and the CLI stops rather than misread it.",
597
+ nextActions: [{
598
+ kind: "user-choice",
599
+ label: "Migrate the file: wrap the exported object in defineConfig from @prisma/cli-engine and export the result as the default export."
600
+ }],
601
+ where: { path }
602
+ };
603
+ }
604
+ function firstLine$1(text) {
605
+ const newline = text.indexOf("\n");
606
+ return (newline === -1 ? text : text.slice(0, newline)).trim();
607
+ }
608
+ function unsupportedVersionDiagnostic(path, found) {
609
+ return {
610
+ code: "CLI.CONFIG_VERSION_UNSUPPORTED",
611
+ severity: "error",
612
+ summary: `${path} declares config version ${found}, but this CLI supports only version 1.`,
613
+ nextActions: [{
614
+ kind: "user-choice",
615
+ label: "Regenerate the config with a defineConfig matching this CLI, or update the CLI to a version that supports the declared config version."
616
+ }],
617
+ where: { path }
618
+ };
619
+ }
620
+ function missingNamedFileDiagnostic(path) {
621
+ return {
622
+ code: "CLI.CONFIG_NOT_FOUND",
623
+ severity: "error",
624
+ summary: `--config named ${path}, and there is no file there.`,
625
+ why: "A config file found by discovery may be absent — the section validators supply their defaults. A config file named on the command line may not: the CLI would otherwise run against different settings than the ones asked for.",
626
+ nextActions: [{
627
+ kind: "user-choice",
628
+ label: "Correct the path passed to --config, or drop the flag to use the prisma.config.ts in the current directory."
629
+ }],
630
+ where: { path }
631
+ };
632
+ }
633
+ function unreadableDiagnostic(path, cause) {
634
+ return {
635
+ code: "CLI.CONFIG_UNREADABLE",
636
+ severity: "error",
637
+ summary: `${path} could not be evaluated: ${firstLine$1(cause instanceof Error ? cause.message : String(cause))}`,
638
+ nextActions: [{
639
+ kind: "user-choice",
640
+ label: "Fix the error in the file, then run the command again."
641
+ }],
642
+ where: { path }
643
+ };
644
+ }
645
+ /**
646
+ * Everything c12 does beyond evaluating the one file it was handed.
647
+ * Composer leaves the last five at their defaults and can afford to:
648
+ * its config has a fixed set of keys, where every top-level key here is
649
+ * a user-authored section name, so all five are reachable from an
650
+ * ordinary config file.
651
+ */
652
+ const EVALUATE_ONE_FILE_ONLY = {
653
+ rcFile: false,
654
+ globalRc: false,
655
+ packageJson: false,
656
+ /** Else `$production` blocks merge over the root under NODE_ENV. */
657
+ envName: false,
658
+ /** Else `$prismaConfig` is stripped and every config reads unmarked. */
659
+ omit$Keys: false,
660
+ /** Else `extends` is a merge directive rather than a section name. */
661
+ extend: false,
662
+ /** Else an `extends` URL is fetched over the network and evaluated. */
663
+ giget: false,
664
+ /** Else a neighbouring .env is read into process.env. */
665
+ dotenv: false
666
+ };
667
+ /**
668
+ * Evaluates the file at `path` and returns its default export. The call
669
+ * is prisma/composer's `loadAppConfig` with prisma/prisma's dynamic
670
+ * import, so a run with no config file never pays for c12 or jiti.
671
+ *
672
+ * The loaded-file check is in both references: c12 is asked for one
673
+ * exact path and must not answer with another.
674
+ */
675
+ async function evaluateConfigFile(path) {
676
+ const result = await (await import("c12")).loadConfig({
677
+ name: "prisma",
678
+ configFile: path,
679
+ cwd: dirname(path),
680
+ ...EVALUATE_ONE_FILE_ONLY
681
+ });
682
+ const loadedFile = result.configFile;
683
+ if (typeof loadedFile !== "string" || realpathSync(loadedFile) !== realpathSync(path)) throw new Error(`config loading resolved ${String(loadedFile)} instead of ${path}`);
684
+ return result.config;
685
+ }
686
+ /** Built with fromEntries rather than assigned key by key: assigning a
687
+ * key named `__proto__` runs Object.prototype's setter instead of
688
+ * creating an own property, so that one key would disappear from
689
+ * Object.keys and never be reported as unrecognised. */
690
+ function sectionsOf(exported) {
691
+ return Object.fromEntries(Object.entries(exported).filter(([key]) => key !== MARKER_KEY));
692
+ }
693
+ /**
694
+ * The file to read, always absolute: the one --config named, resolved
695
+ * against cwd, or prisma.config.ts in cwd.
696
+ *
697
+ * Absolute is not cosmetic, and it is one more thing than either
698
+ * reference repository does — both are handed an absolute path before
699
+ * they reach c12, so neither has to resolve one. Given a relative path,
700
+ * c12 resolves it a second time against its own cwd and looks for a
701
+ * file that is not there, and jiti cannot import a relative specifier
702
+ * at all. Resolving here also makes the file's path in every diagnostic
703
+ * absolute, and makes the loaded-file comparison compare like with
704
+ * like.
705
+ */
706
+ function fileToRead(cwd, configPath) {
707
+ const root = resolve(cwd);
708
+ return configPath === void 0 ? join(root, CONFIG_FILE_NAME) : resolve(root, configPath);
709
+ }
710
+ /**
711
+ * The real-disk loader behind Runtime.loadConfig. The bin binds it to
712
+ * the process cwd; tests hand in fixtures.
713
+ */
714
+ async function loadConfig(cwd, configPath) {
715
+ const path = fileToRead(cwd, configPath);
716
+ if (!existsSync(path)) return configPath === void 0 ? {
717
+ path,
718
+ sections: {},
719
+ diagnostics: []
720
+ } : fileLevelConfig(path, missingNamedFileDiagnostic(path));
721
+ let exported;
722
+ try {
723
+ exported = await evaluateConfigFile(path);
724
+ } catch (cause) {
725
+ return fileLevelConfig(path, unreadableDiagnostic(path, cause));
726
+ }
727
+ if (!hasVersionMarker(exported)) return fileLevelConfig(path, missingMarkerDiagnostic(path));
728
+ const version = exported[MARKER_KEY];
729
+ if (version !== 1) return fileLevelConfig(path, unsupportedVersionDiagnostic(path, version));
730
+ return {
731
+ path,
732
+ sections: sectionsOf(exported),
733
+ diagnostics: []
734
+ };
735
+ }
736
+ //#endregion
737
+ //#region src/execution/pre-parse-argv.ts
738
+ function flagTokens(argv) {
739
+ const terminator = argv.indexOf("--");
740
+ return terminator === -1 ? argv : argv.slice(0, terminator);
741
+ }
742
+ function versionFlagGiven(argv) {
743
+ return flagTokens(argv).includes("--version");
744
+ }
745
+ /**
746
+ * The one malformed `--config` shape the parser cannot see. stricli
747
+ * matches a flag-with-value against `/^--([a-z][a-z-.\d_]+)=(.+)$/`,
748
+ * which needs at least one character after the `=`, so the bare token
749
+ * `--config=` is not a flag to it at all and falls through to the
750
+ * command's positional arguments. prisma/prisma rejects that shape as a
751
+ * usage error (a user who wrote `--config=` meant to name a file), so
752
+ * the engine checks for the exact token before handing argv over.
753
+ *
754
+ * Running before parsing, this cannot tell a flag from data: it rejects
755
+ * `--config=` wherever it appears ahead of a bare `--`, including as
756
+ * another flag's value or a positional. prisma/prisma's scan does the
757
+ * same and does not stop at `--`; the token is an odd one to need as
758
+ * data, and `--` remains the way to pass it.
759
+ */
760
+ function configFlagGivenNoValue(argv) {
761
+ return flagTokens(argv).includes("--config=");
762
+ }
763
+ /** The format requested by --json / --format / --format=<value>, if
764
+ * any. */
765
+ function formatFlagGiven(argv) {
766
+ const tokens = flagTokens(argv);
767
+ for (const [index, token] of tokens.entries()) {
768
+ if (token === "--json" || token === "--format=json") return "json";
769
+ if (token === "--format=human") return "human";
770
+ if (token === "--format") {
771
+ const value = tokens[index + 1];
772
+ if (value === "json" || value === "human") return value;
773
+ }
774
+ }
775
+ }
776
+ //#endregion
477
777
  //#region src/execution/shared-flags.ts
478
778
  /** The engine-injected shared flag family. Commands cannot declare
479
779
  * these names or aliases; handlers never see their values. */
@@ -487,6 +787,7 @@ const RESERVED_FLAG_NAMES = new Set([
487
787
  "confirm",
488
788
  "interactive",
489
789
  "color",
790
+ "config",
490
791
  "help",
491
792
  "helpAll",
492
793
  "version"
@@ -554,8 +855,33 @@ const SHARED_FLAG_PARAMETERS = {
554
855
  optional: true,
555
856
  withNegated: true,
556
857
  brief: "Force ANSI color on or off"
858
+ },
859
+ config: {
860
+ kind: "parsed",
861
+ parse: parseConfigPath,
862
+ placeholder: "path",
863
+ optional: true,
864
+ brief: "Read this config file instead of ./prisma.config.ts"
557
865
  }
558
866
  };
867
+ /** Rejects `--config ""`, which a shell produces from
868
+ * `--config "$UNSET_VAR"`. prisma/prisma treats the empty value as a
869
+ * usage error rather than letting it reach the loader as an empty
870
+ * path, and so does this: the parser turns the throw into the run's
871
+ * usage error. */
872
+ function parseConfigPath(input) {
873
+ if (input === "") throw new Error("--config needs a path, and was given an empty value");
874
+ return input;
875
+ }
876
+ function configFlagGivenNoValueError() {
877
+ return new CliStructuredError("CLI.INVALID_ARGUMENTS", "--config needs a path, and was given an empty value", {
878
+ why: "`--config=` binds the flag to an empty value.",
879
+ nextActions: [{
880
+ kind: "user-choice",
881
+ label: "Pass a config path: --config <path> or --config=<path>."
882
+ }]
883
+ });
884
+ }
559
885
  const SHARED_ALIASES = {
560
886
  v: "verbose",
561
887
  q: "quiet",
@@ -563,22 +889,9 @@ const SHARED_ALIASES = {
563
889
  };
564
890
  /** The pre-parse format decision: json framing must be in effect before
565
891
  * stricli parses (its own failure output is framed too), so the format
566
- * flags are scanned from raw argv. */
892
+ * flags are read from raw argv and a TTY stdout decides the rest. */
567
893
  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
- }
894
+ return formatFlagGiven(argv) ?? (runtime.isTty.stdout ? "human" : "json");
582
895
  }
583
896
  function applySharedFlags(state, shared, runtime) {
584
897
  state.format = shared.format ?? resolveAutoFormat(shared, runtime);
@@ -587,6 +900,7 @@ function applySharedFlags(state, shared, runtime) {
587
900
  state.interactive = shared.interactive ?? defaultInteractive(runtime);
588
901
  state.logLevel = resolveLogLevel(shared);
589
902
  state.colorEnabled = shared.color ?? (runtime.isTty.stdout && runtime.env.NO_COLOR === void 0);
903
+ state.configPath = shared.config;
590
904
  }
591
905
  /** Interactive iff TTY stdin outside CI; --interactive and
592
906
  * --no-interactive override in either direction. Format never decides
@@ -687,6 +1001,22 @@ function validateSectionOwnership(spec, path, def) {
687
1001
  if (commandFamily === void 0) return;
688
1002
  if (commandFamily.configSection !== section) throw constructionError(`command '${path}' needs the '${section.name}' config section, which is not its command family's section`);
689
1003
  }
1004
+ /** The config file's top-level keys are the declared section names, so
1005
+ * a section may only be named something the file format leaves free:
1006
+ * not `$`-prefixed (those are metadata — $prismaConfig is the version
1007
+ * marker, and a $meta key is deleted before the loader ever sees it),
1008
+ * and not `extends` (the key config loaders take as an instruction to
1009
+ * merge another file in). Both the families and the commands mounted
1010
+ * without one are checked: whoever declares the section, claiming a
1011
+ * reserved name is broken at build time, not at a user's runtime. */
1012
+ function validateConfigSectionNames(spec) {
1013
+ for (const commandFamily of spec.commandFamilies) rejectReservedSectionName("command family", commandFamily.configSection);
1014
+ for (const [path, def] of Object.entries(spec.commands)) rejectReservedSectionName(`command '${path}'`, def.needs.config);
1015
+ }
1016
+ function rejectReservedSectionName(owner, section) {
1017
+ if (section === void 0 || !reservedConfigSectionName(section.name)) return;
1018
+ throw constructionError(`${owner} declares config section '${section.name}', a name the config file reserves ('extends' is a config loader's merge directive, and '$'-prefixed keys are metadata)`);
1019
+ }
690
1020
  function validateDocsBaseUrls(spec) {
691
1021
  for (const commandFamily of spec.commandFamilies) {
692
1022
  const base = commandFamily.docsBaseUrl;
@@ -697,6 +1027,7 @@ function buildCommandTree(spec) {
697
1027
  const paths = Object.keys(spec.commands);
698
1028
  if (paths.length === 0) throw constructionError("createCli requires at least one mounted command");
699
1029
  validateDocsBaseUrls(spec);
1030
+ validateConfigSectionNames(spec);
700
1031
  const root = emptyNode();
701
1032
  for (const path of paths) {
702
1033
  const def = spec.commands[path];
@@ -923,7 +1254,7 @@ async function checkNeeds(def, invocation) {
923
1254
  const credentials = await checkCredentials(needs, invocation);
924
1255
  if (credentials.failure !== void 0) return credentials.failure;
925
1256
  if (needs.config !== void 0) {
926
- const outcome = checkConfiguration(needs.config, invocation);
1257
+ const outcome = await checkConfiguration(needs.config, invocation);
927
1258
  return outcome.kind === "ok" ? {
928
1259
  ...outcome,
929
1260
  spawnCredential: credentials.spawnCredential
@@ -983,16 +1314,52 @@ function nearExpiryFailure(credential, invocation) {
983
1314
  if (credential.expiresAt.getTime() - invocation.now().getTime() > 3e5) return;
984
1315
  return needsErrored(credentialsRequiredError("expiring-soon"));
985
1316
  }
986
- function checkConfiguration(section, invocation) {
987
- const fileLevel = invocation.runtime.config.diagnostics.filter((entry) => entry.section === null);
988
- if (fileLevel.length > 0) return needsErrored(structuredErrorFromDiagnostic(fileLevel[0].diagnostic), fileLevel.slice(1).map((entry) => entry.diagnostic));
989
- return validateConfigSection(section, invocation);
1317
+ /**
1318
+ * A top-level key in the config file that is not one of the sections
1319
+ * the mounted commands and command families declare. The set is closed,
1320
+ * so an unrecognised key is a typo or a leftover, and staying silent
1321
+ * would mean quietly ignoring settings the user wrote.
1322
+ *
1323
+ * The check is the engine's rather than the loader's because the loader
1324
+ * is a Runtime member a host supplies: a check on the far side of that
1325
+ * seam holds only for as long as every host writes one.
1326
+ */
1327
+ function unknownSectionDiagnostic(path, key, configSections) {
1328
+ return {
1329
+ code: "CLI.CONFIG_UNKNOWN_SECTION",
1330
+ severity: "error",
1331
+ summary: `${path} has a top-level key '${key}', which is not a config section this CLI recognises.`,
1332
+ why: `The sections this CLI recognises are: ${[...configSections].sort().join(", ")}.`,
1333
+ nextActions: [{
1334
+ kind: "user-choice",
1335
+ label: "Remove the key, or rename it to one of the recognised section names."
1336
+ }],
1337
+ where: { path }
1338
+ };
1339
+ }
1340
+ function unknownSections(loaded, configSections) {
1341
+ const declared = new Set(configSections);
1342
+ return Object.keys(loaded.sections).filter((key) => !declared.has(key)).map((key) => unknownSectionDiagnostic(loaded.path, key, configSections));
1343
+ }
1344
+ /** The config file is read HERE and nowhere else, so a command with no
1345
+ * needs.config never touches it. The file `--config` named travels on
1346
+ * the run state; the closed set of section names comes from the
1347
+ * mounted command families, and every key outside it is reported here
1348
+ * whatever the loader did or did not check. */
1349
+ async function checkConfiguration(section, invocation) {
1350
+ const configPath = invocation.state.configPath;
1351
+ const loaded = await invocation.runtime.loadConfig(configPath);
1352
+ const fileLevel = [...loaded.diagnostics.filter((entry) => entry.section === null).map((entry) => entry.diagnostic), ...unknownSections(loaded, invocation.configSections)];
1353
+ if (fileLevel.length > 0) return needsErrored(structuredErrorFromDiagnostic(fileLevel[0]), fileLevel.slice(1));
1354
+ return validateConfigSection(section, loaded, invocation, configPath ?? "prisma.config.ts");
990
1355
  }
991
1356
  /** Validates the command's needed config section. The validator
992
1357
  * owns absence (it receives undefined when the section is missing) and
993
- * never throws — a throw is an engine-boundary bug, settled as one. */
994
- function validateConfigSection(section, invocation) {
995
- const raw = invocation.runtime.config.sections[section.name];
1358
+ * never throws — a throw is an engine-boundary bug, settled as one.
1359
+ * `configFile` is named in the error so a run under --config points at
1360
+ * the file it actually read. */
1361
+ function validateConfigSection(section, loaded, invocation, configFile) {
1362
+ const raw = loaded.sections[section.name];
996
1363
  let validation;
997
1364
  try {
998
1365
  validation = section.validate(raw);
@@ -1002,7 +1369,7 @@ function validateConfigSection(section, invocation) {
1002
1369
  cause: new Error(`@prisma/cli-engine: the '${section.name}' config section validator threw instead of returning diagnostics (a validator never throws)`, { cause })
1003
1370
  };
1004
1371
  }
1005
- if (!validation.ok) return needsErrored(new CliStructuredError("CLI.CONFIG_INVALID", `The '${section.name}' section of prisma.config.ts is invalid.`, { nextActions: [{
1372
+ if (!validation.ok) return needsErrored(new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${section.name}' section of ${configFile} is invalid.`, { nextActions: [{
1006
1373
  kind: "user-choice",
1007
1374
  label: "Fix the reported problems in that section, then run the command again."
1008
1375
  }] }), validation.diagnostics);
@@ -1429,8 +1796,6 @@ function makePromptSurface(invocation) {
1429
1796
  }
1430
1797
  //#endregion
1431
1798
  //#region src/execution/spawn.ts
1432
- const SERVICE_TOKEN_ENV_VAR = "PRISMA_SERVICE_TOKEN";
1433
- const WORKSPACE_ID_ENV_VAR = "PRISMA_WORKSPACE_ID";
1434
1799
  /**
1435
1800
  * D1 ruling (S3): how long a child terminated by a programmatic abort
1436
1801
  * has to exit on its own after SIGTERM before the engine sends SIGKILL.
@@ -1511,7 +1876,7 @@ async function runChild(invocation, terminal, spawnChild, request) {
1511
1876
  const ended = new AbortController();
1512
1877
  armTerminationLadder(invocation, terminal, child, ended.signal);
1513
1878
  try {
1514
- return await child.ended;
1879
+ return engineSpawnedResult(await child.ended);
1515
1880
  } catch (cause) {
1516
1881
  throw spawnFailedError(request.command, cause);
1517
1882
  } finally {
@@ -1952,7 +2317,8 @@ function settleCompleted(invocation, def, presented) {
1952
2317
  }
1953
2318
  const state = invocation.state;
1954
2319
  invocation.hooks.onPresented?.(presented);
1955
- state.settledExitCode = presented.exitCode;
2320
+ const exitCode = runExitCode(invocation, presented.exitCode);
2321
+ state.settledExitCode = exitCode;
1956
2322
  if (state.format === "json") {
1957
2323
  emitFrame(invocation, {
1958
2324
  kind: "result",
@@ -1960,7 +2326,7 @@ function settleCompleted(invocation, def, presented) {
1960
2326
  ok: true,
1961
2327
  commandId: state.commandId,
1962
2328
  result: presented.presentation.json === void 0 ? presented.data : presented.presentation.json,
1963
- exitCode: presented.exitCode,
2329
+ exitCode,
1964
2330
  diagnostics: presented.diagnostics.map((diagnostic) => withDocsUrl(state, diagnostic)),
1965
2331
  nextActions: presented.presentation.next
1966
2332
  },
@@ -1986,10 +2352,26 @@ function settleErrored(invocation, error, diagnostics = []) {
1986
2352
  nextActions: error.nextActions
1987
2353
  });
1988
2354
  }
1989
- /** Signal exit codes: 130 SIGINT, 143 SIGTERM. The engine's own
1990
- * controller only ever aborts with a signal name. */
1991
- function signalExitCode(reason) {
1992
- return reason === "SIGTERM" ? 143 : 130;
2355
+ /** The conventional code for a delivered signal: 128 + its number, so
2356
+ * 130 for SIGINT and 143 for SIGTERM. */
2357
+ function signalExitCode(signal) {
2358
+ return signal === "SIGTERM" ? 143 : 130;
2359
+ }
2360
+ /**
2361
+ * The engine's own signal record decides how a run ends. A run a
2362
+ * delivered signal terminated settles 128 + that signal's number even
2363
+ * when its handler caught the signal, cleaned up, and returned
2364
+ * successfully: the exit code states how the RUN ended, and a handler
2365
+ * cannot author it — the documented codes stop at 99.
2366
+ *
2367
+ * Verbatim codes are the exception, because they were never this CLI's
2368
+ * to state: a real child's status (the child owned the terminal and the
2369
+ * signal reached it too) and a server command's protocol conclusion
2370
+ * both pass through untouched.
2371
+ */
2372
+ function runExitCode(invocation, completed) {
2373
+ const signal = invocation.state.deliveredSignal;
2374
+ return signal === void 0 ? completed : signalExitCode(signal);
1993
2375
  }
1994
2376
  function isAbortCause(cause, signal) {
1995
2377
  if (!signal.aborted) return false;
@@ -2003,7 +2385,8 @@ function settleThrown(invocation, cause) {
2003
2385
  }
2004
2386
  function settleAborted(invocation) {
2005
2387
  const state = invocation.state;
2006
- state.settledExitCode = signalExitCode(invocation.signal.reason);
2388
+ const signal = state.deliveredSignal;
2389
+ state.settledExitCode = signal === void 0 ? 3 : signalExitCode(signal);
2007
2390
  emitErrored(invocation, {
2008
2391
  ok: false,
2009
2392
  commandId: state.commandId,
@@ -2021,32 +2404,42 @@ function settleAborted(invocation) {
2021
2404
  * Settle an exit code the engine did not author, verbatim, with no
2022
2405
  * envelope and no presentation: something other than this CLI's code
2023
2406
  * space produced it. The two callers are the child-status settlement
2024
- * and the server-command handoff.
2407
+ * and the server-command handoff. A delivered signal does not overrule
2408
+ * it — a code from outside is reported as it was received.
2025
2409
  */
2026
2410
  function settleVerbatimExitCode(invocation, exitCode) {
2027
2411
  invocation.state.settledExitCode = exitCode;
2028
2412
  }
2029
2413
  /**
2030
2414
  * 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.
2415
+ * verbatim: the one path on which a result command settles a code it
2416
+ * never documented, because the code is not the handler's own
2417
+ * conclusion, it is the child's.
2418
+ *
2419
+ * Two conditions fence it, both construction errors. The command must
2420
+ * hand the terminal to another program — reachable from a
2421
+ * non-declaring handler this would also end a json stream without its
2422
+ * terminal result frame. And the status must be one the engine watched
2423
+ * a real child produce: a handler that invents a child result is
2424
+ * choosing an exit code through a door meant for reporting one, and a
2425
+ * handler interrupted mid-run has no need to, because the engine
2426
+ * settles a signal-terminated run itself.
2038
2427
  */
2039
2428
  function settleChildStatus(invocation, def, settlement) {
2040
2429
  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`);
2430
+ if (!isEngineSpawned(settlement)) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus for a child result the engine did not produce — only the result of a ctx.spawn carries a child's status`);
2041
2431
  for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action)}\n`);
2042
2432
  settleVerbatimExitCode(invocation, settlement.exitCode);
2043
2433
  }
2044
- /** A session command that returned ok — including after the signal
2045
- * fired — shut down cleanly: exit 0, no presentation. In json mode the
2046
- * stream still terminates with exactly one result frame. */
2434
+ /** A session command that returned ok shut down cleanly: no
2435
+ * presentation, and exit 0 — unless a signal ended the run, which
2436
+ * settles 130/143 from the engine's record even though the shutdown
2437
+ * itself succeeded. In json mode the stream still terminates with
2438
+ * exactly one result frame. */
2047
2439
  function settleSessionCompleted(invocation) {
2048
2440
  const state = invocation.state;
2049
- state.settledExitCode = 0;
2441
+ const exitCode = runExitCode(invocation, 0);
2442
+ state.settledExitCode = exitCode;
2050
2443
  if (state.format !== "json") return;
2051
2444
  emitFrame(invocation, {
2052
2445
  kind: "result",
@@ -2054,7 +2447,7 @@ function settleSessionCompleted(invocation) {
2054
2447
  ok: true,
2055
2448
  commandId: state.commandId,
2056
2449
  result: null,
2057
- exitCode: 0,
2450
+ exitCode,
2058
2451
  diagnostics: [],
2059
2452
  nextActions: []
2060
2453
  },
@@ -2175,10 +2568,12 @@ var EngineImpl = class {
2175
2568
  root;
2176
2569
  now;
2177
2570
  delay;
2571
+ configSections;
2178
2572
  constructor(spec, now = () => /* @__PURE__ */ new Date(), delay = waitFor) {
2179
2573
  this.spec = spec;
2180
2574
  this.now = now;
2181
2575
  this.delay = delay;
2576
+ this.configSections = declaredConfigSections(spec);
2182
2577
  this.root = buildRoutes(spec, buildCommandTree(spec), "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
2183
2578
  }
2184
2579
  async execute(argv, runtime, hooks) {
@@ -2192,6 +2587,7 @@ var EngineImpl = class {
2192
2587
  confirmValues: [],
2193
2588
  interactive: defaultInteractive(runtime),
2194
2589
  colorEnabled: false,
2590
+ configPath: void 0,
2195
2591
  resolved: false,
2196
2592
  settledExitCode: void 0,
2197
2593
  usageErrorText: void 0,
@@ -2202,12 +2598,12 @@ var EngineImpl = class {
2202
2598
  snapshot: void 0,
2203
2599
  delegatedTerminal: void 0,
2204
2600
  activePrompts: 0,
2601
+ deliveredSignal: void 0,
2205
2602
  pendingForceExit: void 0,
2206
2603
  spawnCredential: void 0
2207
2604
  };
2208
2605
  const startedAtMs = this.now().getTime();
2209
2606
  const controller = new AbortController();
2210
- let signalDelivered = false;
2211
2607
  /** The engine neither aborts nor exits while a child owns the
2212
2608
  * terminal: it records, and the affordance replays on child exit,
2213
2609
  * so the engine always outlives the child. */
@@ -2216,11 +2612,11 @@ var EngineImpl = class {
2216
2612
  recordSignalDuringSpawn(state.delegatedTerminal, signal);
2217
2613
  return;
2218
2614
  }
2219
- if (signalDelivered) {
2615
+ if (state.deliveredSignal !== void 0) {
2220
2616
  runtime.exit(signal === "SIGTERM" ? 143 : 130);
2221
2617
  return;
2222
2618
  }
2223
- signalDelivered = true;
2619
+ state.deliveredSignal = signal;
2224
2620
  controller.abort(signal);
2225
2621
  };
2226
2622
  const unsubscribe = runtime.onSignal(deliverSignal);
@@ -2231,12 +2627,18 @@ var EngineImpl = class {
2231
2627
  delay: this.delay,
2232
2628
  state,
2233
2629
  signal: controller.signal,
2630
+ configSections: this.configSections,
2234
2631
  deliverSignal
2235
2632
  };
2236
- if (versionRequested(argv)) {
2633
+ if (versionFlagGiven(argv)) {
2237
2634
  unsubscribe();
2238
2635
  return settleVersion(this.spec, invocation);
2239
2636
  }
2637
+ if (configFlagGivenNoValue(argv)) {
2638
+ unsubscribe();
2639
+ settleErrored(invocation, configFlagGivenNoValueError());
2640
+ return 2;
2641
+ }
2240
2642
  const stricliProcess = {
2241
2643
  /** stricli writes only help text here. In json mode stdout carries
2242
2644
  * exactly the frame stream, so help prose goes to stderr instead. */
@@ -2304,7 +2706,7 @@ var EngineImpl = class {
2304
2706
  await this.executeServer(invocation, entry, rawFlags);
2305
2707
  return;
2306
2708
  }
2307
- if (entry.def.maySpawn && explicitFormat(state.argv) === "json") {
2709
+ if (entry.def.maySpawn && formatFlagGiven(state.argv) === "json") {
2308
2710
  state.format = "human";
2309
2711
  settleErrored(invocation, jsonUnsupportedError(entry.id));
2310
2712
  return;
@@ -2427,6 +2829,15 @@ var EngineImpl = class {
2427
2829
  }
2428
2830
  }
2429
2831
  };
2832
+ /** The closed set of config section names. Every mounted command
2833
+ * contributes the section it needs, whether it reaches the tree
2834
+ * through a command family or on its own — the shell mounts its own
2835
+ * commands with no family, and a section the CLI cannot name is a
2836
+ * section its own command could never read. Every other top-level key
2837
+ * in prisma.config.ts is reported by the config needs check. */
2838
+ function declaredConfigSections(spec) {
2839
+ return [...new Set([...spec.commandFamilies.map((commandFamily) => commandFamily.configSection?.name), ...Object.values(spec.commands).map((def) => def.needs.config?.name)].filter((name) => name !== void 0))];
2840
+ }
2430
2841
  /** A command that may hand the terminal to a child cannot frame its
2431
2842
  * output, so json is refused as soon as the command is known — before
2432
2843
  * the needs check and before anything runs. */
@@ -2439,13 +2850,6 @@ function jsonUnsupportedError(commandId) {
2439
2850
  }]
2440
2851
  });
2441
2852
  }
2442
- function versionRequested(argv) {
2443
- for (const argument of argv) {
2444
- if (argument === "--") return false;
2445
- if (argument === "--version") return true;
2446
- }
2447
- return false;
2448
- }
2449
2853
  function declaredFlags(def, rawFlags) {
2450
2854
  const flags = {};
2451
2855
  for (const key of Object.keys(def.args.flags)) flags[key] = rawFlags[key];
@@ -2491,12 +2895,15 @@ function claimedString(claims, name) {
2491
2895
  const value = claims?.[name];
2492
2896
  return typeof value === "string" && value.length > 0 ? value : void 0;
2493
2897
  }
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. */
2898
+ /**
2899
+ * The workspace a credential names. One derivation, because a token
2900
+ * says it one of two ways and every caller wants the same answer: an
2901
+ * OAuth token carries `workspace_id`, while a service token names its
2902
+ * workspace through `sub` and carries no `workspace_id` at all. Reading
2903
+ * only the claim was a second path that happened to work because
2904
+ * service tokens reached it by a different route — a split nothing
2905
+ * enforced.
2906
+ */
2500
2907
  function credentialWorkspaceId(token) {
2501
2908
  const claims = decodeTokenClaims(token);
2502
2909
  const fromClaim = claimedString(claims, "workspace_id");
@@ -2527,4 +2934,4 @@ function claimedIdentity(token) {
2527
2934
  };
2528
2935
  }
2529
2936
  //#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 };
2937
+ export { PRESENTED as _, CONFIG_FILE_NAME as a, positional as b, PRISMA_CONFIG_VERSION as c, authServiceError as d, credentialRejectedError as f, noSessionForWorkspaceError as g, emptyServiceTokenError as h, buildEngine as i, SERVICE_TOKEN_ENV_VAR as l, credentialsRequiredError as m, claimedIdentity as n, defineConfig as o, credentialWorkspaceMismatchError as p, credentialWorkspaceId as r, loadConfig as s, claimedExpiresAt as t, WORKSPACE_ID_ENV_VAR as u, exitWithChildStatus as v, flag as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/cli-engine",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "The execution engine of the unified Prisma CLI.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -48,7 +48,8 @@
48
48
  "dependencies": {
49
49
  "@clack/prompts": "1.5.0",
50
50
  "@prisma/management-api-sdk": "1.55.0",
51
- "@stricli/core": "1.3.0"
51
+ "@stricli/core": "1.3.0",
52
+ "c12": "3.3.4"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@repo/tsconfig": "workspace:8.0.0-rc.1",