@prisma/cli-engine 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,8 @@ import { createRequire } from "node:module";
3
3
  import { Buffer } from "node:buffer";
4
4
  import { FlagNotFoundError, buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
5
5
  import { randomUUID } from "node:crypto";
6
- import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
7
- import { dirname, join, resolve } from "node:path";
6
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
7
+ import { dirname, isAbsolute, join, resolve } from "node:path";
8
8
  import { detect } from "package-manager-detector/detect";
9
9
  import { fileURLToPath, pathToFileURL } from "node:url";
10
10
  import { createColors } from "colorette";
@@ -1477,7 +1477,7 @@ function endpointVerdict(message) {
1477
1477
  //#endregion
1478
1478
  //#region src/runtime.ts
1479
1479
  /**
1480
- * The config contract version defineConfig writes as the structural
1480
+ * The config contract version definePrismaConfig writes as the structural
1481
1481
  * `$prismaConfig` marker; the loader checks it before interpreting
1482
1482
  * anything.
1483
1483
  */
@@ -1485,33 +1485,48 @@ const PRISMA_CONFIG_VERSION = 1;
1485
1485
  //#endregion
1486
1486
  //#region src/config-loader.ts
1487
1487
  /**
1488
- * The prisma.config.ts loader behind Runtime.loadConfig: resolve the
1489
- * file (the one `--config` named, otherwise prisma.config.ts in cwd —
1490
- * cwd only, no walking up), evaluate it, check the defineConfig version
1491
- * marker, and produce LoadedConfig.
1488
+ * The prisma.config.ts loader behind Runtime.loadConfig: resolve an
1489
+ * ordered chain of config files, evaluate each, check every one for the
1490
+ * definePrismaConfig version marker, and produce LoadedConfig.
1491
+ *
1492
+ * Without `--config`, discovery starts at cwd and walks upward
1493
+ * collecting every prisma.config.ts, stopping at the repository
1494
+ * boundary: the first directory containing `.git`. With `--config`,
1495
+ * the named file is the first chain link and discovery resumes
1496
+ * strictly above its directory — a prisma.config.ts beside the named
1497
+ * file is never collected. No `.git` at or above the anchor means
1498
+ * the anchor directory only — every file on the chain is executed
1499
+ * TypeScript, and nothing outside the repository runs without explicit
1500
+ * consent. A file may end collection itself with `parent: false`, or
1501
+ * name its parent explicitly with `parent: "path"` (resolved against
1502
+ * the declaring file's directory); an explicit parent may cross the
1503
+ * repository boundary — naming it is the consent — and the chain is
1504
+ * cycle-checked. After an explicit link, automatic discovery resumes
1505
+ * from the parent file's own directory.
1492
1506
  *
1493
1507
  * Which section names a CLI recognises is not this module's business:
1494
- * it hands back every top-level key the file had, and the engine — not
1508
+ * it hands back every top-level key each file had, and the engine — not
1495
1509
  * a Runtime member a host can replace — checks them against the
1496
1510
  * sections the mounted commands declare.
1497
1511
  *
1498
- * Absence of an undiscovered file is not an error: section validators
1499
- * own absence, so no prisma.config.ts in cwd yields no sections and no
1500
- * diagnostics.
1512
+ * Finding no file is not an error: section validators own absence, so
1513
+ * a chain with no files yields no sections and no diagnostics.
1501
1514
  * Absence of a file the user NAMED with --config is an error — they
1502
1515
  * said which file to read and it was not there. An evaluated file
1503
1516
  * WITHOUT the marker (a classic Prisma 7 config, which uses the same
1504
- * filename) fails early with one typed diagnostic — the loader never
1505
- * partially interprets an unmarked file, and never guesses.
1517
+ * filename) fails early with one typed diagnostic naming that file —
1518
+ * the loader never partially interprets an unmarked file, and never
1519
+ * guesses. A broken file anywhere on the chain fails resolution.
1506
1520
  *
1507
1521
  * Evaluation goes through c12, the same loader prisma/prisma and
1508
1522
  * prisma/composer use, because the shipped CLI runs on ordinary Node,
1509
1523
  * which cannot import a .ts file. c12 transpiles it with jiti first.
1510
1524
  * Every c12 feature beyond "evaluate this one file" is switched off
1511
- * below so discovery and merging stay exactly as they were.
1525
+ * below — chain discovery is this loader's, never c12's.
1512
1526
  */
1513
1527
  const CONFIG_FILE_NAME = "prisma.config.ts";
1514
1528
  const MARKER_KEY = "$prismaConfig";
1529
+ const PARENT_KEY = "parent";
1515
1530
  /**
1516
1531
  * Top-level keys the config file format keeps for itself, so no
1517
1532
  * section may be named one of them; buildCommandTree rejects the
@@ -1520,19 +1535,21 @@ const MARKER_KEY = "$prismaConfig";
1520
1535
  * `$`-prefixed keys are metadata: `$prismaConfig` is the version
1521
1536
  * marker, and config loaders read `$env`, `$<NODE_ENV>` and `$meta` —
1522
1537
  * c12 deletes `$meta` from the config object whatever else it is told.
1538
+ * `parent` is the engine's chain directive: the loader reads it to
1539
+ * follow or end the chain and strips it from the sections, like the
1540
+ * marker.
1523
1541
  * `extends` is the key config loaders take as "merge another file into
1524
1542
  * this one". This loader switches that off (`extend: false`), so a key
1525
1543
  * by that name does reach the config object. It stays reserved anyway:
1526
- * the file format has no layering of its own, `extends` is the name it
1527
- * would want if it gained some, and a section called `extends` would
1528
- * disappear the moment anything switched merging back on.
1544
+ * `parent` is this format's layering, and a section called `extends`
1545
+ * would disappear the moment anything switched c12's merging back on.
1529
1546
  *
1530
1547
  * `__proto__` is reserved for the reason `$meta` is: c12 merges layers
1531
1548
  * with defu, which drops the key rather than let a config file reach an
1532
1549
  * object's prototype, so a section by that name could never be read.
1533
1550
  */
1534
1551
  function reservedConfigSectionName(name) {
1535
- return name === "extends" || name === "__proto__" || name.startsWith("$");
1552
+ return name === "extends" || name === PARENT_KEY || name === "__proto__" || name.startsWith("$");
1536
1553
  }
1537
1554
  /**
1538
1555
  * Attaches the version marker to a prisma.config.ts export. Each
@@ -1547,16 +1564,12 @@ function definePrismaConfig(config) {
1547
1564
  $prismaConfig: 1
1548
1565
  });
1549
1566
  }
1550
- /** @deprecated Renamed to {@link definePrismaConfig}: every family's
1551
- * config helper carries a unique name, so none needs an import alias. */
1552
- const defineConfig = definePrismaConfig;
1553
1567
  function hasVersionMarker(value) {
1554
1568
  return typeof value === "object" && value !== null && typeof value[MARKER_KEY] === "number";
1555
1569
  }
1556
- function fileLevelConfig(path, diagnostic) {
1570
+ function failedChain(files, diagnostic) {
1557
1571
  return {
1558
- path,
1559
- sections: {},
1572
+ files,
1560
1573
  diagnostics: [{
1561
1574
  section: null,
1562
1575
  diagnostic
@@ -1600,11 +1613,59 @@ function missingNamedFileDiagnostic(path) {
1600
1613
  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.",
1601
1614
  nextActions: [{
1602
1615
  kind: "user-choice",
1603
- label: "Correct the path passed to --config, or drop the flag to use the prisma.config.ts in the current directory."
1616
+ label: "Correct the path passed to --config, or drop the flag to let the CLI discover prisma.config.ts from the current directory."
1617
+ }],
1618
+ where: { path }
1619
+ };
1620
+ }
1621
+ /** JSON where it can (true, null, 42, {}); String for what JSON has no
1622
+ * spelling for (undefined cannot reach here, but bigint or a symbol
1623
+ * can). */
1624
+ function showParentValue(value) {
1625
+ try {
1626
+ return JSON.stringify(value) ?? String(value);
1627
+ } catch {
1628
+ return String(value);
1629
+ }
1630
+ }
1631
+ function invalidParentDiagnostic(path, value) {
1632
+ return {
1633
+ code: "CLI.CONFIG_PARENT_INVALID",
1634
+ severity: "error",
1635
+ summary: `${path} declares parent: ${showParentValue(value)}, but parent must be false or a path string.`,
1636
+ why: "'parent' controls config discovery: false makes this file the last on the chain, and a path names the next file explicitly. Any other value is a mistake the CLI stops on rather than guesses about.",
1637
+ nextActions: [{
1638
+ kind: "user-choice",
1639
+ label: "Set parent to false or to the path of the parent config file, or remove it to let discovery continue upward."
1604
1640
  }],
1605
1641
  where: { path }
1606
1642
  };
1607
1643
  }
1644
+ function missingParentDiagnostic(declaring, target) {
1645
+ return {
1646
+ code: "CLI.CONFIG_PARENT_NOT_FOUND",
1647
+ severity: "error",
1648
+ summary: `${declaring} names ${target} as its parent config, and there is no file there.`,
1649
+ nextActions: [{
1650
+ kind: "user-choice",
1651
+ label: "Correct the parent path, set parent to false, or remove it to let discovery continue upward."
1652
+ }],
1653
+ where: { path: declaring }
1654
+ };
1655
+ }
1656
+ function parentCycleDiagnostic(declaring, target) {
1657
+ return {
1658
+ code: "CLI.CONFIG_PARENT_CYCLE",
1659
+ severity: "error",
1660
+ summary: `${declaring} names ${target} as its parent config, but that file is already on the config chain.`,
1661
+ why: "Following the link again would loop forever, so resolution stops here.",
1662
+ nextActions: [{
1663
+ kind: "user-choice",
1664
+ label: "Break the cycle: point parent elsewhere or set it to false."
1665
+ }],
1666
+ where: { path: declaring }
1667
+ };
1668
+ }
1608
1669
  /** jiti reports an unresolvable import as "Cannot find module", Node's
1609
1670
  * own resolver as "Cannot find package"; either can appear in the
1610
1671
  * evaluation error chain depending on how the file is loaded. Node's
@@ -1701,55 +1762,161 @@ async function evaluateConfigFile(path) {
1701
1762
  * creating an own property, so that one key would disappear from
1702
1763
  * Object.keys and never be reported as unrecognised. */
1703
1764
  function sectionsOf(exported) {
1704
- return Object.fromEntries(Object.entries(exported).filter(([key]) => key !== MARKER_KEY));
1765
+ return Object.fromEntries(Object.entries(exported).filter(([key]) => key !== MARKER_KEY && key !== PARENT_KEY));
1705
1766
  }
1706
- /**
1707
- * The file to read, always absolute: the one --config named, resolved
1708
- * against cwd, or prisma.config.ts in cwd.
1709
- *
1710
- * Absolute is not cosmetic, and it is one more thing than either
1711
- * reference repository does — both are handed an absolute path before
1712
- * they reach c12, so neither has to resolve one. Given a relative path,
1713
- * c12 resolves it a second time against its own cwd and looks for a
1714
- * file that is not there, and jiti cannot import a relative specifier
1715
- * at all. Resolving here also makes the file's path in every diagnostic
1716
- * absolute, and makes the loaded-file comparison compare like with
1717
- * like.
1718
- */
1719
- function fileToRead(cwd, configPath) {
1720
- const root = resolve(cwd);
1721
- return configPath === void 0 ? join(root, CONFIG_FILE_NAME) : resolve(root, configPath);
1767
+ /** realpath where the path exists; the path itself where it does not
1768
+ * (a cwd that is gone, a comparison candidate that was just checked). */
1769
+ function realpathOr(path) {
1770
+ try {
1771
+ return realpathSync(path);
1772
+ } catch {
1773
+ return path;
1774
+ }
1722
1775
  }
1723
- /**
1724
- * The real-disk loader behind Runtime.loadConfig. The bin binds it to
1725
- * the process cwd and its own version; tests hand in fixtures.
1726
- * `cliVersion` names the exact prisma version in the install guidance
1727
- * when the 'prisma/config' entry point cannot be resolved; absent, the
1728
- * guidance names no version rather than an example that installs the
1729
- * wrong one.
1730
- */
1731
- async function loadConfig(cwd, configPath, cliVersion) {
1732
- const path = fileToRead(cwd, configPath);
1733
- if (!existsSync(path)) return configPath === void 0 ? {
1734
- path,
1735
- sections: {},
1736
- diagnostics: []
1737
- } : fileLevelConfig(path, missingNamedFileDiagnostic(path));
1776
+ /** The first directory at or above `dir` containing a `.git` entry —
1777
+ * a directory in an ordinary checkout, a file in worktrees and
1778
+ * submodules — or null when there is none all the way up. */
1779
+ function repositoryBoundary(dir) {
1780
+ let current = dir;
1781
+ while (true) {
1782
+ if (existsSync(join(current, ".git"))) return current;
1783
+ const parent = dirname(current);
1784
+ if (parent === current) return null;
1785
+ current = parent;
1786
+ }
1787
+ }
1788
+ /** The directories automatic discovery scans from `start`: upward to
1789
+ * the repository boundary inclusive, or `start` alone when no `.git`
1790
+ * exists at or above it. */
1791
+ function discoveryDirs(start) {
1792
+ const boundary = repositoryBoundary(start);
1793
+ const dirs = [start];
1794
+ let current = start;
1795
+ while (boundary !== null && current !== boundary) {
1796
+ current = dirname(current);
1797
+ dirs.push(current);
1798
+ }
1799
+ return dirs;
1800
+ }
1801
+ /** Where discovery continues after the file in `dir`: the directories
1802
+ * strictly above it, still inside its repository. Outside any
1803
+ * repository, nothing above it is scanned. */
1804
+ function dirsAbove(dir) {
1805
+ return discoveryDirs(dir).slice(1);
1806
+ }
1807
+ /** A directory named prisma.config.ts is not a config file, for
1808
+ * discovery and explicit `parent` links alike. */
1809
+ function isFileAt(path) {
1810
+ return existsSync(path) && statSync(path).isFile();
1811
+ }
1812
+ function nextDiscoveredFile(dirs, collected) {
1813
+ for (const dir of dirs) {
1814
+ const candidate = join(dir, CONFIG_FILE_NAME);
1815
+ if (isFileAt(candidate) && !collected.has(realpathOr(candidate))) return candidate;
1816
+ }
1817
+ return null;
1818
+ }
1819
+ /** One file's evaluation and marker/version classification, every
1820
+ * outcome carrying the diagnostic that names this file. */
1821
+ async function evaluateChainFile(path, cliVersion) {
1738
1822
  let exported;
1739
1823
  try {
1740
1824
  exported = await evaluateConfigFile(path);
1741
1825
  } catch (cause) {
1742
- return fileLevelConfig(path, importsMissingPrismaPackage(cause) ? prismaConfigUnresolvedDiagnostic(path, cliVersion) : unreadableDiagnostic(path, cause));
1826
+ return {
1827
+ ok: false,
1828
+ diagnostic: importsMissingPrismaPackage(cause) ? prismaConfigUnresolvedDiagnostic(path, cliVersion) : unreadableDiagnostic(path, cause)
1829
+ };
1743
1830
  }
1744
- if (!hasVersionMarker(exported)) return fileLevelConfig(path, missingMarkerDiagnostic(path));
1831
+ if (!hasVersionMarker(exported)) return {
1832
+ ok: false,
1833
+ diagnostic: missingMarkerDiagnostic(path)
1834
+ };
1745
1835
  const version = exported[MARKER_KEY];
1746
- if (version !== 1) return fileLevelConfig(path, unsupportedVersionDiagnostic(path, version));
1836
+ if (version !== 1) return {
1837
+ ok: false,
1838
+ diagnostic: unsupportedVersionDiagnostic(path, version)
1839
+ };
1747
1840
  return {
1748
- path,
1749
- sections: sectionsOf(exported),
1841
+ ok: true,
1842
+ exported
1843
+ };
1844
+ }
1845
+ /** Where the chain goes after the file at `path` declared `parent`:
1846
+ * false ends it, a path names the next file (checked to exist and to
1847
+ * not close a cycle), absence resumes automatic discovery above. */
1848
+ function followParent(path, parent, collected) {
1849
+ if (parent === false) return { next: null };
1850
+ if (typeof parent === "string") {
1851
+ const target = resolve(dirname(path), parent);
1852
+ if (!isFileAt(target)) return { diagnostic: missingParentDiagnostic(path, target) };
1853
+ const real = realpathOr(target);
1854
+ if (collected.has(real)) return { diagnostic: parentCycleDiagnostic(path, target) };
1855
+ return { next: {
1856
+ kind: "file",
1857
+ path: real
1858
+ } };
1859
+ }
1860
+ if (parent !== void 0) return { diagnostic: invalidParentDiagnostic(path, parent) };
1861
+ return { next: {
1862
+ kind: "scan",
1863
+ dirs: dirsAbove(realpathOr(dirname(path)))
1864
+ } };
1865
+ }
1866
+ async function collectChain(first, cliVersion) {
1867
+ const files = [];
1868
+ const collected = /* @__PURE__ */ new Set();
1869
+ let next = first;
1870
+ while (next !== null) {
1871
+ const path = next.kind === "file" ? next.path : nextDiscoveredFile(next.dirs, collected);
1872
+ if (path === null) break;
1873
+ const evaluated = await evaluateChainFile(path, cliVersion);
1874
+ if (!evaluated.ok) return failedChain(files, evaluated.diagnostic);
1875
+ files.push({
1876
+ path,
1877
+ sections: sectionsOf(evaluated.exported)
1878
+ });
1879
+ collected.add(realpathOr(path));
1880
+ const link = followParent(path, evaluated.exported[PARENT_KEY], collected);
1881
+ if ("diagnostic" in link) return failedChain(files, link.diagnostic);
1882
+ next = link.next;
1883
+ }
1884
+ return {
1885
+ files,
1750
1886
  diagnostics: []
1751
1887
  };
1752
1888
  }
1889
+ /**
1890
+ * The real-disk loader behind Runtime.loadConfig. The bin binds it to
1891
+ * the process cwd and its own version; tests hand in fixtures.
1892
+ * `cliVersion` names the exact prisma version in the install guidance
1893
+ * when the 'prisma/config' entry point cannot be resolved; absent, the
1894
+ * guidance names no version rather than an example that installs the
1895
+ * wrong one.
1896
+ *
1897
+ * Every path handed onward is absolute — one more thing than either
1898
+ * reference repository does, since both are handed an absolute path
1899
+ * before they reach c12. Given a relative path, c12 resolves it a
1900
+ * second time against its own cwd and looks for a file that is not
1901
+ * there, and jiti cannot import a relative specifier at all. Resolving
1902
+ * here also makes the file's path in every diagnostic absolute, and
1903
+ * makes every chain-path comparison compare like with like. The anchor
1904
+ * directory is additionally resolved through symlinks, so discovered
1905
+ * files and the errors about them name real paths.
1906
+ */
1907
+ async function loadConfig(cwd, configPath, cliVersion) {
1908
+ const root = resolve(cwd);
1909
+ if (configPath === void 0) return collectChain({
1910
+ kind: "scan",
1911
+ dirs: discoveryDirs(realpathOr(root))
1912
+ }, cliVersion);
1913
+ const named = resolve(root, configPath);
1914
+ if (!existsSync(named)) return failedChain([], missingNamedFileDiagnostic(named));
1915
+ return collectChain({
1916
+ kind: "file",
1917
+ path: realpathOr(named)
1918
+ }, cliVersion);
1919
+ }
1753
1920
  //#endregion
1754
1921
  //#region src/execution/pre-parse-argv.ts
1755
1922
  function flagTokens$1(argv) {
@@ -2074,17 +2241,19 @@ function validateSectionOwnership(spec, path, def) {
2074
2241
  * a section may only be named something the file format leaves free:
2075
2242
  * not `$`-prefixed (those are metadata — $prismaConfig is the version
2076
2243
  * marker, and a $meta key is deleted before the loader ever sees it),
2077
- * and not `extends` (the key config loaders take as an instruction to
2078
- * merge another file in). Both the families and the commands mounted
2079
- * without one are checked: whoever declares the section, claiming a
2080
- * reserved name is broken at build time, not at a user's runtime. */
2244
+ * not `parent` (the engine's chain directive, read and stripped by
2245
+ * the loader), and not `extends` (the key config loaders take as an
2246
+ * instruction to merge another file in). Both the families and the
2247
+ * commands mounted without one are checked: whoever declares the
2248
+ * section, claiming a reserved name is broken at build time, not at a
2249
+ * user's runtime. */
2081
2250
  function validateConfigSectionNames(spec) {
2082
2251
  for (const commandFamily of spec.commandFamilies) rejectReservedSectionName("command family", commandFamily.configSection);
2083
2252
  for (const [path, def] of Object.entries(spec.commands)) rejectReservedSectionName(`command '${path}'`, def.needs.config);
2084
2253
  }
2085
2254
  function rejectReservedSectionName(owner, section) {
2086
2255
  if (section === void 0 || !reservedConfigSectionName(section.name)) return;
2087
- 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)`);
2256
+ throw constructionError(`${owner} declares config section '${section.name}', a name the config file reserves ('parent' is the engine's chain directive, 'extends' is a config loader's merge directive, and '$'-prefixed keys are metadata)`);
2088
2257
  }
2089
2258
  function validateDocsBaseUrls(spec) {
2090
2259
  for (const commandFamily of spec.commandFamilies) {
@@ -2176,6 +2345,122 @@ function matchFlagRedirect(table, commandPath, typedFlags) {
2176
2345
  }
2177
2346
  }
2178
2347
  //#endregion
2348
+ //#region src/config-merge.ts
2349
+ /**
2350
+ * Per-key resolution of one config section over the loaded chain, and
2351
+ * the provenance that survives it: which files contributed the resolved
2352
+ * value, and which file wrote each of its top-level keys, so
2353
+ * diagnostics name the file to fix and relative paths resolve against
2354
+ * the file that declared them.
2355
+ *
2356
+ * A section's value is user code — a property getter can throw or side
2357
+ * effect — so each contributor's value is read exactly once, inside a
2358
+ * guard that turns a throw into a config error naming that file.
2359
+ */
2360
+ function isPlainObject(value) {
2361
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2362
+ const proto = Object.getPrototypeOf(value);
2363
+ return proto === Object.prototype || proto === null;
2364
+ }
2365
+ function snapshotContribution(file, name) {
2366
+ if (!Object.hasOwn(file.sections, name)) return null;
2367
+ const raw = file.sections[name];
2368
+ if (raw === void 0) return null;
2369
+ if (!isPlainObject(raw)) return {
2370
+ file,
2371
+ value: raw,
2372
+ keys: null
2373
+ };
2374
+ const entries = Object.entries(raw).filter(([, value]) => value !== void 0);
2375
+ return {
2376
+ file,
2377
+ value: Object.fromEntries(entries),
2378
+ keys: new Set(entries.map(([key]) => key))
2379
+ };
2380
+ }
2381
+ /** The engine's default merge: per key at the section's top level, the
2382
+ * child's key winning, replacement below. fromEntries rather than
2383
+ * key-by-key assignment: assigning a key named `__proto__` would run
2384
+ * the prototype setter instead of creating an own property. */
2385
+ function mergePerKey(parent, child) {
2386
+ if (!isPlainObject(parent) || !isPlainObject(child)) return child;
2387
+ return Object.fromEntries([...Object.entries(parent), ...Object.entries(child)]);
2388
+ }
2389
+ function provenanceOf(value, contributions) {
2390
+ const files = contributions.map((contribution) => contribution.file.path);
2391
+ return {
2392
+ files,
2393
+ keys: isPlainObject(value) ? Object.fromEntries(Object.keys(value).map((key) => [key, contributions.find((contribution) => contribution.keys?.has(key))?.file.path ?? files[0]])) : {}
2394
+ };
2395
+ }
2396
+ /**
2397
+ * Resolves `section` over the chain, nearest first: the farthest
2398
+ * declaring file's value, folded under each nearer one with the
2399
+ * section's own merge or the engine default. A plain-object result is
2400
+ * always a fresh, frozen object — the files' exports are never
2401
+ * mutated — and the result carries the provenance resolveSectionPath
2402
+ * consumes.
2403
+ */
2404
+ function resolveSectionOverChain(section, files) {
2405
+ const contributions = [];
2406
+ for (const file of files) {
2407
+ let contribution;
2408
+ try {
2409
+ contribution = snapshotContribution(file, section.name);
2410
+ } catch (cause) {
2411
+ return {
2412
+ ok: false,
2413
+ file: file.path,
2414
+ cause
2415
+ };
2416
+ }
2417
+ if (contribution !== null) contributions.push(contribution);
2418
+ }
2419
+ const contributors = contributions.map((contribution) => contribution.file);
2420
+ if (contributions.length === 0) return {
2421
+ ok: true,
2422
+ value: void 0,
2423
+ contributors,
2424
+ provenance: {
2425
+ files: [],
2426
+ keys: {}
2427
+ }
2428
+ };
2429
+ const merge = section.merge ?? mergePerKey;
2430
+ let merged;
2431
+ try {
2432
+ merged = contributions.map((contribution) => contribution.value).reduceRight((parent, child) => merge(parent, child));
2433
+ } catch (cause) {
2434
+ return {
2435
+ ok: false,
2436
+ file: contributions[0].file.path,
2437
+ cause
2438
+ };
2439
+ }
2440
+ const value = isPlainObject(merged) ? Object.freeze(merged) : merged;
2441
+ return {
2442
+ ok: true,
2443
+ value,
2444
+ contributors,
2445
+ provenance: provenanceOf(value, contributions)
2446
+ };
2447
+ }
2448
+ /**
2449
+ * Resolves a path found under a TOP-LEVEL `key` of a resolved section
2450
+ * value against the file that declared that key — never against cwd or
2451
+ * the nearest config file. The intended caller is a section validator,
2452
+ * which receives the provenance as its second argument and returns the
2453
+ * resolved absolute path in its validated value; an absolute path comes
2454
+ * back unchanged. Throws on a key the resolved value does not carry at its
2455
+ * top level — a silent fallback could resolve against the wrong file,
2456
+ * which is the mistake this helper exists to prevent.
2457
+ */
2458
+ function resolveSectionPath(provenance, key, path) {
2459
+ if (isAbsolute(path)) return path;
2460
+ if (!Object.hasOwn(provenance.keys, key)) throw new Error(`@prisma/cli-engine: resolveSectionPath resolves only top-level section keys, and '${key}' is not a top-level key of the resolved section`);
2461
+ return resolve(dirname(provenance.keys[key]), path);
2462
+ }
2463
+ //#endregion
2179
2464
  //#region src/execution/palette.ts
2180
2465
  /**
2181
2466
  * Tones into bytes, and text into a display width. Basic 16-colour SGR
@@ -2784,6 +3069,7 @@ async function checkNeeds(def, invocation) {
2784
3069
  return {
2785
3070
  kind: "ok",
2786
3071
  config: void 0,
3072
+ configFiles: [],
2787
3073
  spawnCredential: credentials.spawnCredential
2788
3074
  };
2789
3075
  }
@@ -2869,9 +3155,11 @@ function unknownSectionDiagnostic(path, key, configSections) {
2869
3155
  where: { path }
2870
3156
  };
2871
3157
  }
3158
+ /** Every file on the chain is checked — a typo'd key in a nested file
3159
+ * errors even when the command's section resolved elsewhere. */
2872
3160
  function unknownSections(loaded, configSections) {
2873
3161
  const declared = new Set(configSections);
2874
- return Object.keys(loaded.sections).filter((key) => !declared.has(key)).map((key) => unknownSectionDiagnostic(loaded.path, key, configSections));
3162
+ return loaded.files.flatMap((file) => Object.keys(file.sections).filter((key) => !declared.has(key)).map((key) => unknownSectionDiagnostic(file.path, key, configSections)));
2875
3163
  }
2876
3164
  /** The config file is read HERE and nowhere else, so a command with no
2877
3165
  * needs.config never touches it. The file `--config` named travels on
@@ -2883,35 +3171,68 @@ async function checkConfiguration(section, invocation) {
2883
3171
  const loaded = await invocation.runtime.loadConfig(configPath);
2884
3172
  const fileLevel = [...loaded.diagnostics.filter((entry) => entry.section === null).map((entry) => entry.diagnostic), ...unknownSections(loaded, invocation.configSections)];
2885
3173
  if (fileLevel.length > 0) return needsErrored(structuredErrorFromDiagnostic(fileLevel[0]), fileLevel.slice(1));
2886
- return validateConfigSection(section, loaded, invocation, configPath ?? "prisma.config.ts");
2887
- }
2888
- /** Validates the command's needed config section. The validator
2889
- * owns absence (it receives undefined when the section is missing) and
2890
- * never throws — a throw is an engine-boundary bug, settled as one.
2891
- * `configFile` is named in the error so a run under --config points at
2892
- * the file it actually read. */
2893
- function validateConfigSection(section, loaded, invocation, configFile) {
2894
- const raw = loaded.sections[section.name];
3174
+ return validateConfigSection(section, loaded, invocation);
3175
+ }
3176
+ /** Validates the command's needed config section, resolved per key over
3177
+ * the chain nearest-first. The validator owns absence (it receives
3178
+ * undefined when no file declares the section) and never throws — a
3179
+ * throw is an engine-boundary bug, settled as one. */
3180
+ function validateConfigSection(section, loaded, invocation) {
3181
+ const resolved = resolveSectionOverChain(section, loaded.files);
3182
+ if (!resolved.ok) return needsErrored(sectionUnreadableError(section.name, resolved.file, resolved.cause));
2895
3183
  let validation;
2896
3184
  try {
2897
- validation = section.validate(raw);
3185
+ validation = section.validate(resolved.value, resolved.provenance);
2898
3186
  } catch (cause) {
2899
3187
  return {
2900
3188
  kind: "bug",
2901
3189
  cause: new Error(`@prisma/cli-engine: the '${section.name}' config section validator threw instead of returning diagnostics (a validator never throws)`, { cause })
2902
3190
  };
2903
3191
  }
2904
- if (!validation.ok) return needsErrored(new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${section.name}' section of ${configFile} is invalid.`, { nextActions: [{
2905
- kind: "user-choice",
2906
- label: "Fix the reported problems in that section, then run the command again."
2907
- }] }), validation.diagnostics);
3192
+ if (!validation.ok) return needsErrored(sectionInvalidError(section.name, resolved.contributors, loaded.files), validation.diagnostics);
2908
3193
  writeSectionWarnings(invocation, validation.diagnostics);
2909
3194
  return {
2910
3195
  kind: "ok",
2911
3196
  config: validation.value,
3197
+ configFiles: Object.freeze(loaded.files),
2912
3198
  spawnCredential: void 0
2913
3199
  };
2914
3200
  }
3201
+ /** A section value's property getters and a section's custom merge are
3202
+ * user code alike; a throw from either is a config error naming the
3203
+ * file, never an engine bug. */
3204
+ function sectionUnreadableError(name, file, cause) {
3205
+ return new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${name}' section of ${file} is invalid: resolving its value threw '${(cause instanceof Error ? cause.message : String(cause)).split("\n", 1)[0].trim()}'.`, { nextActions: [{
3206
+ kind: "user-choice",
3207
+ label: "Fix the reported problems in that section, then run the command again."
3208
+ }] });
3209
+ }
3210
+ /** Provenance decides which file the error names: the one declaring
3211
+ * file, the nearest of several with the chain listed, or — when no
3212
+ * file declares the section at all — the fact that it is missing. */
3213
+ function sectionInvalidError(name, contributors, files) {
3214
+ const fix = {
3215
+ kind: "user-choice",
3216
+ label: "Fix the reported problems in that section, then run the command again."
3217
+ };
3218
+ if (contributors.length === 1) return new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${name}' section of ${contributors[0].path} is invalid.`, { nextActions: [fix] });
3219
+ if (contributors.length > 1) {
3220
+ const paths = contributors.map((file) => file.path);
3221
+ const parents = paths.length === 2 ? "its parent config file" : "its parent config files";
3222
+ return new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${name}' section, merged from ${paths[0]} and ${parents}, is invalid.`, {
3223
+ why: `The resolved section combines these files, nearest first: ${paths.join(", ")}.`,
3224
+ nextActions: [fix]
3225
+ });
3226
+ }
3227
+ const target = files[0]?.path ?? "prisma.config.ts";
3228
+ return new CliStructuredError("CLI.CONFIG_SECTION_INVALID", `The '${name}' section is missing: ${files.length === 0 ? "no config file was found" : "no loaded config file declares it"}.`, {
3229
+ why: files.length === 0 ? void 0 : `Config files loaded, nearest first: ${files.map((file) => file.path).join(", ")}.`,
3230
+ nextActions: [{
3231
+ kind: "user-choice",
3232
+ label: `Declare the '${name}' section in ${target}, then run the command again.`
3233
+ }]
3234
+ });
3235
+ }
2915
3236
  /** Diagnostics on an OK validation are warnings: written to stderr as
2916
3237
  * commentary in both formats (stderr is free for commentary in json
2917
3238
  * mode), filtered by the active log level, never added to the stream
@@ -3828,7 +4149,7 @@ function materializePresentation(state, ui, presentations) {
3828
4149
  next: presentations.next?.() ?? []
3829
4150
  };
3830
4151
  }
3831
- function makeContext(invocation, def, config, capabilities) {
4152
+ function makeContext(invocation, def, config, configFiles, capabilities) {
3832
4153
  const state = invocation.state;
3833
4154
  const ui = state.format === "markdown" ? unboundedUi() : makeUi(state.colorEnabled, invocation.runtime.stderr);
3834
4155
  const present = (outcome, presentations) => {
@@ -3847,6 +4168,8 @@ function makeContext(invocation, def, config, capabilities) {
3847
4168
  let api;
3848
4169
  const context = {
3849
4170
  config,
4171
+ configFiles,
4172
+ configPath: state.configPath,
3850
4173
  present,
3851
4174
  activeCredential: () => invocation.runtime.credentialManager?.activeCredential() ?? Promise.resolve(null),
3852
4175
  get api() {
@@ -5181,7 +5504,7 @@ var EngineImpl = class {
5181
5504
  flags: declaredFlags(entry.def, rawFlags),
5182
5505
  positionals: distributePositionals(entry.def, values)
5183
5506
  };
5184
- const ctx = makeContext(invocation, entry.def, needsOutcome.config, declaredCapabilities(entry.def));
5507
+ const ctx = makeContext(invocation, entry.def, needsOutcome.config, needsOutcome.configFiles, declaredCapabilities(entry.def));
5185
5508
  if (entry.def.kind === "session-command") {
5186
5509
  await this.settleHandlerOutcome(invocation, entry, () => handler(args, ctx), () => settleSessionCompleted(invocation));
5187
5510
  return;
@@ -5296,4 +5619,4 @@ function distributePositionals(def, values) {
5296
5619
  return positionals;
5297
5620
  }
5298
5621
  //#endregion
5299
- export { credentialRejectedError as C, noSessionForWorkspaceError as D, emptyServiceTokenError as E, authServiceError as S, credentialsRequiredError as T, positional as _, loadConfig as a, claimedIdentity as b, WORKSPACE_ID_ENV_VAR as c, userConfigPath as d, writeUserConfig as f, flag as g, detectCI as h, definePrismaConfig as i, PRESENTED as l, exitWithChildStatus as m, CONFIG_FILE_NAME as n, PRISMA_CONFIG_VERSION as o, resolveGating as p, defineConfig as r, SERVICE_TOKEN_ENV_VAR as s, buildEngine as t, readUserConfig as u, readActiveAccessToken as v, credentialWorkspaceMismatchError as w, credentialWorkspaceId as x, claimedExpiresAt as y };
5622
+ export { credentialWorkspaceId as C, credentialsRequiredError as D, credentialWorkspaceMismatchError as E, emptyServiceTokenError as O, claimedIdentity as S, credentialRejectedError as T, detectCI as _, definePrismaConfig as a, readActiveAccessToken as b, PRISMA_CONFIG_VERSION as c, PRESENTED as d, readUserConfig as f, exitWithChildStatus as g, resolveGating as h, CONFIG_FILE_NAME as i, noSessionForWorkspaceError as k, SERVICE_TOKEN_ENV_VAR as l, writeUserConfig as m, resolveSectionOverChain as n, loadConfig as o, userConfigPath as p, resolveSectionPath as r, realpathOr as s, buildEngine as t, WORKSPACE_ID_ENV_VAR as u, flag as v, authServiceError as w, claimedExpiresAt as x, positional as y };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as PRISMA_CONFIG_VERSION, A as Format, At as CredentialOrigin, B as Ui, C as defineSessionCommand, Ct as flag, D as OpenUrlRequest, Dt as Credential, E as OpenUrlOutcome, Et as ActiveCredential, F as Span, Ft as CredentialRefresher, G as ConfigSection, H as Severity, I as Status, It as ManagementApiClient, J as Host, K as SectionValidation, L as Text, Lt as ManagementApiClientConfig, M as PRESENTED, Mt as Session, N as Presentations, Nt as StoredSessions, O as PromptSurface, Ot as CredentialIdentity, P as PresentedResult, Pt as CredentialRefreshResult, Q as OutputStream, R as Tone, Rt as TokenStorage, S as defineServerCommand, St as PositionalSpec, T as CommandContext, Tt as ActiveAccessTokenOptions, U as StreamEvent, V as EngineEvent, W as StreamMeta, X as InputStream, Y as HostProcess, Z as LoadedConfig, _ as ServerCommandDefinition, _t as Args, a as RedirectSpec, at as ChildStatusSettlement, b as WorkflowStep, bt as CommandArgs, c as CommandDefinition, ct as SpawnOptions, d as CommandNeeds, dt as exitWithChildStatus, et as Runtime, f as CompletedEnvelope, ft as PackageManagerId, g as NeedsSpec, gt as PackageOperations, h as HelpSpec, ht as PackageManagerRunner, i as MountedTree, it as ChildResult, j as Outcome, jt as SERVICE_TOKEN_ENV_VAR, k as Block, kt as CredentialManager, l as CommandHandler, lt as SpawnRequest, m as Handler, mt as PackageManagerRunResult, n as CommandFamily, nt as EngineCommandSnapshot, o as defineCommandFamily, ot as ExitWithChildStatusOptions, p as ErroredEnvelope, pt as PackageManagerRunRequest, q as defineConfigSection, r as CommandRedirect, rt as RunSummary, s as AnyCommand, st as SpawnChild, t as TelemetryDeclaration, tt as TelemetryPayload, u as CommandHelp, ut as SpawnedChild, v as SessionCommandDefinition, vt as ArgsSpec, w as BrowserWaitRequest, wt as positional, x as defineCommand, xt as FlagSpec, y as SpawnDeclarations, yt as Char, z as TreeNode } from "./report-DNdnCXuq.js";
1
+ import { $ as HostProcess, A as Format, At as ActiveAccessTokenOptions, B as Ui, Bt as CredentialRefresher, C as defineSessionCommand, Ct as ArgsSpec, D as OpenUrlRequest, Dt as PositionalSpec, E as OpenUrlOutcome, Et as FlagSpec, F as Span, Ft as CredentialOrigin, G as ConfigSection, H as Severity, Ht as ManagementApiClientConfig, I as Status, It as SERVICE_TOKEN_ENV_VAR, J as ResolvedSection, K as SectionValidation, L as Text, Lt as Session, M as PRESENTED, Mt as Credential, N as Presentations, Nt as CredentialIdentity, O as PromptSurface, Ot as flag, P as PresentedResult, Pt as CredentialManager, Q as Host, R as Tone, Rt as StoredSessions, S as defineServerCommand, St as Args, T as CommandContext, Tt as CommandArgs, U as StreamEvent, Ut as TokenStorage, V as EngineEvent, Vt as ManagementApiClient, W as StreamMeta, X as resolveSectionOverChain, Y as SectionProvenance, Z as resolveSectionPath, _ as ServerCommandDefinition, _t as PackageManagerId, a as RedirectSpec, at as Runtime, b as WorkflowStep, bt as PackageManagerRunner, c as CommandDefinition, ct as RunSummary, d as CommandNeeds, dt as ExitWithChildStatusOptions, et as InputStream, f as CompletedEnvelope, ft as SpawnChild, g as NeedsSpec, gt as exitWithChildStatus, h as HelpSpec, ht as SpawnedChild, i as MountedTree, it as PRISMA_CONFIG_VERSION, j as Outcome, jt as ActiveCredential, k as Block, kt as positional, l as CommandHandler, lt as ChildResult, m as Handler, mt as SpawnRequest, n as CommandFamily, nt as LoadedConfigFile, o as defineCommandFamily, ot as TelemetryPayload, p as ErroredEnvelope, pt as SpawnOptions, q as defineConfigSection, r as CommandRedirect, rt as OutputStream, s as AnyCommand, st as EngineCommandSnapshot, t as TelemetryDeclaration, tt as LoadedConfig, u as CommandHelp, ut as ChildStatusSettlement, v as SessionCommandDefinition, vt as PackageManagerRunRequest, w as BrowserWaitRequest, wt as Char, x as defineCommand, xt as PackageOperations, y as SpawnDeclarations, yt as PackageManagerRunResult, z as TreeNode, zt as CredentialRefreshResult } from "./report-CCIboNYr.js";
2
2
  import { n as CliStructuredError } from "./protocol-YjqPCCOG.js";
3
3
 
4
4
  //#region src/active-access-token.d.ts
@@ -81,9 +81,9 @@ declare function createCli(spec: {
81
81
  declare function definePrismaConfig<T extends Record<string, unknown>>(config: T): T & {
82
82
  readonly $prismaConfig: number;
83
83
  };
84
- /** @deprecated Renamed to {@link definePrismaConfig}: every family's
85
- * config helper carries a unique name, so none needs an import alias. */
86
- declare const defineConfig: typeof definePrismaConfig;
84
+ /** realpath where the path exists; the path itself where it does not
85
+ * (a cwd that is gone, a comparison candidate that was just checked). */
86
+ declare function realpathOr(path: string): string;
87
87
  /**
88
88
  * The real-disk loader behind Runtime.loadConfig. The bin binds it to
89
89
  * the process cwd and its own version; tests hand in fixtures.
@@ -91,6 +91,16 @@ declare const defineConfig: typeof definePrismaConfig;
91
91
  * when the 'prisma/config' entry point cannot be resolved; absent, the
92
92
  * guidance names no version rather than an example that installs the
93
93
  * wrong one.
94
+ *
95
+ * Every path handed onward is absolute — one more thing than either
96
+ * reference repository does, since both are handed an absolute path
97
+ * before they reach c12. Given a relative path, c12 resolves it a
98
+ * second time against its own cwd and looks for a file that is not
99
+ * there, and jiti cannot import a relative specifier at all. Resolving
100
+ * here also makes the file's path in every diagnostic absolute, and
101
+ * makes every chain-path comparison compare like with like. The anchor
102
+ * directory is additionally resolved through symlinks, so discovered
103
+ * files and the errors about them name real paths.
94
104
  */
95
105
  declare function loadConfig(cwd: string, configPath?: string, cliVersion?: string): Promise<LoadedConfig>;
96
106
  //#endregion
@@ -215,4 +225,4 @@ declare function claimedExpiresAt(token: string): Date | undefined;
215
225
  */
216
226
  declare function claimedIdentity(token: string): CredentialIdentity | undefined;
217
227
  //#endregion
218
- export { type ActiveAccessTokenOptions, 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 CommandRedirect, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialRefreshResult, type CredentialRefresher, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, EnvironmentCredentialManager, type ErroredEnvelope, type ExitWithChildStatusOptions, type FlagSpec, type Format, type Handler, type HelpSpec, type Host, 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 PackageManagerId, type PackageManagerRunRequest, type PackageManagerRunResult, type PackageManagerRunner, type PackageOperations, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RedirectSpec, type RunSummary, type Runtime, SERVICE_TOKEN_ENV_VAR, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type Span, type SpawnChild, type SpawnDeclarations, type SpawnOptions, type SpawnRequest, type SpawnedChild, type Status, type StoredSessions, type StreamEvent, type StreamMeta, type TelemetryDeclaration, type TelemetryPayload, type TelemetryStatus, type TelemetryStatusReason, type Text, type TokenStorage, type Tone, type TreeNode, type Ui, type WorkflowStep, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, definePrismaConfig, defineServerCommand, defineSessionCommand, detectCI, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional, readActiveAccessToken, telemetryCommandGroup };
228
+ export { type ActiveAccessTokenOptions, 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 CommandRedirect, type CompletedEnvelope, type ConfigSection, type Credential, type CredentialIdentity, type CredentialManager, type CredentialOrigin, type CredentialRefreshResult, type CredentialRefresher, type CredentialsRequiredReason, type EngineCommandSnapshot, type EngineEvent, EnvironmentCredentialManager, type ErroredEnvelope, type ExitWithChildStatusOptions, type FlagSpec, type Format, type Handler, type HelpSpec, type Host, type HostProcess, type InputStream, type LoadedConfig, type LoadedConfigFile, type ManagementApiClient, type ManagementApiClientConfig, type MountedTree, type NeedsSpec, type OpenUrlOutcome, type OpenUrlRequest, type Outcome, type OutputStream, PRESENTED, PRISMA_CONFIG_VERSION, type PackageManagerId, type PackageManagerRunRequest, type PackageManagerRunResult, type PackageManagerRunner, type PackageOperations, type PositionalSpec, type Presentations, type PresentedResult, type PromptSurface, type RedirectSpec, type ResolvedSection, type RunSummary, type Runtime, SERVICE_TOKEN_ENV_VAR, type SectionProvenance, type SectionValidation, type ServerCommandDefinition, type Session, type SessionCommandDefinition, type Severity, type Span, type SpawnChild, type SpawnDeclarations, type SpawnOptions, type SpawnRequest, type SpawnedChild, type Status, type StoredSessions, type StreamEvent, type StreamMeta, type TelemetryDeclaration, type TelemetryPayload, type TelemetryStatus, type TelemetryStatusReason, type Text, type TokenStorage, type Tone, type TreeNode, type Ui, type WorkflowStep, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfigSection, definePrismaConfig, defineServerCommand, defineSessionCommand, detectCI, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional, readActiveAccessToken, realpathOr, resolveSectionOverChain, resolveSectionPath, telemetryCommandGroup };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { i as ok, r as notOk, t as CliStructuredError } from "./protocol-TtNVkeVS.js";
2
- import { C as credentialRejectedError, D as noSessionForWorkspaceError, E as emptyServiceTokenError, S as authServiceError, T as credentialsRequiredError, _ as positional, a as loadConfig, b as claimedIdentity, c as WORKSPACE_ID_ENV_VAR, d as userConfigPath, f as writeUserConfig, g as flag, h as detectCI, i as definePrismaConfig, l as PRESENTED, m as exitWithChildStatus, o as PRISMA_CONFIG_VERSION, p as resolveGating, r as defineConfig, s as SERVICE_TOKEN_ENV_VAR, t as buildEngine, u as readUserConfig, v as readActiveAccessToken, w as credentialWorkspaceMismatchError, x as credentialWorkspaceId, y as claimedExpiresAt } from "./engine-DSn58puQ.js";
2
+ import { C as credentialWorkspaceId, D as credentialsRequiredError, E as credentialWorkspaceMismatchError, O as emptyServiceTokenError, S as claimedIdentity, T as credentialRejectedError, _ as detectCI, a as definePrismaConfig, b as readActiveAccessToken, c as PRISMA_CONFIG_VERSION, d as PRESENTED, f as readUserConfig, g as exitWithChildStatus, h as resolveGating, k as noSessionForWorkspaceError, l as SERVICE_TOKEN_ENV_VAR, m as writeUserConfig, n as resolveSectionOverChain, o as loadConfig, p as userConfigPath, r as resolveSectionPath, s as realpathOr, t as buildEngine, u as WORKSPACE_ID_ENV_VAR, v as flag, w as authServiceError, x as claimedExpiresAt, y as positional } from "./engine-DaES-DtJ.js";
3
3
  //#region src/cli.ts
4
4
  /**
5
5
  * Shell-side construction. Group help is declared with the mount.
@@ -95,7 +95,8 @@ function defineServerCommand(def) {
95
95
  function defineConfigSection(spec) {
96
96
  return Object.freeze({
97
97
  name: spec.name,
98
- validate: spec.validate
98
+ validate: spec.validate,
99
+ merge: spec.merge
99
100
  });
100
101
  }
101
102
  //#endregion
@@ -378,4 +379,4 @@ Telemetry is on by default (opt-out); see ${options.docsUrl}\nfor what is collec
378
379
  };
379
380
  }
380
381
  //#endregion
381
- export { EnvironmentCredentialManager, PRESENTED, PRISMA_CONFIG_VERSION, SERVICE_TOKEN_ENV_VAR, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfig, defineConfigSection, definePrismaConfig, defineServerCommand, defineSessionCommand, detectCI, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional, readActiveAccessToken, telemetryCommandGroup };
382
+ export { EnvironmentCredentialManager, PRESENTED, PRISMA_CONFIG_VERSION, SERVICE_TOKEN_ENV_VAR, authServiceError, claimedExpiresAt, claimedIdentity, createCli, credentialRejectedError, credentialWorkspaceId, credentialWorkspaceMismatchError, credentialsRequiredError, defineCommand, defineCommandFamily, defineConfigSection, definePrismaConfig, defineServerCommand, defineSessionCommand, detectCI, emptyServiceTokenError, exitWithChildStatus, flag, loadConfig, noSessionForWorkspaceError, positional, readActiveAccessToken, realpathOr, resolveSectionOverChain, resolveSectionPath, telemetryCommandGroup };
@@ -587,13 +587,16 @@ interface Runtime {
587
587
  */
588
588
  readonly onSignal: (cb: (signal: "SIGINT" | "SIGTERM") => void) => () => void;
589
589
  /**
590
- * Reads prisma.config.ts, on demand. The engine calls it only when
591
- * the command it is about to run declares a config section, so a run
592
- * that needs no config never touches the file. `configPath` is the
593
- * file `--config` named: the loader resolves it against the runtime's
594
- * cwd and reports its absence. Absent means look for prisma.config.ts
595
- * in cwd, where absence is not an error. The bin wires the real disk
596
- * loader; tests hand in fixtures.
590
+ * Resolves the prisma.config.ts chain, on demand. The engine calls it
591
+ * only when the command it is about to run declares a config section,
592
+ * so a run that needs no config never touches a file. `configPath` is
593
+ * the file `--config` named: the loader resolves it against the
594
+ * runtime's cwd, reports its absence, makes it the first chain link,
595
+ * and resumes discovery strictly above its directory — a
596
+ * prisma.config.ts beside it is not collected. Absent means
597
+ * discover from cwd, where finding no file is
598
+ * not an error. The bin wires the real disk loader; tests hand in
599
+ * fixtures.
597
600
  */
598
601
  readonly loadConfig: (configPath?: string) => Promise<LoadedConfig>;
599
602
  /**
@@ -703,26 +706,33 @@ interface HostProcess {
703
706
  off(event: "SIGINT" | "SIGTERM", listener: () => void): unknown;
704
707
  exit(code: number): never;
705
708
  }
706
- interface LoadedConfig {
707
- /**
708
- * The file this config came from, absolute: the one `--config` named,
709
- * or prisma.config.ts in cwd. A loader that found no file still names
710
- * the file it looked for — with no file there are no sections, and
711
- * the engine reads the path only to name the file when it reports a
712
- * top-level key that is not one of the CLI's sections.
713
- */
709
+ /** One file on the resolved config chain. */
710
+ interface LoadedConfigFile {
711
+ /** Where the file is, absolute; every diagnostic about it names it. */
714
712
  readonly path: string;
715
713
  /**
716
- * Raw section values by name; validation happens per command via its
717
- * command family's section token. The engine, not the loader, checks
718
- * these names against the sections the CLI declares, so the closed
719
- * set holds whatever loader a host wires.
714
+ * Raw section values by name — the file's top-level keys minus the
715
+ * engine-reserved ones (`$prismaConfig`, `parent`); validation
716
+ * happens per command via its command family's section token. The
717
+ * engine, not the loader, checks these names against the sections
718
+ * the CLI declares, so the closed set holds whatever loader a host
719
+ * wires.
720
720
  */
721
721
  readonly sections: Readonly<Record<string, unknown>>;
722
+ }
723
+ interface LoadedConfig {
724
+ /**
725
+ * The resolved chain, nearest-first: the anchor file (the one
726
+ * `--config` named, or prisma.config.ts discovered from cwd), then
727
+ * each ancestor or declared parent. Empty when discovery found no
728
+ * file at all — the section validators own absence.
729
+ */
730
+ readonly files: ReadonlyArray<LoadedConfigFile>;
722
731
  /**
723
- * File-level problems (unevaluable module, missing version marker)
724
- * carry section: null and fail only commands with a needs.config
725
- * section; commands with no config need run normally.
732
+ * File-level problems anywhere on the chain (unevaluable module,
733
+ * missing version marker, a broken `parent` link) carry
734
+ * section: null and fail only commands with a needs.config section;
735
+ * commands with no config need run normally.
726
736
  */
727
737
  readonly diagnostics: ReadonlyArray<{
728
738
  readonly section: string | null;
@@ -730,23 +740,84 @@ interface LoadedConfig {
730
740
  }>;
731
741
  }
732
742
  /**
733
- * The config contract version defineConfig writes as the structural
743
+ * The config contract version definePrismaConfig writes as the structural
734
744
  * `$prismaConfig` marker; the loader checks it before interpreting
735
745
  * anything.
736
746
  */
737
747
  declare const PRISMA_CONFIG_VERSION = 1;
738
748
  //#endregion
749
+ //#region src/config-merge.d.ts
750
+ /** Which files a resolved section value came from. */
751
+ interface SectionProvenance {
752
+ /** Paths of the files declaring the section, nearest first. */
753
+ readonly files: readonly string[];
754
+ /**
755
+ * The declaring file per top-level key of the resolved value: the
756
+ * nearest file whose raw section wrote that key. A key no file wrote
757
+ * (a custom merge produced it) is attributed to the nearest file.
758
+ */
759
+ readonly keys: Readonly<Record<string, string>>;
760
+ }
761
+ type ResolvedSection = {
762
+ readonly ok: true;
763
+ /** undefined when no file on the chain declares the section — the
764
+ * section validator owns absence, exactly as before. */
765
+ readonly value: unknown; /** The files declaring the section, nearest first. */
766
+ readonly contributors: readonly LoadedConfigFile[]; /** Where the value came from, for resolveSectionPath. */
767
+ readonly provenance: SectionProvenance;
768
+ } | {
769
+ /** Reading or merging the section's value threw: the value and a
770
+ * custom merge are user code alike, so this is a config error
771
+ * naming the file, never an engine bug. */
772
+ readonly ok: false;
773
+ readonly file: string;
774
+ readonly cause: unknown;
775
+ };
776
+ /**
777
+ * Resolves `section` over the chain, nearest first: the farthest
778
+ * declaring file's value, folded under each nearer one with the
779
+ * section's own merge or the engine default. A plain-object result is
780
+ * always a fresh, frozen object — the files' exports are never
781
+ * mutated — and the result carries the provenance resolveSectionPath
782
+ * consumes.
783
+ */
784
+ declare function resolveSectionOverChain(section: ConfigSection<unknown>, files: readonly LoadedConfigFile[]): ResolvedSection;
785
+ /**
786
+ * Resolves a path found under a TOP-LEVEL `key` of a resolved section
787
+ * value against the file that declared that key — never against cwd or
788
+ * the nearest config file. The intended caller is a section validator,
789
+ * which receives the provenance as its second argument and returns the
790
+ * resolved absolute path in its validated value; an absolute path comes
791
+ * back unchanged. Throws on a key the resolved value does not carry at its
792
+ * top level — a silent fallback could resolve against the wrong file,
793
+ * which is the mistake this helper exists to prevent.
794
+ */
795
+ declare function resolveSectionPath(provenance: SectionProvenance, key: string, path: string): string;
796
+ //#endregion
739
797
  //#region src/config-section.d.ts
740
798
  /**
741
799
  * A command family's named slice of prisma.config.ts. The token couples
742
800
  * the section name, its validated type, and its total validator. The
743
801
  * validator owns absence: its input is the raw section value, or
744
802
  * undefined when the config file has no such section. It returns
745
- * findings; it never throws.
803
+ * findings; it never throws. Its second argument is the resolved
804
+ * value's provenance: a validator with path-valued keys resolves each
805
+ * through resolveSectionPath(provenance, key, path) and returns
806
+ * absolute paths, so downstream code never resolves against cwd. A
807
+ * one-argument validator stays valid for sections with no paths.
746
808
  */
747
809
  interface ConfigSection<T> {
748
810
  readonly name: string;
749
- readonly validate: (raw: unknown | undefined) => SectionValidation<T>;
811
+ readonly validate: (raw: unknown | undefined, provenance: SectionProvenance) => SectionValidation<T>;
812
+ /**
813
+ * How two files' raw values combine when more than one file on the
814
+ * config chain declares the section. `child` is the nearer file's
815
+ * value and wins conflicts. Both inputs may be frozen, so the result
816
+ * must be a fresh value, never a mutation of either. Absent, the
817
+ * engine merges per key at the section's top level and replaces
818
+ * below.
819
+ */
820
+ readonly merge?: (parent: unknown, child: unknown) => unknown;
750
821
  }
751
822
  /**
752
823
  * Diagnostics on an OK validation are warnings: the engine writes them
@@ -763,7 +834,8 @@ type SectionValidation<T> = {
763
834
  };
764
835
  declare function defineConfigSection<T>(spec: {
765
836
  readonly name: string;
766
- readonly validate: (raw: unknown | undefined) => SectionValidation<T>;
837
+ readonly validate: (raw: unknown | undefined, provenance: SectionProvenance) => SectionValidation<T>;
838
+ readonly merge?: (parent: unknown, child: unknown) => unknown;
767
839
  }): ConfigSection<T>;
768
840
  //#endregion
769
841
  //#region src/events.d.ts
@@ -1022,6 +1094,20 @@ interface CommandContext<TConfig = undefined, TCode extends number = never> {
1022
1094
  * validator. Commands with no config need get undefined.
1023
1095
  */
1024
1096
  readonly config: TConfig;
1097
+ /**
1098
+ * The config chain the needs check resolved, nearest-first — the
1099
+ * same load ctx.config was validated from, including files whose
1100
+ * sections this command did not need. Empty when the command
1101
+ * declares no config need, and when discovery found no file.
1102
+ */
1103
+ readonly configFiles: ReadonlyArray<LoadedConfigFile>;
1104
+ /**
1105
+ * The file `--config` named, exactly as the user wrote it, or
1106
+ * undefined when the flag was absent. Handlers that load config out
1107
+ * of band (outside needs.config) pass it on, so the file the user
1108
+ * named governs those reads too.
1109
+ */
1110
+ readonly configPath: string | undefined;
1025
1111
  /**
1026
1112
  * Builds the PresentedResult for the active format. The only
1027
1113
  * constructor of PresentedResult.
@@ -1554,4 +1640,4 @@ interface TelemetryDeclaration {
1554
1640
  readonly docsUrl: string;
1555
1641
  }
1556
1642
  //#endregion
1557
- export { PRISMA_CONFIG_VERSION as $, Format as A, CredentialOrigin as At, Ui as B, defineSessionCommand as C, flag as Ct, OpenUrlRequest as D, Credential as Dt, OpenUrlOutcome as E, ActiveCredential as Et, Span as F, CredentialRefresher as Ft, ConfigSection as G, Severity as H, Status as I, ManagementApiClient$1 as It, Host as J, SectionValidation as K, Text as L, ManagementApiClientConfig as Lt, PRESENTED as M, Session as Mt, Presentations as N, StoredSessions as Nt, PromptSurface as O, CredentialIdentity as Ot, PresentedResult as P, CredentialRefreshResult as Pt, OutputStream as Q, Tone as R, TokenStorage$1 as Rt, defineServerCommand as S, PositionalSpec as St, CommandContext as T, ActiveAccessTokenOptions as Tt, StreamEvent as U, EngineEvent as V, StreamMeta as W, InputStream as X, HostProcess as Y, LoadedConfig as Z, ServerCommandDefinition as _, Args as _t, RedirectSpec as a, ChildStatusSettlement as at, WorkflowStep as b, CommandArgs as bt, CommandDefinition as c, SpawnOptions as ct, CommandNeeds as d, exitWithChildStatus as dt, Runtime as et, CompletedEnvelope as f, PackageManagerId as ft, NeedsSpec as g, PackageOperations as gt, HelpSpec as h, PackageManagerRunner as ht, MountedTree as i, ChildResult as it, Outcome as j, SERVICE_TOKEN_ENV_VAR as jt, Block as k, CredentialManager as kt, CommandHandler as l, SpawnRequest as lt, Handler as m, PackageManagerRunResult as mt, CommandFamily as n, EngineCommandSnapshot as nt, defineCommandFamily as o, ExitWithChildStatusOptions as ot, ErroredEnvelope as p, PackageManagerRunRequest as pt, defineConfigSection as q, CommandRedirect as r, RunSummary as rt, AnyCommand as s, SpawnChild as st, TelemetryDeclaration as t, TelemetryPayload as tt, CommandHelp as u, SpawnedChild as ut, SessionCommandDefinition as v, ArgsSpec as vt, BrowserWaitRequest as w, positional as wt, defineCommand as x, FlagSpec as xt, SpawnDeclarations as y, Char as yt, TreeNode as z };
1643
+ export { HostProcess as $, Format as A, ActiveAccessTokenOptions as At, Ui as B, CredentialRefresher as Bt, defineSessionCommand as C, ArgsSpec as Ct, OpenUrlRequest as D, PositionalSpec as Dt, OpenUrlOutcome as E, FlagSpec as Et, Span as F, CredentialOrigin as Ft, ConfigSection as G, Severity as H, ManagementApiClientConfig as Ht, Status as I, SERVICE_TOKEN_ENV_VAR as It, ResolvedSection as J, SectionValidation as K, Text as L, Session as Lt, PRESENTED as M, Credential as Mt, Presentations as N, CredentialIdentity as Nt, PromptSurface as O, flag as Ot, PresentedResult as P, CredentialManager as Pt, Host as Q, Tone as R, StoredSessions as Rt, defineServerCommand as S, Args as St, CommandContext as T, CommandArgs as Tt, StreamEvent as U, TokenStorage$1 as Ut, EngineEvent as V, ManagementApiClient$1 as Vt, StreamMeta as W, resolveSectionOverChain as X, SectionProvenance as Y, resolveSectionPath as Z, ServerCommandDefinition as _, PackageManagerId as _t, RedirectSpec as a, Runtime as at, WorkflowStep as b, PackageManagerRunner as bt, CommandDefinition as c, RunSummary as ct, CommandNeeds as d, ExitWithChildStatusOptions as dt, InputStream as et, CompletedEnvelope as f, SpawnChild as ft, NeedsSpec as g, exitWithChildStatus as gt, HelpSpec as h, SpawnedChild as ht, MountedTree as i, PRISMA_CONFIG_VERSION as it, Outcome as j, ActiveCredential as jt, Block as k, positional as kt, CommandHandler as l, ChildResult as lt, Handler as m, SpawnRequest as mt, CommandFamily as n, LoadedConfigFile as nt, defineCommandFamily as o, TelemetryPayload as ot, ErroredEnvelope as p, SpawnOptions as pt, defineConfigSection as q, CommandRedirect as r, OutputStream as rt, AnyCommand as s, EngineCommandSnapshot as st, TelemetryDeclaration as t, LoadedConfig as tt, CommandHelp as u, ChildStatusSettlement as ut, SessionCommandDefinition as v, PackageManagerRunRequest as vt, BrowserWaitRequest as w, Char as wt, defineCommand as x, PackageOperations as xt, SpawnDeclarations as y, PackageManagerRunResult as yt, TreeNode as z, CredentialRefreshResult as zt };
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Dt as Credential, Et as ActiveCredential, Ft as CredentialRefresher, It as ManagementApiClient, J as Host, Lt as ManagementApiClientConfig, Mt as Session, Nt as StoredSessions, P as PresentedResult, Rt as TokenStorage, Tt as ActiveAccessTokenOptions, U as StreamEvent, V as EngineEvent, b as WorkflowStep, et as Runtime, ft as PackageManagerId, ht as PackageManagerRunner, i as MountedTree, it as ChildResult, kt as CredentialManager, lt as SpawnRequest, n as CommandFamily, rt as RunSummary, st as SpawnChild, t as TelemetryDeclaration, tt as TelemetryPayload } from "./report-DNdnCXuq.js";
1
+ import { At as ActiveAccessTokenOptions, Bt as CredentialRefresher, Ht as ManagementApiClientConfig, Lt as Session, Mt as Credential, P as PresentedResult, Pt as CredentialManager, Q as Host, Rt as StoredSessions, U as StreamEvent, Ut as TokenStorage, V as EngineEvent, Vt as ManagementApiClient, _t as PackageManagerId, at as Runtime, b as WorkflowStep, bt as PackageManagerRunner, ct as RunSummary, ft as SpawnChild, i as MountedTree, jt as ActiveCredential, lt as ChildResult, mt as SpawnRequest, n as CommandFamily, ot as TelemetryPayload, t as TelemetryDeclaration } from "./report-CCIboNYr.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
package/dist/testing.js CHANGED
@@ -1,5 +1,6 @@
1
- import { D as noSessionForWorkspaceError, T as credentialsRequiredError, b as claimedIdentity, t as buildEngine, v as readActiveAccessToken, w as credentialWorkspaceMismatchError, x as credentialWorkspaceId, y as claimedExpiresAt } from "./engine-DSn58puQ.js";
1
+ import { C as credentialWorkspaceId, D as credentialsRequiredError, E as credentialWorkspaceMismatchError, S as claimedIdentity, b as readActiveAccessToken, k as noSessionForWorkspaceError, t as buildEngine, x as claimedExpiresAt } from "./engine-DaES-DtJ.js";
2
2
  import { Buffer } from "node:buffer";
3
+ import { resolve } from "node:path";
3
4
  //#region src/in-memory-credential-manager.ts
4
5
  /**
5
6
  * A complete CredentialManager whose state lives in memory rather than
@@ -367,9 +368,13 @@ function createTestCli(spec) {
367
368
  apiBaseUrl: managementApiBaseUrl,
368
369
  authBaseUrl: "https://auth.test.invalid"
369
370
  };
370
- const loadConfig = spec.loadConfig ?? (async (configPath) => ({
371
- path: configPath ?? "prisma.config.ts",
372
- sections: spec.config ?? {},
371
+ /** LoadedConfigFile.path is absolute by contract, so the seeded file
372
+ * lands in the run's cwd — where the real loader would discover it. */
373
+ const loadConfigFor = (cwd) => spec.loadConfig ?? (async (configPath) => ({
374
+ files: [{
375
+ path: resolve(cwd, configPath ?? "prisma.config.ts"),
376
+ sections: spec.config ?? {}
377
+ }],
373
378
  diagnostics: []
374
379
  }));
375
380
  const spawnChild = spec.spawn ?? scriptedSpawn(spec.spawnScript ?? (() => ({
@@ -439,7 +444,7 @@ function createTestCli(spec) {
439
444
  signalListeners.delete(cb);
440
445
  };
441
446
  },
442
- loadConfig,
447
+ loadConfig: loadConfigFor(opts?.cwd ?? "/"),
443
448
  credentialManager,
444
449
  managementApiClientConfig,
445
450
  spawn: recordingSpawn(spawnChild, spawns),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/cli-engine",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "The execution engine of the unified Prisma CLI.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -52,8 +52,8 @@
52
52
  },
53
53
  "devDependencies": {
54
54
  "@prisma/management-api-sdk": "1.69.0",
55
- "@repo/cli-conformance": "8.0.0-rc.14-dev.102",
56
- "@repo/tsconfig": "8.0.0-rc.14-dev.102",
55
+ "@repo/cli-conformance": "8.0.0-rc.15-dev.110",
56
+ "@repo/tsconfig": "8.0.0-rc.15-dev.110",
57
57
  "@types/node": "^22.19.19",
58
58
  "ci-info": "^4.3.1",
59
59
  "tsdown": "^0.21.10",