@prisma/orm-mongo 8.0.1-dev.42 → 8.0.1-dev.44

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 (22) hide show
  1. package/dist/{mongo-static-DXv-zWOu-FTCkjjZe.mjs → mongo-static-Dudm8H_X-DUUqqcta.mjs} +3 -3
  2. package/dist/{mongo-static-DXv-zWOu-FTCkjjZe.mjs.map → mongo-static-Dudm8H_X-DUUqqcta.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 +1 -1
  8. package/skills/prisma-8/references/contract.md +1 -1
  9. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +129 -36
  10. 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 +86 -9
  11. 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
  12. 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
  13. 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
  14. 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
  15. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +100 -0
  16. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +29 -15
  17. 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 +86 -9
  18. 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
  19. 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
  20. 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
  21. 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
  22. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +56 -0
@@ -6,7 +6,7 @@
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
  *
@@ -18,6 +18,7 @@
18
18
  *
19
19
  * 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
20
  */
21
+ import { spawnSync } from 'node:child_process';
21
22
  import { createHash } from 'node:crypto';
22
23
  import {
23
24
  chmodSync,
@@ -1145,6 +1146,79 @@ function isWalked(name: string): boolean {
1145
1146
  return !SKIPPED_DIRECTORIES.has(name) && !name.startsWith('.');
1146
1147
  }
1147
1148
 
1149
+ let ignoredByGit: (path: string) => boolean = () => false;
1150
+
1151
+ /** 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. */
1152
+ function gitIgnores(root: string): (path: string) => boolean {
1153
+ const listed = spawnSync(
1154
+ 'git',
1155
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
1156
+ { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 30 },
1157
+ );
1158
+ if (listed.status !== 0) return () => false;
1159
+ const ignored = new Set(
1160
+ listed.stdout
1161
+ .split('\0')
1162
+ .filter((path) => path !== '')
1163
+ .map((path) => path.replace(/\/$/, '')),
1164
+ );
1165
+ if (ignored.has('.')) return () => false;
1166
+ const bases = [root, realpathSync(root)];
1167
+ return (path) =>
1168
+ bases.some((base) => ignored.has(relative(base, path).split(sep).join('/'))) &&
1169
+ !isInMigrationsFolder(bases, path);
1170
+ }
1171
+
1172
+ function readsAsRef(path: string): boolean {
1173
+ try {
1174
+ const value: unknown = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
1175
+ return isRecord(value) && hasRefContent(value);
1176
+ } catch {
1177
+ return false;
1178
+ }
1179
+ }
1180
+
1181
+ /** 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. */
1182
+ function holdsMigrationFiles(dir: string): boolean {
1183
+ return isMigrationsDirectory(dir) || holdsRef(dir);
1184
+ }
1185
+
1186
+ function holdsRef(dir: string): boolean {
1187
+ const refs = join(dir, 'refs');
1188
+ const entries = listDirectory(refs);
1189
+ return (
1190
+ typeof entries !== 'string' &&
1191
+ entries.some((entry) => entry.isFile() && readsAsRef(join(refs, entry.name)))
1192
+ );
1193
+ }
1194
+
1195
+ /** 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. */
1196
+ function holdsSpaceFiles(dir: string): boolean {
1197
+ return hasSubdirectory(dir, isMigrationPackage) || holdsRef(dir);
1198
+ }
1199
+
1200
+ function isMigrationsFolder(dir: string): boolean {
1201
+ return (
1202
+ holdsMigrationFiles(dir) ||
1203
+ hasSubdirectory(dir, (path, name) => SPACE_ID.test(name) && holdsSpaceFiles(path))
1204
+ );
1205
+ }
1206
+
1207
+ /** 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. */
1208
+ function isInMigrationsFolder(bases: readonly string[], path: string): boolean {
1209
+ for (let dir = path; !bases.includes(dir) && dir !== dirname(dir); dir = dirname(dir))
1210
+ if (isDirectory(dir) && isMigrationsFolder(dir)) return true;
1211
+ return false;
1212
+ }
1213
+
1214
+ /** Whether the walk from `realRoot` reaches `target`. */
1215
+ function isReached(realRoot: string, target: string): boolean {
1216
+ const names = relative(realRoot, target).split(sep);
1217
+ return names.every(
1218
+ (name, index) => isWalked(name) && !ignoredByGit(join(realRoot, ...names.slice(0, index + 1))),
1219
+ );
1220
+ }
1221
+
1148
1222
  function isInside(dir: string, path: string): boolean {
1149
1223
  return path === dir || path.startsWith(`${dir}${sep}`);
1150
1224
  }
@@ -1164,12 +1238,16 @@ function visit(
1164
1238
  for (const entry of entries) {
1165
1239
  const path = join(dir, entry.name);
1166
1240
  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)) {
1241
+ const isLeftover = entry.isDirectory()
1242
+ ? entry.name.startsWith('.') && entry.name.endsWith(REMOVED_SUFFIX)
1243
+ : entry.isFile() && entry.name.endsWith(TEMPORARY_SUFFIX);
1244
+ if (isLeftover) {
1172
1245
  files.leftovers.push(path);
1246
+ continue;
1247
+ }
1248
+ if (ignoredByGit(path)) continue;
1249
+ if (entry.isDirectory()) {
1250
+ if (isWalked(entry.name)) visit(root, path, files, stops, checkLinks);
1173
1251
  } else if (entry.isFile() && entry.name.endsWith('.json')) {
1174
1252
  classify(root, path, files, stops, shown);
1175
1253
  } else if (entry.isFile() && entry.name === 'migration.ts' && isMigrationPackage(dir)) {
@@ -1196,9 +1274,7 @@ function checkLink(root: string, path: string, name: string, stops: string[]): v
1196
1274
  }
1197
1275
  if (isInside(target, realRoot)) return;
1198
1276
  const inside = isInside(realRoot, target);
1199
- const reached =
1200
- relative(realRoot, target).split(sep).every(isWalked) &&
1201
- (isDirectory(target) || target.endsWith('.json'));
1277
+ const reached = isReached(realRoot, target) && (isDirectory(target) || target.endsWith('.json'));
1202
1278
  const intoSnapshot = inside && isInSnapshotDirectory(realRoot, target);
1203
1279
  const reading = inside && reached ? linkReading(root, path, realRoot, target, name) : undefined;
1204
1280
  if (reading === 'snapshot') {
@@ -1666,6 +1742,7 @@ function main(args: readonly string[]): number {
1666
1742
  process.stderr.write(`${root}: not a directory\n`);
1667
1743
  return 1;
1668
1744
  }
1745
+ ignoredByGit = gitIgnores(root);
1669
1746
  const shown = (path: string) => relative(root, path).split(sep).join('/');
1670
1747
  const files = emptyFiles();
1671
1748
  const stops: string[] = [];
@@ -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 { 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. Either install TypeScript 5 in the project for the run, for example with \`pnpm add -D typescript@5\`, and put your version back afterwards; or install \`typescript@5\` in an empty folder, copy this script into that folder, and run the copy with the project folder as its argument: \`node <folder>/<script>.ts <project folder>\`.`,
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;
@@ -4,11 +4,12 @@
4
4
  *
5
5
  * Usage: node platform-paths-an-extension-uses.ts [project-root]
6
6
  *
7
- * The script reads each file with the TypeScript compiler of the project, so the project needs its `typescript` package installed. 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 each `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`, `.cjs` and `.jsx` file in place. It prints each file it changed, then, under `Not changed:`, each import it could not rewrite and each place it wants checked. 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. A second run changes nothing.
7
+ * The script reads each file with the TypeScript compiler of the project, so the project needs its `typescript` package installed. 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 each `.ts`, `.mts`, `.cts`, `.tsx`, `.js`, `.mjs`, `.cjs` and `.jsx` file in place. It prints each file it changed, then, under `Not changed:`, each import it could not rewrite and each place it wants checked. 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. 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
11
  import { createRequire } from 'node:module';
11
- import { join, relative, resolve } from 'node:path';
12
+ import { join, relative, resolve, sep } from 'node:path';
12
13
  import { fileURLToPath, pathToFileURL } from 'node:url';
13
14
  import type * as TS from 'typescript';
14
15
 
@@ -1800,7 +1801,7 @@ export function rewriteWith(
1800
1801
  host,
1801
1802
  });
1802
1803
  if (program.getSourceFile(file.fileName) !== file)
1803
- throw new Error(
1804
+ throw new ScriptStop(
1804
1805
  `TypeScript did not take in ${fileName}, so the script cannot tell a local binding from an import there.`,
1805
1806
  );
1806
1807
  const checker = program.getTypeChecker();
@@ -1917,28 +1918,86 @@ export function rewriteWith(
1917
1918
  return { source: result, left: [...new Set(left)] };
1918
1919
  }
1919
1920
 
1921
+ /** A stop the script expects, such as a missing `typescript`, as against a fault in the script. */
1922
+ class ScriptStop extends Error {}
1923
+
1924
+ function hasCompilerApi(module: unknown): module is TypeScript {
1925
+ return (
1926
+ typeof module === 'object' &&
1927
+ module !== null &&
1928
+ 'createProgram' in module &&
1929
+ typeof module.createProgram === 'function'
1930
+ );
1931
+ }
1932
+
1933
+ function versionOf(module: unknown): string {
1934
+ return typeof module === 'object' &&
1935
+ module !== null &&
1936
+ 'version' in module &&
1937
+ typeof module.version === 'string'
1938
+ ? module.version
1939
+ : 'unknown';
1940
+ }
1941
+
1920
1942
  /** TypeScript's compiler, from the project the script works on, or else from beside the script. */
1921
1943
  export function loadTypeScript(root: string): TypeScript {
1944
+ const withoutCompiler = new Set<string>();
1922
1945
  for (const from of [join(root, 'package.json'), fileURLToPath(import.meta.url)]) {
1946
+ let found: unknown;
1923
1947
  try {
1924
- return createRequire(from)('typescript');
1925
- } catch {}
1948
+ found = createRequire(from)('typescript');
1949
+ } catch {
1950
+ continue;
1951
+ }
1952
+ if (hasCompilerApi(found)) return found;
1953
+ withoutCompiler.add(versionOf(found));
1926
1954
  }
1927
- throw new Error(
1955
+ if (withoutCompiler.size > 0)
1956
+ throw new ScriptStop(
1957
+ `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. Either install TypeScript 5 in the project for the run, for example with \`pnpm add -D typescript@5\`, and put your version back afterwards; or install \`typescript@5\` in an empty folder, copy this script into that folder, and run the copy with the project folder as its argument: \`node <folder>/<script>.ts <project folder>\`.`,
1958
+ );
1959
+ throw new ScriptStop(
1928
1960
  'This script reads code 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.',
1929
1961
  );
1930
1962
  }
1931
1963
 
1964
+ function stopMessage(error: unknown): string {
1965
+ if (error instanceof ScriptStop) return `${error.message}\nThe script changed no file.`;
1966
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
1967
+ 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}`;
1968
+ }
1969
+
1932
1970
  const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
1933
1971
  const SOURCE_FILE = /\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;
1934
1972
 
1935
- function* sourceFiles(dir: string): Generator<string> {
1973
+ /** 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. */
1974
+ function gitIgnores(root: string): (path: string) => boolean {
1975
+ const listed = spawnSync(
1976
+ 'git',
1977
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
1978
+ { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 30 },
1979
+ );
1980
+ if (listed.status !== 0) return () => false;
1981
+ const ignored = new Set(
1982
+ listed.stdout
1983
+ .split('\0')
1984
+ .filter((path) => path !== '')
1985
+ .map((path) => path.replace(/\/$/, '')),
1986
+ );
1987
+ if (ignored.has('.')) return () => false;
1988
+ const bases = [root, realpathSync(root)];
1989
+ return (path) => bases.some((base) => ignored.has(relative(base, path).split(sep).join('/')));
1990
+ }
1991
+
1992
+ function* sourceFiles(dir: string, ignored: (path: string) => boolean): Generator<string> {
1936
1993
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1994
+ const path = join(dir, entry.name);
1995
+ if (ignored(path)) continue;
1937
1996
  if (entry.isDirectory()) {
1938
1997
  if (SKIPPED_DIRECTORIES.has(entry.name) || entry.name.startsWith('.')) continue;
1939
- yield* sourceFiles(join(dir, entry.name));
1998
+ yield* sourceFiles(path, ignored);
1940
1999
  } else if (entry.isFile() && SOURCE_FILE.test(entry.name)) {
1941
- yield join(dir, entry.name);
2000
+ yield path;
1942
2001
  }
1943
2002
  }
1944
2003
  }
@@ -1950,16 +2009,14 @@ function main(): void {
1950
2009
  try {
1951
2010
  const ts = loadTypeScript(root);
1952
2011
  const database = databaseOf(root);
1953
- for (const file of sourceFiles(root)) {
2012
+ for (const file of sourceFiles(root, gitIgnores(root))) {
1954
2013
  const source = readFileSync(file, 'utf8');
1955
2014
  const { source: rewritten, left } = rewriteWith(ts, file, source, database);
1956
2015
  for (const entry of left) leftovers.push(`${relative(root, file)}: ${entry}`);
1957
2016
  if (rewritten !== source) changes.push([file, rewritten]);
1958
2017
  }
1959
2018
  } catch (error) {
1960
- console.error(
1961
- `${error instanceof Error ? error.message : String(error)}\nThe script changed no file.`,
1962
- );
2019
+ console.error(stopMessage(error));
1963
2020
  process.exitCode = 1;
1964
2021
  return;
1965
2022
  }