@prisma/orm-mongo 8.0.0-rc.26 → 8.0.0-rc.28

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.
Files changed (28) hide show
  1. package/dist/{mongo-static-DnxWWp96-D-vo6-SA.mjs → mongo-static-BcGm3FJA-Cu72kTZk.mjs} +3 -3
  2. package/dist/{mongo-static-DnxWWp96-D-vo6-SA.mjs.map → mongo-static-BcGm3FJA-Cu72kTZk.mjs.map} +1 -1
  3. package/dist/runtime.mjs +1 -1
  4. package/dist/runtime.mjs.map +1 -1
  5. package/dist/static.mjs +1 -1
  6. package/package.json +12 -12
  7. package/skills/prisma-8/SKILL.md +3 -3
  8. package/skills/prisma-8/references/contract.md +1 -1
  9. package/skills/prisma-8/references/scripts/find-detection-hits.ts +57 -0
  10. package/skills/prisma-8/references/upgrade-app.md +29 -10
  11. package/skills/prisma-8/references/upgrade-extension.md +24 -7
  12. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +139 -42
  13. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +164 -12
  14. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +110 -18
  15. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +28 -6
  16. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +70 -13
  17. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +98 -13
  18. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +102 -0
  19. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
  20. package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +2 -1
  21. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +33 -19
  22. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +164 -12
  23. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +110 -18
  24. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +28 -6
  25. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +70 -13
  26. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +98 -13
  27. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +56 -0
  28. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
@@ -6,18 +6,21 @@
6
6
  *
7
7
  * Usage: node contract-hash-inputs.ts [project-root]
8
8
  *
9
- * The project root defaults to the working directory. The script reads and writes files only; it needs no database. It walks the root, skipping `node_modules`, `dist`, `build` and directories whose name starts with a dot, and finds stored files the way the `stored-files-format-version` script does: a contract by its content (`targetFamily` and `storage`) in any `*.json` file, a `migration.json` by the `ops.json` next to it, and a ref file by where Prisma writes refs or by its content.
9
+ * The project root defaults to the working directory. The script reads and writes files only; it needs no database. It walks the root, skipping `node_modules`, `dist`, `build`, directories whose name starts with a dot and, in a git repository, the files and folders git ignores, unless git ignores the root itself, except a migrations folder (one holding the contract snapshot store, a migration package or a ref file, directly or in a space folder) and what is in it, since nothing else writes those files again, and finds stored files the way the `stored-files-format-version` script does: a contract by its content (`targetFamily` and `storage`) in any `*.json` file, a `migration.json` by the `ops.json` next to it, and a ref file by where Prisma writes refs or by its content.
10
10
  *
11
11
  * First it checks every contract: each stored `storageHash`, `profileHash` and `executionHash`, and each snapshot directory's name, must be the hash the old rules or the new rules give the contract's content. Two exceptions: a snapshot's profile and execution hash may come from an earlier release's rules, and a MongoDB snapshot may keep the storage hash it had before an earlier upgrade step rewrote its content; both get the hashes their content gives. Then it checks each `migration.json` against its `migrationHash`, and that each `from`, `to` and ref `hash` names a contract of the project. If any check fails, it changes no file, prints one line per problem and exits 1. A hash that does not match the content means the file was edited by hand or comes from another release; fix that first.
12
12
  *
13
13
  * It reads a stored file whether or not it has a `formatVersion`, and leaves its format version as it is: a file a release candidate wrote keeps `"schemaVersion": "1"`, or no version field, and this release reads it as format version 0.
14
14
  *
15
- * A contract that is not a snapshot and whose storage hash no migration, ref or snapshot names, such as a hand-made test fixture, does not stop the upgrade when its hashes are wrong: it is reported, left unchanged, and makes the script exit 1.
15
+ * A contract that is not a snapshot and whose storage hash no migration, ref or snapshot names, such as a hand-made test fixture, does not stop the upgrade when its hashes are wrong: it is reported, left unchanged, and makes the script exit 1. An intermediate contract, one in a migration's directory beside its `migration.ts`, which reads it to type a data migration's queries, is the exception: when its hashes are wrong it is listed as an intermediate contract and left unchanged, and the script still exits 0, since that `migration.ts` is not run again after this upgrade.
16
+ *
17
+ * A contract whose `execution.mutations.defaults` refs still have the keys `table` and `column`, which 8.0.0-rc.13 renamed to `entry` and `field`, stops the run when it is a snapshot or something names its storage hash: the script changes no file and gives the command of the 8.0.0-rc.12 to 8.0.0-rc.13 step that renames them. Such a contract that nothing names is left alone like one with wrong hashes: an intermediate contract is listed as one, and any other is reported and makes the script exit 1.
16
18
  *
17
19
  * Otherwise it rewrites: the three hashes in every contract; the same hashes in the `contract.d.ts` beside it; each snapshot directory's name; `from`, `to` and `migrationHash` in every `migration.json`, and the storage hashes in the `ops.json` beside it; `hash` in every ref file; and every old storage hash in every `migration.ts` (snapshot import paths and hash literals). It edits each file's text, so every other byte stays, including a leading byte order mark, and replaces each file in one rename, so a run that stops partway can be run again to finish. It prints what it changed and each hash it replaced. A `contract.d.ts` whose hashes it cannot match with its contract, or a migration or ref naming a hash it cannot tell the new value of, is reported, left unchanged, and makes it exit 1. A second run changes nothing.
18
20
  *
19
21
  * The hash rules, old and new, the families' normal forms of storage and the migration hash rule are copied from Prisma's packages, because a project's strict `node_modules` does not expose them.
20
22
  */
23
+ import { spawnSync } from 'node:child_process';
21
24
  import { createHash } from 'node:crypto';
22
25
  import {
23
26
  chmodSync,
@@ -31,7 +34,8 @@ import {
31
34
  statSync,
32
35
  writeFileSync,
33
36
  } from 'node:fs';
34
- import { basename, dirname, join, relative, resolve, sep } from 'node:path';
37
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
38
+ import { fileURLToPath } from 'node:url';
35
39
 
36
40
  type Json = null | boolean | number | string | Json[] | JsonRecord;
37
41
  interface JsonRecord {
@@ -1145,6 +1149,79 @@ function isWalked(name: string): boolean {
1145
1149
  return !SKIPPED_DIRECTORIES.has(name) && !name.startsWith('.');
1146
1150
  }
1147
1151
 
1152
+ let ignoredByGit: (path: string) => boolean = () => false;
1153
+
1154
+ /** A test of whether git ignores a file or folder under `root`. Outside a git repository it ignores nothing, and so it does when git ignores `root` itself, which the user then named on purpose. */
1155
+ function gitIgnores(root: string): (path: string) => boolean {
1156
+ const listed = spawnSync(
1157
+ 'git',
1158
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
1159
+ { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 30 },
1160
+ );
1161
+ if (listed.status !== 0) return () => false;
1162
+ const ignored = new Set(
1163
+ listed.stdout
1164
+ .split('\0')
1165
+ .filter((path) => path !== '')
1166
+ .map((path) => path.replace(/\/$/, '')),
1167
+ );
1168
+ if (ignored.has('.')) return () => false;
1169
+ const bases = [root, realpathSync(root)];
1170
+ return (path) =>
1171
+ bases.some((base) => ignored.has(relative(base, path).split(sep).join('/'))) &&
1172
+ !isInMigrationsFolder(bases, path);
1173
+ }
1174
+
1175
+ function readsAsRef(path: string): boolean {
1176
+ try {
1177
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
1178
+ return isRecord(value) && hasRefContent(value);
1179
+ } catch {
1180
+ return false;
1181
+ }
1182
+ }
1183
+
1184
+ /** Whether `dir` holds what Prisma writes to a migrations directory or to one of its spaces: the contract snapshot store, a migration package or a ref file. */
1185
+ function holdsMigrationFiles(dir: string): boolean {
1186
+ return isMigrationsDirectory(dir) || holdsRef(dir);
1187
+ }
1188
+
1189
+ function holdsRef(dir: string): boolean {
1190
+ const refs = join(dir, 'refs');
1191
+ const entries = listDirectory(refs);
1192
+ return (
1193
+ typeof entries !== 'string' &&
1194
+ entries.some((entry) => entry.isFile() && readsAsRef(join(refs, entry.name)))
1195
+ );
1196
+ }
1197
+
1198
+ /** Whether `dir` holds what Prisma writes to a space of a migrations directory: a migration package or a ref file. The snapshot store sits beside the spaces, never in one. */
1199
+ function holdsSpaceFiles(dir: string): boolean {
1200
+ return hasSubdirectory(dir, isMigrationPackage) || holdsRef(dir);
1201
+ }
1202
+
1203
+ function isMigrationsFolder(dir: string): boolean {
1204
+ return (
1205
+ holdsMigrationFiles(dir) ||
1206
+ hasSubdirectory(dir, (path, name) => SPACE_ID.test(name) && holdsSpaceFiles(path))
1207
+ );
1208
+ }
1209
+
1210
+ /** Whether `path`, or a folder it is in below the project root, is a migrations folder, whose files the script upgrades even when git ignores them: nothing else writes them again. */
1211
+ function isInMigrationsFolder(bases: readonly string[], path: string): boolean {
1212
+ for (let dir = path; !bases.includes(dir) && dir !== dirname(dir); dir = dirname(dir))
1213
+ if (isDirectory(dir) && isMigrationsFolder(dir)) return true;
1214
+ return false;
1215
+ }
1216
+
1217
+ /** Whether the walk from `realRoot` reaches `target`. */
1218
+ function isReached(realRoot: string, target: string): boolean {
1219
+ const names = relative(realRoot, target).split(sep);
1220
+ return names.every(
1221
+ (name, index) => isWalked(name) && !ignoredByGit(join(realRoot, ...names.slice(0, index + 1))),
1222
+ );
1223
+ }
1224
+
1148
1225
  function isInside(dir: string, path: string): boolean {
1149
1226
  return path === dir || path.startsWith(`${dir}${sep}`);
1150
1227
  }
@@ -1164,12 +1241,16 @@ function visit(
1164
1241
  for (const entry of entries) {
1165
1242
  const path = join(dir, entry.name);
1166
1243
  const shown = relative(root, path);
1167
- if (entry.isDirectory()) {
1168
- if (entry.name.startsWith('.') && entry.name.endsWith(REMOVED_SUFFIX))
1169
- files.leftovers.push(path);
1170
- else if (isWalked(entry.name)) visit(root, path, files, stops, checkLinks);
1171
- } else if (entry.isFile() && entry.name.endsWith(TEMPORARY_SUFFIX)) {
1244
+ const isLeftover = entry.isDirectory()
1245
+ ? entry.name.startsWith('.') && entry.name.endsWith(REMOVED_SUFFIX)
1246
+ : entry.isFile() && entry.name.endsWith(TEMPORARY_SUFFIX);
1247
+ if (isLeftover) {
1172
1248
  files.leftovers.push(path);
1249
+ continue;
1250
+ }
1251
+ if (ignoredByGit(path)) continue;
1252
+ if (entry.isDirectory()) {
1253
+ if (isWalked(entry.name)) visit(root, path, files, stops, checkLinks);
1173
1254
  } else if (entry.isFile() && entry.name.endsWith('.json')) {
1174
1255
  classify(root, path, files, stops, shown);
1175
1256
  } else if (entry.isFile() && entry.name === 'migration.ts' && isMigrationPackage(dir)) {
@@ -1196,9 +1277,7 @@ function checkLink(root: string, path: string, name: string, stops: string[]): v
1196
1277
  }
1197
1278
  if (isInside(target, realRoot)) return;
1198
1279
  const inside = isInside(realRoot, target);
1199
- const reached =
1200
- relative(realRoot, target).split(sep).every(isWalked) &&
1201
- (isDirectory(target) || target.endsWith('.json'));
1280
+ const reached = isReached(realRoot, target) && (isDirectory(target) || target.endsWith('.json'));
1202
1281
  const intoSnapshot = inside && isInSnapshotDirectory(realRoot, target);
1203
1282
  const reading = inside && reached ? linkReading(root, path, realRoot, target, name) : undefined;
1204
1283
  if (reading === 'snapshot') {
@@ -1405,20 +1484,81 @@ function hashList(hashes: HashSet): string {
1405
1484
  }
1406
1485
 
1407
1486
  interface ContractChecks {
1487
+ /** The project root the script upgrades. */
1488
+ readonly root: string;
1408
1489
  readonly stops: string[];
1409
1490
  /** Contracts the script leaves unchanged and reports, without refusing the project. */
1410
1491
  readonly left: string[];
1411
1492
  /** Snapshots whose profile or execution hash an earlier release wrote by other rules. */
1412
1493
  readonly notes: string[];
1494
+ /** Stale intermediate contracts the script leaves unchanged without counting them as problems. */
1495
+ readonly intermediate: string[];
1413
1496
  /** Every storage hash a migration, ref or snapshot names. */
1414
1497
  readonly named: ReadonlySet<string>;
1415
1498
  }
1416
1499
 
1500
+ function oldExecutionRefs(value: JsonRecord): readonly string[] {
1501
+ const execution = value['execution'];
1502
+ const mutations = isRecord(execution) ? execution['mutations'] : undefined;
1503
+ const defaults = isRecord(mutations) ? mutations['defaults'] : undefined;
1504
+ if (!Array.isArray(defaults)) return [];
1505
+ return defaults.flatMap((entry) => {
1506
+ const ref = isRecord(entry) ? entry['ref'] : undefined;
1507
+ if (!isRecord(ref) || !('table' in ref || 'column' in ref)) return [];
1508
+ return [`${String(ref['table'])}.${String(ref['column'])}`];
1509
+ });
1510
+ }
1511
+
1512
+ function isIntermediateContract(path: string): boolean {
1513
+ const dir = dirname(path);
1514
+ return isMigrationPackage(dir) && existsSync(join(dir, 'migration.ts'));
1515
+ }
1516
+
1517
+ /** The `node` command that runs the 8.0.0-rc.12 to 8.0.0-rc.13 script of this skill copy from `root`: relative to `root` when the copy is inside it. */
1518
+ function renameExecutionRefKeysCommand(root: string): string {
1519
+ const upgrades = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
1520
+ const script = join(
1521
+ upgrades,
1522
+ '8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts',
1523
+ );
1524
+ const fromRoot = relative(realpathSync(root), script);
1525
+ const path = fromRoot.startsWith('..') || isAbsolute(fromRoot) ? script : fromRoot;
1526
+ return `node ${path.split(sep).join('/')}`;
1527
+ }
1528
+
1529
+ function planOldExecutionRefs(
1530
+ file: StoredText,
1531
+ shown: string,
1532
+ oldRefs: readonly string[],
1533
+ checks: ContractChecks,
1534
+ ): void {
1535
+ const refs = `its execution.mutations.defaults refs name "table" and "column" (${oldRefs.join(', ')}), the keys from before 8.0.0-rc.13, which "entry" and "field" replaced`;
1536
+ const storage = storedHashes(file.value).storage;
1537
+ const isNamed = typeof storage === 'string' && checks.named.has(storage);
1538
+ if (snapshotDirectoryHash(file.path) === undefined && !isNamed) {
1539
+ if (isIntermediateContract(file.path)) checks.intermediate.push(shown);
1540
+ else
1541
+ checks.left.push(
1542
+ `${shown}: ${refs}. It is not a snapshot, and no migration, ref or snapshot names its hashes, so the script leaves it alone. If Prisma emits it, emit it again with \`prisma contract emit\`; otherwise rename those keys to "entry" and "field"`,
1543
+ );
1544
+ return;
1545
+ }
1546
+ const remedy = shown.split('/').includes('migrations')
1547
+ ? `Run the script of the 8.0.0-rc.12 to 8.0.0-rc.13 step \`execution-ref-entry-field\`, which renames the keys in every contract under a \`migrations\` folder, from the project root: \`${renameExecutionRefKeysCommand(checks.root)}\`. Then run this script again`
1548
+ : 'Emit it again with `prisma contract emit`, as the 8.0.0-rc.12 to 8.0.0-rc.13 step `execution-ref-entry-field` says, then run this script again';
1549
+ checks.stops.push(`${shown}: ${refs}. ${remedy}`);
1550
+ }
1551
+
1417
1552
  function planContract(
1418
1553
  file: StoredText,
1419
1554
  shown: string,
1420
1555
  checks: ContractChecks,
1421
1556
  ): ContractPlan | undefined {
1557
+ const oldRefs = oldExecutionRefs(file.value);
1558
+ if (oldRefs.length > 0) {
1559
+ planOldExecutionRefs(file, shown, oldRefs, checks);
1560
+ return undefined;
1561
+ }
1422
1562
  const sections = sectionsOf(file.value);
1423
1563
  if (typeof sections === 'string') {
1424
1564
  checks.stops.push(`${shown}: ${sections}`);
@@ -1463,7 +1603,9 @@ function planContract(
1463
1603
  );
1464
1604
  if (problems.length > 0) {
1465
1605
  const isNamed = typeof stored.storage === 'string' && checks.named.has(stored.storage);
1466
- if (snapshotHash === undefined && !isNamed)
1606
+ if (snapshotHash === undefined && !isNamed && isIntermediateContract(file.path))
1607
+ checks.intermediate.push(shown);
1608
+ else if (snapshotHash === undefined && !isNamed)
1467
1609
  checks.left.push(
1468
1610
  `${shown}: ${problems.join('; ')}. It is not a snapshot, and no migration, ref or snapshot names its hashes, so the script leaves it alone. If Prisma emits it, emit it again with \`prisma contract emit\`; otherwise set its ${hashList(newHashes)}, the hashes its content gives`,
1469
1611
  );
@@ -1653,6 +1795,7 @@ interface Plan {
1653
1795
  readonly superseded: string[];
1654
1796
  /** Contracts whose capabilities the script writes as the list of keys `requiredCapabilities`. */
1655
1797
  readonly renamedCapabilities: string[];
1798
+ readonly intermediate: readonly string[];
1656
1799
  readonly problems: string[];
1657
1800
  }
1658
1801
 
@@ -1666,6 +1809,7 @@ function main(args: readonly string[]): number {
1666
1809
  process.stderr.write(`${root}: not a directory\n`);
1667
1810
  return 1;
1668
1811
  }
1812
+ ignoredByGit = gitIgnores(root);
1669
1813
  const shown = (path: string) => relative(root, path).split(sep).join('/');
1670
1814
  const files = emptyFiles();
1671
1815
  const stops: string[] = [];
@@ -1674,9 +1818,11 @@ function main(args: readonly string[]): number {
1674
1818
 
1675
1819
  const contracts: ContractPlan[] = [];
1676
1820
  const checks: ContractChecks = {
1821
+ root,
1677
1822
  stops,
1678
1823
  left: [...files.unversioned],
1679
1824
  notes: [],
1825
+ intermediate: [],
1680
1826
  named: namedHashes(files),
1681
1827
  };
1682
1828
  for (const file of files.contracts) {
@@ -1720,6 +1866,7 @@ function main(args: readonly string[]): number {
1720
1866
  merged: [],
1721
1867
  superseded: [],
1722
1868
  renamedCapabilities: [],
1869
+ intermediate: checks.intermediate,
1723
1870
  problems: checks.left,
1724
1871
  };
1725
1872
  const alreadyNew = unknownHashesAlreadyNew(files.migrations, hashes);
@@ -2042,6 +2189,11 @@ function report(
2042
2189
  'Snapshot directories whose new name already held a snapshot with the same storage hash, which `prisma contract emit` wrote with this release. The script kept that snapshot unchanged and removed the old directory:',
2043
2190
  ...plan.superseded.map((note) => ` ${note}`),
2044
2191
  );
2192
+ if (plan.intermediate.length > 0)
2193
+ lines.push(
2194
+ 'Intermediate contracts, left as they are. Each sits beside the `migration.ts` of a data migration, which reads it to type its queries. Their hashes are not the ones their content gives, or their execution default refs have the keys from before 8.0.0-rc.13, but only that `migration.ts` reads them, and it is not run again after this upgrade, so the script does not change them:',
2195
+ ...[...plan.intermediate].sort(compareCodeUnits).map((path) => ` ${path}`),
2196
+ );
2045
2197
  process.stdout.write(`${lines.join('\n')}\n`);
2046
2198
  }
2047
2199
 
@@ -4,22 +4,25 @@
4
4
  *
5
5
  * Usage: node contract-signature-names.ts [project-root]
6
6
  *
7
- * The project root defaults to the working directory. The script walks it, skipping `node_modules`, `dist`, `build` and directories whose name starts with a dot other than the CI folders `.github`, `.circleci`, `.gitlab` and `.buildkite`, and changes:
7
+ * The project root defaults to the working directory. The script walks it, skipping `node_modules`, `dist`, `build`, directories whose name starts with a dot other than the CI folders `.github`, `.circleci`, `.gitlab` and `.buildkite` and, in a git repository, the files and folders git ignores, unless git ignores the project root itself, and changes:
8
8
  *
9
- * - the flag `--marker-only` of `db verify` to `--signature-only`, wherever it is written as a whole word;
10
- * - each of the nine renamed error codes, wherever it is written, and the published path `@prisma/orm-target-mysql/target/marker-lock`;
9
+ * - the flag `--marker-only` of `db verify` to `--signature-only`, wherever it is written as a whole word outside Markdown;
10
+ * - each of the nine renamed error codes, wherever it is written outside Markdown, and the published path `@prisma/orm-target-mysql/target/marker-lock`;
11
11
  * - in code, the values `'orphanMarker'`, `'markerChanged'` and `'marker-verification'`, written as strings, which only Prisma's errors and logs carry;
12
12
  * - in a code file that imports a renamed name from an `@prisma/orm-*` package, that import and the file's uses of it; a name the file re-exports keeps the name the file exports, and an object written in shorthand keeps its key (`{ errorMarkerMissing: errorSignatureMissing }`);
13
13
  * - in a code file that imports from an `@prisma/orm-*` package, a renamed member of a published interface where the file reads it (`.readMarker`), writes it as a key (`{ verifyMarker: false }`) or declares it in a class or interface (`readMarker(…) {`);
14
14
  * - in a code file that runs `db verify`, `db init`, `db update` or `db migrate` with `--json`, the fields it reads from that output, `marker` and `markerHash`, as properties, as keys of an object, and in destructuring, where the project's own name is kept (`{ signature: marker }`); and the mode `'marker-only'`.
15
15
  *
16
+ * It changes no Markdown file (`.md`, `.mdx`), since Markdown can quote what an earlier release printed and its sentences name the marker in other words too. After the files it changed, it lists under `Not changed:` each line of Markdown that names the old flag, an old error code or, on a line that runs a command with `--json`, an old field, as `file:line: old -> new`, for you to change by hand where the text describes this release.
17
+ *
16
18
  * A name of the project's own, declared, exported or passed as a parameter, is never renamed, nor a name inside a longer one. It works out every file's new text before it writes any, so a run that stops before writing changes no file. If a write fails, it stops, names the file it failed on, which may be partly written, and names the files it did not write. It prints each file it changed, and a second run changes nothing.
17
19
  *
18
20
  * To tell a local binding of a renamed name, or of a namespace an `@prisma/orm-*` package is imported as, such as a parameter, from the import, the script reads a file that uses a renamed name through an import with the TypeScript compiler of the project, so such a project needs its `typescript` package installed.
19
21
  */
22
+ import { spawnSync } from 'node:child_process';
20
23
  import { readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
21
24
  import { createRequire } from 'node:module';
22
- import { join, relative, resolve } from 'node:path';
25
+ import { basename, join, relative, resolve, sep } from 'node:path';
23
26
  import { fileURLToPath, pathToFileURL } from 'node:url';
24
27
  import type * as TS from 'typescript';
25
28
 
@@ -338,7 +341,7 @@ function importUses(
338
341
  host,
339
342
  });
340
343
  if (program.getSourceFile(file.fileName) !== file)
341
- throw new Error(
344
+ throw new ScriptStop(
342
345
  `TypeScript did not take in ${fileName}, so the script cannot tell a local binding from an import there.`,
343
346
  );
344
347
  const checker = program.getTypeChecker();
@@ -570,6 +573,11 @@ export function rewriteCode(ts: () => TypeScript, fileName: string, source: stri
570
573
  return applyEdits(text, edits);
571
574
  }
572
575
 
576
+ const JSON_FIELD = /\.marker(Hash)?(?![\w$])/g;
577
+
578
+ const runsDbWithJson = (line: string): boolean =>
579
+ /--json/.test(line) && /\bdb\s+(?:verify|init|update|migrate)\b/.test(line);
580
+
573
581
  /** Scripts and CI files: the flag, the codes, and on a line that runs a command with `--json`, the fields a `jq` filter reads. */
574
582
  export function rewriteScript(source: string): string {
575
583
  return source
@@ -577,43 +585,118 @@ export function rewriteScript(source: string): string {
577
585
  .replace(CODE, (code) => CODES[code] ?? code)
578
586
  .split('\n')
579
587
  .map((line) =>
580
- /--json/.test(line) && /\bdb\s+(?:verify|init|update|migrate)\b/.test(line)
581
- ? line.replace(/\.marker(Hash)?(?![\w$])/g, (_, hash = '') => `.signature${hash}`)
582
- : line,
588
+ runsDbWithJson(line) ? line.replace(JSON_FIELD, (_, hash = '') => `.signature${hash}`) : line,
583
589
  )
584
590
  .join('\n');
585
591
  }
586
592
 
593
+ /** Each line of Markdown that names what `rewriteScript` renames, with the renames. */
594
+ export function markdownRenames(
595
+ source: string,
596
+ ): Array<{ readonly line: number; readonly renames: readonly string[] }> {
597
+ return source.split('\n').flatMap((text, index) => {
598
+ const renames = [
599
+ ...[...text.matchAll(FLAG)].map(() => '--marker-only -> --signature-only'),
600
+ ...[...text.matchAll(CODE)].map(([code]) => `${code} -> ${CODES[code] ?? code}`),
601
+ ...(runsDbWithJson(text)
602
+ ? [...text.matchAll(JSON_FIELD)].map(
603
+ ([field]) => `${field} -> .signature${field.slice('.marker'.length)}`,
604
+ )
605
+ : []),
606
+ ];
607
+ return renames.length === 0 ? [] : [{ line: index + 1, renames: [...new Set(renames)] }];
608
+ });
609
+ }
610
+
587
611
  const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
588
612
  const CI_DIRECTORIES = new Set(['.github', '.circleci', '.gitlab', '.buildkite']);
589
613
  const CODE_FILE = /\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;
614
+ const MARKDOWN_FILE = /\.mdx?$/;
590
615
  const SCRIPT_FILE =
591
616
  /(^package\.json$|^Makefile$|^Dockerfile$|^justfile$|\.(sh|bash|zsh|ya?ml|toml|md|mdx)$)/;
592
617
 
593
- function* files(dir: string): Generator<string> {
618
+ /** A test of whether git ignores a file or folder under `root`. Outside a git repository it ignores nothing, and so it does when git ignores `root` itself, which the user then named on purpose. */
619
+ function gitIgnores(root: string): (path: string) => boolean {
620
+ const listed = spawnSync(
621
+ 'git',
622
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
623
+ { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 30 },
624
+ );
625
+ if (listed.status !== 0) return () => false;
626
+ const ignored = new Set(
627
+ listed.stdout
628
+ .split('\0')
629
+ .filter((path) => path !== '')
630
+ .map((path) => path.replace(/\/$/, '')),
631
+ );
632
+ if (ignored.has('.')) return () => false;
633
+ const bases = [root, realpathSync(root)];
634
+ return (path) => bases.some((base) => ignored.has(relative(base, path).split(sep).join('/')));
635
+ }
636
+
637
+ function* files(dir: string, ignored: (path: string) => boolean): Generator<string> {
594
638
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
639
+ const path = join(dir, entry.name);
640
+ if (ignored(path)) continue;
595
641
  if (entry.isDirectory()) {
596
642
  if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
597
643
  if (entry.name.startsWith('.') && !CI_DIRECTORIES.has(entry.name)) continue;
598
- yield* files(join(dir, entry.name));
644
+ yield* files(path, ignored);
599
645
  } else if (entry.isFile() && (CODE_FILE.test(entry.name) || SCRIPT_FILE.test(entry.name))) {
600
- yield join(dir, entry.name);
646
+ yield path;
601
647
  }
602
648
  }
603
649
  }
604
650
 
651
+ /** A stop the script expects, such as a missing `typescript`, as against a fault in the script. */
652
+ class ScriptStop extends Error {}
653
+
654
+ function hasCompilerApi(module: unknown): module is TypeScript {
655
+ return (
656
+ typeof module === 'object' &&
657
+ module !== null &&
658
+ 'createProgram' in module &&
659
+ typeof module.createProgram === 'function'
660
+ );
661
+ }
662
+
663
+ function versionOf(module: unknown): string {
664
+ return typeof module === 'object' &&
665
+ module !== null &&
666
+ 'version' in module &&
667
+ typeof module.version === 'string'
668
+ ? module.version
669
+ : 'unknown';
670
+ }
671
+
605
672
  /** TypeScript's compiler, from the project the script works on, or else from beside the script. */
606
673
  export function loadTypeScript(root: string): TypeScript {
674
+ const withoutCompiler = new Set<string>();
607
675
  for (const from of [join(root, 'package.json'), fileURLToPath(import.meta.url)]) {
676
+ let found: unknown;
608
677
  try {
609
- return createRequire(from)('typescript');
610
- } catch {}
678
+ found = createRequire(from)('typescript');
679
+ } catch {
680
+ continue;
681
+ }
682
+ if (hasCompilerApi(found)) return found;
683
+ withoutCompiler.add(versionOf(found));
611
684
  }
612
- throw new Error(
685
+ if (withoutCompiler.size > 0)
686
+ throw new ScriptStop(
687
+ `This script reads code with the TypeScript compiler, and the \`typescript\` package it found, version ${[...withoutCompiler].join(' and ')}, has no compiler: the \`typescript\` package of TypeScript 7 exports only its version. The script needs TypeScript 5 or 6. There are two ways to give it one. The first changes nothing in the project: make an empty folder outside the project, write a \`package.json\` in it that holds \`{"type": "module"}\`, run \`pnpm add typescript@5\` in that folder, copy this script into it, and run the copy with the project folder as its argument: \`node <folder>/${basename(fileURLToPath(import.meta.url))} <project folder>\`. Without that \`package.json\`, Node prints a \`MODULE_TYPELESS_PACKAGE_JSON\` warning, which is harmless. The second installs TypeScript 5 in the project for the run: \`pnpm add -D typescript@5\`, with \`-w\` added at the root of a pnpm workspace. It changes \`package.json\` and the lockfile, so after the run put back the \`typescript\` version you had, with \`pnpm add -D typescript@<your version>\` (with \`-w\` again where you used it), or \`pnpm remove typescript\` if the project had none; do not use \`git checkout\` on those files, which would also undo the other uncommitted changes the upgrade made to them.`,
688
+ );
689
+ throw new ScriptStop(
613
690
  'This script reads code that imports a renamed name with TypeScript, and found no `typescript` package in the project or beside the script. Prisma lists `typescript` as an optional peer dependency, so the project may not have it: install it in the project, for example as a development dependency, then run the script again.',
614
691
  );
615
692
  }
616
693
 
694
+ function stopMessage(error: unknown): string {
695
+ if (error instanceof ScriptStop) return `${error.message}\nThe script changed no file.`;
696
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
697
+ return `The script failed on an unexpected error, before it changed any file. This is a fault in the script; report it to Prisma with this output:\n${detail}`;
698
+ }
699
+
617
700
  function main(): void {
618
701
  const root = resolve(process.argv[2] ?? process.cwd());
619
702
  let typescript: TypeScript | undefined;
@@ -622,18 +705,22 @@ function main(): void {
622
705
  return typescript;
623
706
  };
624
707
  const changes: Array<readonly [string, string]> = [];
708
+ const markdown: string[] = [];
625
709
  try {
626
- for (const file of files(root)) {
710
+ for (const file of files(root, gitIgnores(root))) {
627
711
  const source = readFileSync(file, 'utf8');
712
+ if (MARKDOWN_FILE.test(file)) {
713
+ for (const { line, renames } of markdownRenames(source))
714
+ markdown.push(`${relative(root, file)}:${line}: ${renames.join(', ')}`);
715
+ continue;
716
+ }
628
717
  const rewritten = CODE_FILE.test(file)
629
718
  ? rewriteCode(ts, file, source)
630
719
  : rewriteScript(source);
631
720
  if (rewritten !== source) changes.push([file, rewritten]);
632
721
  }
633
722
  } catch (error) {
634
- console.error(
635
- `${error instanceof Error ? error.message : String(error)}\nThe script changed no file.`,
636
- );
723
+ console.error(stopMessage(error));
637
724
  process.exitCode = 1;
638
725
  return;
639
726
  }
@@ -657,6 +744,11 @@ function main(): void {
657
744
  process.exitCode = 1;
658
745
  return;
659
746
  }
747
+ if (markdown.length === 0) return;
748
+ console.log(
749
+ 'Not changed: these lines of Markdown name an old flag, error code or JSON field. Markdown can quote what an earlier release printed, so change by hand only the ones that describe this release, with the words around them, such as "marker":',
750
+ );
751
+ for (const entry of markdown) console.log(` ${entry}`);
660
752
  }
661
753
 
662
754
  // Node names the module by its real path, so a script reached through a symbolic link compares that.
@@ -4,10 +4,11 @@
4
4
  *
5
5
  * Usage: node facade-paths-an-application-uses.ts [project-root]
6
6
  *
7
- * The project root defaults to the working directory. The script walks it, skipping `node_modules`, `dist`, `build` and directories whose name starts with a dot, and rewrites the module specifiers in each `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`, `.cjs` and `.jsx` file in place. It changes nothing else in a file, prints each file it changed, and a second run changes nothing.
7
+ * The project root defaults to the working directory. The script walks it, skipping `node_modules`, `dist`, `build`, directories whose name starts with a dot and, in a git repository, the files and folders git ignores, unless git ignores the project root itself, and rewrites the module specifiers in each `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`, `.cjs` and `.jsx` file in place. It changes nothing else in a file, prints each file it changed, and a second run changes nothing.
8
8
  */
9
+ import { spawnSync } from 'node:child_process';
9
10
  import { readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
10
- import { join, relative, resolve } from 'node:path';
11
+ import { join, relative, resolve, sep } from 'node:path';
11
12
  import { pathToFileURL } from 'node:url';
12
13
 
13
14
  const AUDIENCE: 'app' | 'extension' = 'app';
@@ -637,20 +638,41 @@ export function rewrite(source: string): string {
637
638
  const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
638
639
  const SOURCE_FILE = /\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;
639
640
 
640
- function* sourceFiles(dir: string): Generator<string> {
641
+ /** A test of whether git ignores a file or folder under `root`. Outside a git repository it ignores nothing, and so it does when git ignores `root` itself, which the user then named on purpose. */
642
+ function gitIgnores(root: string): (path: string) => boolean {
643
+ const listed = spawnSync(
644
+ 'git',
645
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
646
+ { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 30 },
647
+ );
648
+ if (listed.status !== 0) return () => false;
649
+ const ignored = new Set(
650
+ listed.stdout
651
+ .split('\0')
652
+ .filter((path) => path !== '')
653
+ .map((path) => path.replace(/\/$/, '')),
654
+ );
655
+ if (ignored.has('.')) return () => false;
656
+ const bases = [root, realpathSync(root)];
657
+ return (path) => bases.some((base) => ignored.has(relative(base, path).split(sep).join('/')));
658
+ }
659
+
660
+ function* sourceFiles(dir: string, ignored: (path: string) => boolean): Generator<string> {
641
661
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
662
+ const path = join(dir, entry.name);
663
+ if (ignored(path)) continue;
642
664
  if (entry.isDirectory()) {
643
665
  if (SKIPPED_DIRECTORIES.has(entry.name) || entry.name.startsWith('.')) continue;
644
- yield* sourceFiles(join(dir, entry.name));
666
+ yield* sourceFiles(path, ignored);
645
667
  } else if (entry.isFile() && SOURCE_FILE.test(entry.name)) {
646
- yield join(dir, entry.name);
668
+ yield path;
647
669
  }
648
670
  }
649
671
  }
650
672
 
651
673
  function main(): void {
652
674
  const root = resolve(process.argv[2] ?? process.cwd());
653
- for (const file of sourceFiles(root)) {
675
+ for (const file of sourceFiles(root, gitIgnores(root))) {
654
676
  const source = readFileSync(file, 'utf8');
655
677
  const rewritten = rewrite(source);
656
678
  if (rewritten === source) continue;