@prisma/cli-engine 8.0.0-rc.1 → 8.0.0-rc.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.
@@ -57,6 +57,17 @@ const flag = {
57
57
  ...spec
58
58
  });
59
59
  },
60
+ /**
61
+ * A boolean the user can leave unsaid: `--flag`, `--no-flag`, or
62
+ * neither, which arrives as undefined. Use it when absence means
63
+ * something of its own — "ask me" rather than "no".
64
+ */
65
+ optionalBoolean(spec) {
66
+ return brandFlag({
67
+ type: "optionalBoolean",
68
+ ...spec
69
+ });
70
+ },
60
71
  enum(spec) {
61
72
  return brandFlag({
62
73
  type: "enum",
@@ -849,6 +860,26 @@ function buildManagementApiClient(invocation) {
849
860
  };
850
861
  } });
851
862
  }
863
+ /**
864
+ * Loads the SDK, surviving a Node ESM resolver fault observed in the
865
+ * wild: the resolver can return the package's un-realpathed pnpm
866
+ * symlink URL (instead of the .pnpm real path), from which the SDK's
867
+ * own 'openapi-fetch' import cannot resolve. The fault is
868
+ * state-dependent — two fstatSync calls at process start reliably
869
+ * provoke it, and a module-loader hook masks it — so nothing here can
870
+ * rule it out. The fallback resolves through CJS require, which
871
+ * realpaths, and imports the real location directly; it never fires
872
+ * when the normal import works.
873
+ */
874
+ async function importManagementApiSdk() {
875
+ try {
876
+ return await import("@prisma/management-api-sdk");
877
+ } catch {
878
+ const { createRequire } = await import("node:module");
879
+ const { pathToFileURL } = await import("node:url");
880
+ return await import(pathToFileURL(createRequire(import.meta.url).resolve("@prisma/management-api-sdk")).href);
881
+ }
882
+ }
852
883
  async function constructClient(invocation, debug, probe) {
853
884
  const manager = invocation.runtime.credentialManager;
854
885
  if (manager === void 0) throw credentialsRequiredError();
@@ -857,7 +888,7 @@ async function constructClient(invocation, debug, probe) {
857
888
  const config = invocation.runtime.managementApiClientConfig;
858
889
  if (config === void 0) throw new Error("@prisma/cli-engine: ctx.api requires Runtime.managementApiClientConfig when a credentialManager is wired");
859
890
  const storage = observedTokenStorage(await manager.activeCredentialStorage(), active, debug, probe);
860
- const { createManagementApiSdk } = await import("@prisma/management-api-sdk");
891
+ const { createManagementApiSdk } = await importManagementApiSdk();
861
892
  return {
862
893
  client: createManagementApiSdk({
863
894
  clientId: config.clientId,
@@ -1075,14 +1106,17 @@ function reservedConfigSectionName(name) {
1075
1106
  * top-level key names a config section, and the recognised section
1076
1107
  * names are exactly the ones the CLI's command families declare. Never
1077
1108
  * throws — bad section values are the section validator's problem, not
1078
- * defineConfig's.
1109
+ * definePrismaConfig's.
1079
1110
  */
1080
- function defineConfig(config) {
1111
+ function definePrismaConfig(config) {
1081
1112
  return Object.freeze({
1082
1113
  ...config,
1083
1114
  $prismaConfig: 1
1084
1115
  });
1085
1116
  }
1117
+ /** @deprecated Renamed to {@link definePrismaConfig}: every family's
1118
+ * config helper carries a unique name, so none needs an import alias. */
1119
+ const defineConfig = definePrismaConfig;
1086
1120
  function hasVersionMarker(value) {
1087
1121
  return typeof value === "object" && value !== null && typeof value[MARKER_KEY] === "number";
1088
1122
  }
@@ -1101,10 +1135,10 @@ function missingMarkerDiagnostic(path) {
1101
1135
  code: "CLI.CONFIG_MISSING_MARKER",
1102
1136
  severity: "error",
1103
1137
  summary: `${path} was not written for this version of the Prisma CLI, so it cannot be used.`,
1104
- 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.",
1138
+ why: "Configs for this CLI are created with definePrismaConfig, 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.",
1105
1139
  nextActions: [{
1106
1140
  kind: "user-choice",
1107
- label: "Migrate the file: wrap the exported object in defineConfig from @prisma/cli-engine and export the result as the default export."
1141
+ label: "Migrate the file: wrap the exported object in definePrismaConfig from @prisma/cli-engine and export the result as the default export."
1108
1142
  }],
1109
1143
  where: { path }
1110
1144
  };
@@ -1120,7 +1154,7 @@ function unsupportedVersionDiagnostic(path, found) {
1120
1154
  summary: `${path} declares config version ${found}, but this CLI supports only version 1.`,
1121
1155
  nextActions: [{
1122
1156
  kind: "user-choice",
1123
- label: "Regenerate the config with a defineConfig matching this CLI, or update the CLI to a version that supports the declared config version."
1157
+ label: "Regenerate the config with a definePrismaConfig matching this CLI, or update the CLI to a version that supports the declared config version."
1124
1158
  }],
1125
1159
  where: { path }
1126
1160
  };
@@ -1243,12 +1277,12 @@ async function loadConfig(cwd, configPath) {
1243
1277
  }
1244
1278
  //#endregion
1245
1279
  //#region src/execution/pre-parse-argv.ts
1246
- function flagTokens(argv) {
1280
+ function flagTokens$1(argv) {
1247
1281
  const terminator = argv.indexOf("--");
1248
1282
  return terminator === -1 ? argv : argv.slice(0, terminator);
1249
1283
  }
1250
1284
  function versionFlagGiven(argv) {
1251
- return flagTokens(argv).includes("--version");
1285
+ return flagTokens$1(argv).includes("--version");
1252
1286
  }
1253
1287
  /**
1254
1288
  * The one malformed `--config` shape the parser cannot see. stricli
@@ -1266,12 +1300,12 @@ function versionFlagGiven(argv) {
1266
1300
  * data, and `--` remains the way to pass it.
1267
1301
  */
1268
1302
  function configFlagGivenNoValue(argv) {
1269
- return flagTokens(argv).includes("--config=");
1303
+ return flagTokens$1(argv).includes("--config=");
1270
1304
  }
1271
1305
  /** The format requested by --json / --format / --format=<value>, if
1272
1306
  * any. */
1273
1307
  function formatFlagGiven(argv) {
1274
- const tokens = flagTokens(argv);
1308
+ const tokens = flagTokens$1(argv);
1275
1309
  for (const [index, token] of tokens.entries()) {
1276
1310
  if (token === "--json" || token === "--format=json") return "json";
1277
1311
  if (token === "--format=human") return "human";
@@ -1669,9 +1703,9 @@ const TONE_VERB = {
1669
1703
  "color-6": "green"
1670
1704
  };
1671
1705
  const COLORED = createColors({ useColor: true });
1672
- const PLAIN = createColors({ useColor: false });
1706
+ const PLAIN$1 = createColors({ useColor: false });
1673
1707
  function makePaint(colorEnabled) {
1674
- const colors = colorEnabled ? COLORED : PLAIN;
1708
+ const colors = colorEnabled ? COLORED : PLAIN$1;
1675
1709
  return (tone, text) => colors[TONE_VERB[tone]](text);
1676
1710
  }
1677
1711
  function renderText(text, paint) {
@@ -1755,7 +1789,7 @@ const STATUS_SYMBOL = {
1755
1789
  };
1756
1790
  const MASK = "********";
1757
1791
  const COLUMN_GAP = " ";
1758
- const RAIL = "│";
1792
+ const RAIL$1 = "│";
1759
1793
  const BRANCH = "├─";
1760
1794
  const LAST_BRANCH = "└─";
1761
1795
  const TRAILING_SPACES = / +$/;
@@ -1825,10 +1859,10 @@ function toned(text, tone) {
1825
1859
  function writeFields(rows, rail, paint, write) {
1826
1860
  const cells = rows.map((row) => ({
1827
1861
  label: toned(extend(row.label, ":"), "heading"),
1828
- value: row.sensitive === true ? MASK : row.value
1862
+ value: row.sensitive === true ? MASK : orPlaceholder(row.value)
1829
1863
  }));
1830
1864
  const width = Math.max(0, ...cells.map((cell) => textWidth(cell.label)));
1831
- const prefix = rail ? `${paint("structure", RAIL)}${COLUMN_GAP}` : "";
1865
+ const prefix = rail ? `${paint("structure", RAIL$1)}${COLUMN_GAP}` : "";
1832
1866
  for (const cell of cells) write(`${prefix}${renderText(padTo(cell.label, width), paint)}${COLUMN_GAP}${renderText(cell.value, paint)}`);
1833
1867
  }
1834
1868
  /**
@@ -1836,8 +1870,23 @@ function writeFields(rows, rail, paint, write) {
1836
1870
  * than the bytes so colour cannot shift a column. The last column is
1837
1871
  * never padded, so no line carries trailing whitespace.
1838
1872
  */
1873
+ /** One header convention for every table: plain-string headers are
1874
+ * normalized to sentence case, so casing is not a per-command choice. */
1875
+ function sentenceCase(text) {
1876
+ if (typeof text !== "string" || text === "") return text;
1877
+ return `${text[0].toUpperCase()}${text.slice(1)}`;
1878
+ }
1879
+ const PLACEHOLDER = "—";
1880
+ /** An absent value renders as a dim em dash rather than invented prose
1881
+ * ("none", "n/a") in data tone. */
1882
+ function orPlaceholder(cell) {
1883
+ return cell === "" || typeof cell !== "string" && textWidth(cell) === 0 ? [{
1884
+ text: PLACEHOLDER,
1885
+ tone: "placeholder"
1886
+ }] : cell;
1887
+ }
1839
1888
  function writeTable(columns, rows, paint, write) {
1840
- const all = [columns.map((column) => toned(column, "heading")), ...rows];
1889
+ const all = [columns.map((column) => toned(sentenceCase(column), "heading")), ...rows.map((row) => row.map(orPlaceholder))];
1841
1890
  const widths = [];
1842
1891
  for (const row of all) for (const [index, cell] of row.entries()) widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
1843
1892
  for (const row of all) write(row.map((cell, index) => renderText(index === row.length - 1 ? cell : padTo(cell, widths[index]), paint)).join(COLUMN_GAP).replace(TRAILING_SPACES, ""));
@@ -1848,7 +1897,7 @@ function writeBranches(nodes, prefix, paint, write) {
1848
1897
  for (const [index, node] of nodes.entries()) {
1849
1898
  const last = index === nodes.length - 1;
1850
1899
  write(`${prefix}${paint("structure", last ? LAST_BRANCH : BRANCH)} ${treeLabel(node, paint)}`);
1851
- const continuation = last ? " " : `${paint("structure", RAIL)}${COLUMN_GAP}`;
1900
+ const continuation = last ? " " : `${paint("structure", RAIL$1)}${COLUMN_GAP}`;
1852
1901
  writeBranches(node.children ?? [], `${prefix}${continuation}`, paint, write);
1853
1902
  }
1854
1903
  }
@@ -1863,21 +1912,27 @@ const DIAGNOSTIC_SYMBOL = {
1863
1912
  warn: "⚠",
1864
1913
  info: "ℹ"
1865
1914
  };
1866
- function writeDiagnostic(stream, diagnostic) {
1867
- stream.write(`${DIAGNOSTIC_SYMBOL[diagnostic.severity]} [${diagnostic.code}] ${diagnostic.summary}\n`);
1868
- if (diagnostic.why !== void 0) stream.write(` why: ${diagnostic.why}\n`);
1869
- for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action)}\n`);
1870
- if (diagnostic.docsUrl !== void 0) stream.write(` docs: ${diagnostic.docsUrl}\n`);
1915
+ const PLAIN = makePaint(false);
1916
+ function writeDiagnostic(stream, diagnostic, paint = PLAIN) {
1917
+ const glyph = paint(diagnostic.severity, DIAGNOSTIC_SYMBOL[diagnostic.severity]);
1918
+ const code = paint("muted", `[${diagnostic.code}]`);
1919
+ stream.write(`${glyph} ${code} ${diagnostic.summary}\n`);
1920
+ if (diagnostic.why !== void 0) stream.write(` ${paint("muted", `why: ${diagnostic.why}`)}\n`);
1921
+ for (const action of diagnostic.nextActions) stream.write(`${renderNextAction(action, paint)}\n`);
1922
+ if (diagnostic.docsUrl !== void 0) stream.write(` ${paint("muted", "docs:")} ${paint("link", diagnostic.docsUrl)}\n`);
1871
1923
  }
1872
1924
  /** `label` is required, so a mapper building an action out of a bare
1873
1925
  * command string — a legacy error's follow-up step, with no prose
1874
1926
  * beside it — has nothing to put in the label but the command itself.
1875
1927
  * Only the renderer sees both fields, so only it can tell they are the
1876
1928
  * same string and print it once. */
1877
- function renderNextAction(action) {
1929
+ function renderNextAction(action, paint = PLAIN) {
1878
1930
  const target = action.command ?? action.url;
1879
1931
  const repeatsTheLabel = target === void 0 || target === action.label;
1880
- return `→ ${action.label}${repeatsTheLabel ? "" : `: ${target}`}`;
1932
+ const arrow = paint("heading", "→");
1933
+ if (repeatsTheLabel) return `${arrow} ${action.command !== void 0 ? paint("identifier", action.label) : action.label}`;
1934
+ const painted = action.command !== void 0 ? paint("identifier", target) : paint("link", target);
1935
+ return `${arrow} ${action.label}: ${painted}`;
1881
1936
  }
1882
1937
  /** Populates docsUrl from the owning family's docsBaseUrl (base + code)
1883
1938
  * when the diagnostic does not carry its own — a per-raise docsUrl wins. */
@@ -1889,6 +1944,27 @@ function withDocsUrl(state, diagnostic) {
1889
1944
  docsUrl: `${base}${diagnostic.code}`
1890
1945
  };
1891
1946
  }
1947
+ const TRAILING_NEWLINE = /\n$/;
1948
+ function diagnosticSection(diagnostic, paint) {
1949
+ const lines = [];
1950
+ writeDiagnostic({ write: (text) => lines.push(...text.replace(TRAILING_NEWLINE, "").split("\n")) }, diagnostic, paint);
1951
+ return {
1952
+ lines,
1953
+ compact: lines.length === 1
1954
+ };
1955
+ }
1956
+ /** A blank line between sections wherever a multi-line one is involved,
1957
+ * so a card, a table and the next actions each read as their own
1958
+ * paragraph; adjacent compact sections keep hugging. */
1959
+ function writeSections(sections, stream) {
1960
+ let previous;
1961
+ for (const section of sections) {
1962
+ if (section.lines.length === 0) continue;
1963
+ if (previous !== void 0 && !(previous.compact && section.compact)) stream.write("\n");
1964
+ for (const line of section.lines) stream.write(`${line}\n`);
1965
+ previous = section;
1966
+ }
1967
+ }
1892
1968
  /** Channel discipline (operator ruling, 2026-08-09): human Blocks,
1893
1969
  * next-action lines, and diagnostics are presentation prose on stderr;
1894
1970
  * the materialized `stdout` presentation lines are the machine-usable
@@ -1896,10 +1972,21 @@ function withDocsUrl(state, diagnostic) {
1896
1972
  function renderCompletedHuman(invocation, presented) {
1897
1973
  const { runtime, state } = invocation;
1898
1974
  const paint = makePaint(state.colorEnabled);
1899
- for (const block of presented.presentation.human) renderBlock(block, paint, (line) => runtime.stderr.write(`${line}\n`));
1900
- for (const action of presented.presentation.next) runtime.stderr.write(`${renderNextAction(action)}\n`);
1901
- for (const diagnostic of presented.diagnostics) writeDiagnostic(runtime.stderr, withDocsUrl(state, diagnostic));
1902
- for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
1975
+ const sections = presented.presentation.human.map((block) => {
1976
+ const lines = [];
1977
+ renderBlock(block, paint, (line) => lines.push(line));
1978
+ return {
1979
+ lines,
1980
+ compact: block.kind === "summary"
1981
+ };
1982
+ });
1983
+ if (presented.presentation.next.length > 0) sections.push({
1984
+ lines: presented.presentation.next.map((action) => renderNextAction(action, paint)),
1985
+ compact: true
1986
+ });
1987
+ for (const diagnostic of presented.diagnostics) sections.push(diagnosticSection(withDocsUrl(state, diagnostic), paint));
1988
+ writeSections(sections, runtime.stderr);
1989
+ if (!(runtime.isTty.stdout && runtime.isTty.stderr && runtime.outputStreamsShareDevice !== false)) for (const line of presented.presentation.stdout) runtime.stdout.write(`${line}\n`);
1903
1990
  }
1904
1991
  const SEVERITY_RANK = {
1905
1992
  error: 0,
@@ -2131,7 +2218,7 @@ function writeSectionWarnings(invocation, diagnostics) {
2131
2218
  const state = invocation.state;
2132
2219
  for (const diagnostic of diagnostics) {
2133
2220
  if (SEVERITY_RANK[diagnostic.severity] > SEVERITY_RANK[state.logLevel]) continue;
2134
- writeDiagnostic(invocation.runtime.stderr, withDocsUrl(state, diagnostic));
2221
+ writeDiagnostic(invocation.runtime.stderr, withDocsUrl(state, diagnostic), makePaint(state.colorEnabled));
2135
2222
  }
2136
2223
  }
2137
2224
  function dependencyResolvable(specifier, cwd) {
@@ -2980,12 +3067,31 @@ function makeUi(colorEnabled, stderr) {
2980
3067
  };
2981
3068
  }
2982
3069
  /** Materializes ONLY the active format's presentation functions, at the
2983
- * return site: human → human + stdout + next; json → json + next. */
3070
+ * return site: human → human + stdout + next; json → json + next.
3071
+ *
3072
+ * `stdout` and `next` may be absent at runtime, so both are called with
3073
+ * `?.()`. `Presentations` requires all four, so no command compiled
3074
+ * against this engine can omit one — but `@prisma/orm-toolchain` is
3075
+ * built against engine `0.0.9`, where three of the four were optional,
3076
+ * and its published commands took that up: `migration list` declares
3077
+ * `human` and `json` and neither of the others. Calling them
3078
+ * unconditionally makes it exit 2 — `stdout` in human mode, `next` in
3079
+ * both.
3080
+ *
3081
+ * `json` is called unconditionally, and stays that way: a missing json
3082
+ * presentation is the defect this change removes, and every ORM command
3083
+ * already declares one.
3084
+ *
3085
+ * This is version skew in our own code, not a foreign contract. The fix
3086
+ * is in prisma/prisma: declare the missing presentations in the ORM
3087
+ * commands and build orm-toolchain against this engine, where the type
3088
+ * refuses to compile without them. Delete both `?.()` when that
3089
+ * version is pinned here. */
2984
3090
  function materializePresentation(state, ui, presentations) {
2985
3091
  if (state.format === "json") return {
2986
3092
  human: [],
2987
3093
  stdout: [],
2988
- json: presentations.json?.(),
3094
+ json: presentations.json(),
2989
3095
  next: presentations.next?.() ?? []
2990
3096
  };
2991
3097
  return {
@@ -3028,6 +3134,7 @@ function makeContext(invocation, def, config, capabilities) {
3028
3134
  signal: invocation.signal,
3029
3135
  cwd: invocation.runtime.cwd,
3030
3136
  env: invocation.runtime.env,
3137
+ host: invocation.runtime.host,
3031
3138
  isCI: resolveIsCI(invocation.runtime),
3032
3139
  requireDependency: async (specifier) => {
3033
3140
  if (dependencyResolvable(specifier, invocation.runtime.cwd)) return okVoid();
@@ -3158,6 +3265,12 @@ function stricliFlagParameter(spec) {
3158
3265
  brief: spec.brief,
3159
3266
  default: false
3160
3267
  };
3268
+ case "optionalBoolean": return {
3269
+ kind: "boolean",
3270
+ brief: spec.brief,
3271
+ optional: true,
3272
+ withNegated: true
3273
+ };
3161
3274
  case "enum": return {
3162
3275
  kind: "enum",
3163
3276
  brief: spec.brief,
@@ -3322,6 +3435,315 @@ function usageErrorCode(stricliExitCode) {
3322
3435
  if (stricliExitCode === -4) return "CLI.INVALID_ARGUMENTS";
3323
3436
  }
3324
3437
  //#endregion
3438
+ //#region src/execution/help.ts
3439
+ /**
3440
+ * Engine-rendered help: the command tree drawn with the same tones the
3441
+ * block renderer uses, so help is themed like every other surface.
3442
+ * stricli's text_en renderer is never consulted — root and group help
3443
+ * list `name brief` rows, and full signatures appear only on the leaf
3444
+ * that owns them.
3445
+ */
3446
+ const RAIL = "│";
3447
+ const GAP = " ";
3448
+ const WRAP_WIDTH = 76;
3449
+ function flagTokens(argv) {
3450
+ const terminator = argv.indexOf("--");
3451
+ return terminator === -1 ? argv : argv.slice(0, terminator);
3452
+ }
3453
+ function helpFlagGiven(argv) {
3454
+ return flagTokens(argv).some((token) => token === "-h" || token === "--help" || token === "--help-all");
3455
+ }
3456
+ /** The colour decision available before the shared flags are parsed,
3457
+ * read from raw argv: explicit flag, then NO_COLOR, then the TTY of
3458
+ * the stream about to be written. Help and pre-mount failures both
3459
+ * render through this; applySharedFlags re-resolves once a command
3460
+ * actually parses. */
3461
+ function preParseColorEnabled(argv, runtime, stream) {
3462
+ const tokens = flagTokens(argv);
3463
+ if (tokens.includes("--no-color")) return false;
3464
+ if (tokens.includes("--color")) return true;
3465
+ if (runtime.env.NO_COLOR !== void 0) return false;
3466
+ return runtime.isTty[stream];
3467
+ }
3468
+ /** The command path the user asked help for: the leading non-flag
3469
+ * tokens, resolved as far as the tree recognizes them. */
3470
+ function helpPath(argv) {
3471
+ const segments = [];
3472
+ for (const token of argv) {
3473
+ if (token.startsWith("-")) break;
3474
+ segments.push(token);
3475
+ }
3476
+ return segments;
3477
+ }
3478
+ /** Walks as far as the segments stay recognized; help for `project
3479
+ * frobnicate` is project's help, not a dead end. */
3480
+ function resolveTarget(root, segments) {
3481
+ let node = root;
3482
+ const path = [];
3483
+ for (const segment of segments) {
3484
+ const entry = node.commands.get(segment);
3485
+ if (entry !== void 0) return {
3486
+ target: {
3487
+ kind: "leaf",
3488
+ entry
3489
+ },
3490
+ path: [...path, segment]
3491
+ };
3492
+ const child = node.children.get(segment);
3493
+ if (child === void 0) break;
3494
+ node = child;
3495
+ path.push(segment);
3496
+ }
3497
+ return {
3498
+ target: {
3499
+ kind: "node",
3500
+ node
3501
+ },
3502
+ path
3503
+ };
3504
+ }
3505
+ /** A BARE group invocation (`prisma-cli project`, or no argv at all)
3506
+ * is a help request; anything carrying flags or extra tokens is not —
3507
+ * `cli --unknown` and `cli project --frobnicate` must reach routing
3508
+ * and usage validation, not exit 0 with a help card. A bare leaf is a
3509
+ * command run and is left alone. */
3510
+ function bareGroupInvocation(root, argv) {
3511
+ const segments = helpPath(argv);
3512
+ if (segments.length !== argv.length) return false;
3513
+ if (segments.length === 0) return true;
3514
+ const { target, path } = resolveTarget(root, segments);
3515
+ return target.kind === "node" && path.length === segments.length;
3516
+ }
3517
+ function renderHelp(spec, root, argv, colorEnabled, out) {
3518
+ const paint = makePaint(colorEnabled);
3519
+ const { target, path } = resolveTarget(root, helpPath(argv));
3520
+ const lines = [];
3521
+ if (target.kind === "leaf") renderLeafHelp(spec, target.entry, path, paint, lines);
3522
+ else renderNodeHelp(spec, target.node, path, paint, lines);
3523
+ out.write(`${lines.join("\n")}\n`);
3524
+ }
3525
+ /** `prisma-cli project → Manage and inspect your Prisma projects` */
3526
+ function header(spec, path, tagline, paint) {
3527
+ const name = paint("emphasis", [spec.name, ...path].join(" "));
3528
+ if (tagline === void 0 || tagline === "") return name;
3529
+ return `${name} ${paint("muted", `→ ${tagline}`)}`;
3530
+ }
3531
+ function rail(paint, rest = "") {
3532
+ return rest === "" ? paint("structure", RAIL) : `${paint("structure", RAIL)}${GAP}${rest}`;
3533
+ }
3534
+ function sectionLabel(paint, label) {
3535
+ return rail(paint, paint("muted", label));
3536
+ }
3537
+ /** Two-column rows under the rail: name in the accent, brief plain. */
3538
+ function railRows(rows, paint, lines) {
3539
+ const width = Math.max(0, ...rows.map((row) => textWidth(row.name)));
3540
+ for (const row of rows) {
3541
+ const pad = " ".repeat(width - textWidth(row.name));
3542
+ const suffix = row.suffix === void 0 || row.suffix === "" ? "" : ` ${paint("muted", row.suffix)}`;
3543
+ lines.push(rail(paint, `${paint("identifier", row.name)}${pad}${GAP}${row.brief}${suffix}`));
3544
+ }
3545
+ }
3546
+ function wrap(text, width) {
3547
+ const lines = [];
3548
+ for (const paragraph of text.split("\n")) {
3549
+ if (paragraph === "") {
3550
+ lines.push("");
3551
+ continue;
3552
+ }
3553
+ let line = "";
3554
+ for (const word of paragraph.split(" ")) if (line !== "" && line.length + 1 + word.length > width) {
3555
+ lines.push(line);
3556
+ line = word;
3557
+ } else line = line === "" ? word : `${line} ${word}`;
3558
+ if (line !== "") lines.push(line);
3559
+ }
3560
+ return lines;
3561
+ }
3562
+ function proseLines(text, paint, lines, tone = "plain") {
3563
+ for (const line of wrap(text, WRAP_WIDTH)) lines.push(rail(paint, tone === "muted" ? paint("muted", line) : line));
3564
+ }
3565
+ function exampleLines(examples, cliName, paint, lines) {
3566
+ if (examples.length === 0) return;
3567
+ lines.push(rail(paint));
3568
+ lines.push(sectionLabel(paint, "Examples"));
3569
+ for (const example of examples) lines.push(rail(paint, `${GAP}${paint("muted", "$")} ${resolveExample(example, cliName)}`));
3570
+ }
3571
+ function docsLine(url, paint, lines) {
3572
+ if (url === void 0) return;
3573
+ lines.push(rail(paint));
3574
+ lines.push(rail(paint, `${paint("muted", "Docs")}${GAP}${paint("link", url)}`));
3575
+ }
3576
+ /** `--interactive/--no-interactive`, `-q, --quiet`, `--config <path>` —
3577
+ * one spelling rule for shared and declared flags alike. */
3578
+ function flagLabel(key, spec) {
3579
+ const kebab = kebabCase(key);
3580
+ return `${spec.alias === void 0 ? " " : `-${spec.alias},`} --${kebab}${spec.withNegated === true ? `/--no-${kebab}` : ""}${spec.placeholder === void 0 ? "" : ` <${spec.placeholder}>`}${spec.variadic === true ? "..." : ""}`;
3581
+ }
3582
+ function sharedFlagRows() {
3583
+ const aliasByKey = new Map(Object.entries(SHARED_ALIASES).map(([alias, key]) => [key, alias]));
3584
+ return [
3585
+ ...Object.entries(SHARED_FLAG_PARAMETERS).map(([key, spec]) => {
3586
+ const record = spec;
3587
+ return {
3588
+ name: flagLabel(key, {
3589
+ ...record,
3590
+ alias: aliasByKey.get(key)
3591
+ }),
3592
+ brief: record.brief,
3593
+ suffix: record.values === void 0 ? void 0 : record.values.join("|")
3594
+ };
3595
+ }),
3596
+ {
3597
+ name: `-h, --help`,
3598
+ brief: "Print help for a command"
3599
+ },
3600
+ {
3601
+ name: ` --version`,
3602
+ brief: "Print the CLI version and exit"
3603
+ }
3604
+ ];
3605
+ }
3606
+ function declaredFlagRows(def) {
3607
+ return Object.entries(def.args.flags).map(([key, spec]) => {
3608
+ const runtime = flagRuntime(spec);
3609
+ return {
3610
+ name: flagLabel(key, {
3611
+ alias: runtime.alias,
3612
+ placeholder: runtime.type === "boolean" || runtime.type === "optionalBoolean" ? void 0 : runtime.placeholder ?? "value",
3613
+ withNegated: runtime.type === "optionalBoolean",
3614
+ variadic: runtime.type === "repeated"
3615
+ }),
3616
+ brief: runtime.brief,
3617
+ suffix: flagSuffix(runtime)
3618
+ };
3619
+ });
3620
+ }
3621
+ function flagSuffix(runtime) {
3622
+ const parts = [];
3623
+ if (runtime.values !== void 0 && runtime.values.length > 0) parts.push(runtime.values.join("|"));
3624
+ if (runtime.type === "requiredString") parts.push("required");
3625
+ if (runtime.default !== void 0) parts.push(`default: ${String(runtime.default)}`);
3626
+ return parts.length === 0 ? void 0 : `(${parts.join("; ")})`;
3627
+ }
3628
+ function positionalUsage(def) {
3629
+ return Object.values(def.args.positionals).map((spec) => {
3630
+ const runtime = positionalRuntime(spec);
3631
+ if (runtime.type === "optionalString") return `[${runtime.placeholder}]`;
3632
+ if (runtime.type === "variadic") return `[${runtime.placeholder}...]`;
3633
+ return `<${runtime.placeholder}>`;
3634
+ }).join(" ");
3635
+ }
3636
+ function requiredFlagUsage(def) {
3637
+ return Object.entries(def.args.flags).flatMap(([key, spec]) => {
3638
+ const runtime = flagRuntime(spec);
3639
+ return runtime.type === "requiredString" ? [`--${kebabCase(key)} <${runtime.placeholder ?? "value"}>`] : [];
3640
+ }).join(" ");
3641
+ }
3642
+ /** Mount order, not map-partition order: a leaf and a group list in
3643
+ * the order their first command was mounted. */
3644
+ function nodeRows(spec, node, path) {
3645
+ const groupPath = path.join(" ");
3646
+ const depth = path.length;
3647
+ const seen = /* @__PURE__ */ new Set();
3648
+ const rows = [];
3649
+ for (const mounted of Object.keys(spec.commands)) {
3650
+ const segments = mounted.split(" ");
3651
+ if (segments.length <= depth || segments.slice(0, depth).join(" ") !== groupPath) continue;
3652
+ const name = segments[depth];
3653
+ if (seen.has(name)) continue;
3654
+ seen.add(name);
3655
+ const entry = node.commands.get(name);
3656
+ if (entry !== void 0) rows.push({
3657
+ name: usageName(name, entry.def),
3658
+ brief: entry.def.help.summary
3659
+ });
3660
+ else if (node.children.has(name)) {
3661
+ const childPath = depth === 0 ? name : `${groupPath} ${name}`;
3662
+ rows.push({
3663
+ name,
3664
+ brief: spec.groups[childPath]?.brief ?? ""
3665
+ });
3666
+ }
3667
+ }
3668
+ return rows;
3669
+ }
3670
+ function renderNodeHelp(spec, node, path, paint, lines) {
3671
+ const atRoot = path.length === 0;
3672
+ const groupPath = path.join(" ");
3673
+ const tagline = atRoot ? spec.help?.tagline : spec.groups[groupPath]?.brief;
3674
+ lines.push(header(spec, path, tagline, paint));
3675
+ lines.push("");
3676
+ railRows(nodeRows(spec, node, path), paint, lines);
3677
+ const description = atRoot ? spec.help?.description : spec.groups[groupPath]?.description;
3678
+ if (description !== void 0) {
3679
+ lines.push(rail(paint));
3680
+ proseLines(description, paint, lines);
3681
+ }
3682
+ if (atRoot) {
3683
+ lines.push(rail(paint));
3684
+ lines.push(sectionLabel(paint, "Global options"));
3685
+ railRows(sharedFlagRows(), paint, lines);
3686
+ exampleLines(spec.help?.examples ?? [], spec.name, paint, lines);
3687
+ docsLine(spec.help?.docsUrl, paint, lines);
3688
+ } else {
3689
+ lines.push(rail(paint));
3690
+ lines.push(rail(paint, paint("muted", `Run '${spec.name} ${groupPath} <command> --help' for details on a command.`)));
3691
+ }
3692
+ lines.push("");
3693
+ }
3694
+ /** `link [id-or-name]` — the row a group lists for a leaf: name plus
3695
+ * positional shape, briefs carry the rest. */
3696
+ function usageName(name, def) {
3697
+ const positionals = positionalUsage(def);
3698
+ return positionals === "" ? name : `${name} ${positionals}`;
3699
+ }
3700
+ function renderLeafHelp(spec, entry, path, paint, lines) {
3701
+ const def = entry.def;
3702
+ lines.push(header(spec, path, def.help.summary, paint));
3703
+ lines.push("");
3704
+ const usageParts = [
3705
+ spec.name,
3706
+ ...path,
3707
+ requiredFlagUsage(def),
3708
+ "[options]",
3709
+ positionalUsage(def)
3710
+ ].filter((part) => part !== "");
3711
+ lines.push(sectionLabel(paint, "Usage"));
3712
+ lines.push(rail(paint, `${GAP}${paint("muted", "$")} ${paint("emphasis", usageParts.join(" "))}`));
3713
+ if (def.help.description !== void 0) {
3714
+ lines.push(rail(paint));
3715
+ proseLines(def.help.description, paint, lines);
3716
+ }
3717
+ if (def.maySpawn) {
3718
+ lines.push(rail(paint));
3719
+ lines.push(rail(paint, paint("muted", NO_JSON_NOTE)));
3720
+ }
3721
+ const positionalEntries = Object.values(def.args.positionals).map((spec) => positionalRuntime(spec));
3722
+ if (positionalEntries.length > 0) {
3723
+ lines.push(rail(paint));
3724
+ lines.push(sectionLabel(paint, "Arguments"));
3725
+ railRows(positionalEntries.map((runtime) => ({
3726
+ name: runtime.placeholder,
3727
+ brief: runtime.brief,
3728
+ suffix: runtime.type === "optionalString" ? "(optional)" : void 0
3729
+ })), paint, lines);
3730
+ }
3731
+ const flagRows = declaredFlagRows(def);
3732
+ if (flagRows.length > 0) {
3733
+ lines.push(rail(paint));
3734
+ lines.push(sectionLabel(paint, "Options"));
3735
+ railRows(flagRows, paint, lines);
3736
+ }
3737
+ if (def.kind !== "server-command") {
3738
+ const sharedNames = [...Object.keys(SHARED_FLAG_PARAMETERS).map((key) => `--${kebabCase(key)}`)].join(", ");
3739
+ lines.push(rail(paint));
3740
+ proseLines(`Global options also apply: ${sharedNames}. Run '${spec.name} --help' for details.`, paint, lines, "muted");
3741
+ }
3742
+ exampleLines(def.help.examples, spec.name, paint, lines);
3743
+ docsLine(entry.docsBaseUrl, paint, lines);
3744
+ lines.push("");
3745
+ }
3746
+ //#endregion
3325
3747
  //#region src/execution/settlement.ts
3326
3748
  function undocumentedExitCode(def, exitCode) {
3327
3749
  if (exitCode === 0) return;
@@ -3348,7 +3770,7 @@ function settleCompleted(invocation, def, presented) {
3348
3770
  envelope: {
3349
3771
  ok: true,
3350
3772
  commandId: state.commandId,
3351
- result: presented.presentation.json === void 0 ? presented.data : presented.presentation.json,
3773
+ result: presented.presentation.json,
3352
3774
  exitCode,
3353
3775
  diagnostics: presented.diagnostics.map((diagnostic) => withDocsUrl(state, diagnostic)),
3354
3776
  nextActions: presented.presentation.next
@@ -3463,7 +3885,7 @@ function settleChildStatus(invocation, def, settlement) {
3463
3885
  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`);
3464
3886
  const child = invocation.state.lastChild;
3465
3887
  if (child === void 0) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without a child having run — that settlement reports the status of a child ctx.spawn started, and this run started none`);
3466
- if (child.signal === null) for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action)}\n`);
3888
+ if (child.signal === null) for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action, makePaint(invocation.state.colorEnabled))}\n`);
3467
3889
  settleVerbatimExitCode(invocation, childExitCode(child));
3468
3890
  }
3469
3891
  /** A session command that returned ok shut down cleanly: no
@@ -3522,9 +3944,8 @@ function emitErrored(invocation, raw) {
3522
3944
  });
3523
3945
  return;
3524
3946
  }
3525
- const stderr = invocation.runtime.stderr;
3526
- writeDiagnostic(stderr, envelope.error);
3527
- for (const diagnostic of envelope.diagnostics) writeDiagnostic(stderr, diagnostic);
3947
+ const paint = makePaint(invocation.state.colorEnabled);
3948
+ writeSections([envelope.error, ...envelope.diagnostics].map((diagnostic) => diagnosticSection(diagnostic, paint)), invocation.runtime.stderr);
3528
3949
  }
3529
3950
  /** `--version` prints createCli's version and exits 0. In json mode the
3530
3951
  * version travels as the run's single result frame. */
@@ -3601,21 +4022,63 @@ function settleUnhandled(spec, invocation, stricliExitCode) {
3601
4022
  const full = captured.length > 0 ? captured : "The command failed unexpectedly";
3602
4023
  const summary = firstLine(full);
3603
4024
  const remainder = full.slice(full.indexOf("\n") + 1).trim();
4025
+ const code = usageErrorCode(raw) ?? "CLI.INTERNAL_ERROR";
4026
+ const nextActions = code === "CLI.UNKNOWN_COMMAND" ? unknownCommandActions(spec, state) : [];
3604
4027
  emitErrored(invocation, {
3605
4028
  ok: false,
3606
4029
  commandId: segments.join("."),
3607
4030
  error: {
3608
- code: usageErrorCode(raw) ?? "CLI.INTERNAL_ERROR",
4031
+ code,
3609
4032
  severity: "error",
3610
4033
  summary,
3611
4034
  ...usage && full.includes("\n") && remainder.length > 0 ? { why: remainder } : {},
3612
- nextActions: []
4035
+ nextActions
3613
4036
  },
3614
4037
  diagnostics: [],
3615
- nextActions: []
4038
+ nextActions
3616
4039
  });
3617
4040
  return usage ? 2 : 1;
3618
4041
  }
4042
+ function editDistance(a, b) {
4043
+ const rows = a.length + 1;
4044
+ const cols = b.length + 1;
4045
+ const d = Array.from({ length: rows * cols }, () => 0);
4046
+ for (let i = 0; i < rows; i += 1) d[i * cols] = i;
4047
+ for (let j = 0; j < cols; j += 1) d[j] = j;
4048
+ for (let i = 1; i < rows; i += 1) for (let j = 1; j < cols; j += 1) {
4049
+ const substitution = a[i - 1] === b[j - 1] ? 0 : 1;
4050
+ d[i * cols + j] = Math.min(d[(i - 1) * cols + j] + 1, d[i * cols + j - 1] + 1, d[(i - 1) * cols + j - 1] + substitution);
4051
+ }
4052
+ return d[rows * cols - 1];
4053
+ }
4054
+ /** A misspelling is close (edit distance ≤ 2, and short paths tighter);
4055
+ * anything further is not a suggestion worth making. Every unknown
4056
+ * command at least learns where the command list is. */
4057
+ function unknownCommandActions(spec, state) {
4058
+ const attempted = [];
4059
+ for (const token of state.argv) {
4060
+ if (token.startsWith("-")) break;
4061
+ attempted.push(token);
4062
+ }
4063
+ const typed = attempted.join(" ");
4064
+ const candidates = new Set(Object.keys(spec.commands));
4065
+ for (const path of Object.keys(spec.commands)) {
4066
+ const segments = path.split(" ");
4067
+ for (let depth = 1; depth < segments.length; depth += 1) candidates.add(segments.slice(0, depth).join(" "));
4068
+ }
4069
+ return [...[...candidates].map((path) => ({
4070
+ path,
4071
+ distance: editDistance(typed, path)
4072
+ })).filter(({ path, distance }) => distance <= Math.max(path.length >= 8 ? 3 : 1, Math.min(2, path.length - 1))).sort((a, b) => a.distance - b.distance).slice(0, 3).map(({ path }) => ({
4073
+ kind: "run-command",
4074
+ label: "Did you mean",
4075
+ command: `${spec.name} ${path}`
4076
+ })), {
4077
+ kind: "run-command",
4078
+ label: "List every command",
4079
+ command: `${spec.name} --help`
4080
+ }];
4081
+ }
3619
4082
  //#endregion
3620
4083
  //#region src/execution/engine.ts
3621
4084
  function buildEngine(spec, options) {
@@ -3637,6 +4100,7 @@ function waitFor(ms, signal) {
3637
4100
  }
3638
4101
  var EngineImpl = class {
3639
4102
  spec;
4103
+ tree;
3640
4104
  root;
3641
4105
  redirects;
3642
4106
  now;
@@ -3647,20 +4111,25 @@ var EngineImpl = class {
3647
4111
  this.now = now;
3648
4112
  this.delay = delay;
3649
4113
  this.configSections = declaredConfigSections(spec);
3650
- this.root = buildRoutes(spec, buildCommandTree(spec), "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
4114
+ this.tree = buildCommandTree(spec);
4115
+ this.root = buildRoutes(spec, this.tree, "", (invocation, entry, flags, values) => this.executeMounted(invocation, entry, flags, values));
3651
4116
  this.redirects = buildRedirectTable(spec);
3652
4117
  }
3653
4118
  async execute(argv, runtime, hooks) {
4119
+ const format = sniffFormat(argv, runtime);
3654
4120
  const state = {
3655
4121
  commandId: "",
3656
4122
  docsBaseUrl: void 0,
3657
4123
  prefix: [],
3658
- format: sniffFormat(argv, runtime),
4124
+ format,
3659
4125
  logLevel: "info",
3660
4126
  yes: false,
3661
4127
  confirmValues: [],
3662
4128
  interactive: defaultInteractive(runtime),
3663
- colorEnabled: false,
4129
+ /** Pre-parse resolution so a run that never mounts a command — an
4130
+ * unknown command, a parse failure — still colours its
4131
+ * diagnostics; applySharedFlags re-resolves after parsing. */
4132
+ colorEnabled: preParseColorEnabled(argv, runtime, "stderr"),
3664
4133
  configPath: void 0,
3665
4134
  resolved: false,
3666
4135
  settledExitCode: void 0,
@@ -3716,6 +4185,15 @@ var EngineImpl = class {
3716
4185
  settleErrored(invocation, configFlagGivenNoValueError());
3717
4186
  return 2;
3718
4187
  }
4188
+ if (helpFlagGiven(argv) || bareGroupInvocation(this.tree, argv)) {
4189
+ unsubscribe();
4190
+ /** Help prose follows stricli's channel rule: stdout in human
4191
+ * mode, stderr in json mode so stdout stays a clean frame
4192
+ * stream. Never fires telemetry, like --version. */
4193
+ const stream = format === "human" ? runtime.stdout : runtime.stderr;
4194
+ renderHelp(this.spec, this.tree, argv, preParseColorEnabled(argv, runtime, format === "human" ? "stdout" : "stderr"), stream);
4195
+ return 0;
4196
+ }
3719
4197
  const stricliProcess = {
3720
4198
  /** stricli writes only help text here. In json mode stdout carries
3721
4199
  * exactly the frame stream, so help prose goes to stderr instead. */
@@ -4080,4 +4558,4 @@ function claimedIdentity(token) {
4080
4558
  };
4081
4559
  }
4082
4560
  //#endregion
4083
- export { flag as C, exitWithChildStatus as S, PRESENTED as _, CONFIG_FILE_NAME as a, writeUserConfig 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, readUserConfig as v, positional as w, resolveGating as x, userConfigPath as y };
4561
+ export { exitWithChildStatus as C, resolveGating as S, positional as T, noSessionForWorkspaceError as _, CONFIG_FILE_NAME as a, userConfigPath as b, loadConfig as c, WORKSPACE_ID_ENV_VAR as d, authServiceError as f, emptyServiceTokenError as g, credentialsRequiredError as h, buildEngine as i, PRISMA_CONFIG_VERSION as l, credentialWorkspaceMismatchError as m, claimedIdentity as n, defineConfig as o, credentialRejectedError as p, credentialWorkspaceId as r, definePrismaConfig as s, claimedExpiresAt as t, SERVICE_TOKEN_ENV_VAR as u, PRESENTED as v, flag as w, writeUserConfig as x, readUserConfig as y };