@prisma/orm-mongo 8.0.1-dev.5 → 8.0.1-dev.50

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 (215) hide show
  1. package/README.md +6 -5
  2. package/dist/bson.d.mts +2 -1
  3. package/dist/components__runtime.d.mts +3 -1
  4. package/dist/config.d.mts +2 -1
  5. package/dist/config.d.mts.map +1 -1
  6. package/dist/contract-builder.d.mts +11 -12
  7. package/dist/contract-builder.d.mts.map +1 -1
  8. package/dist/contract-types.d.mts +5 -3
  9. package/dist/contract__types.d.mts +3 -1
  10. package/dist/control.d.mts +2 -1
  11. package/dist/control.d.mts.map +1 -1
  12. package/dist/family-contract.d.mts +3 -1
  13. package/dist/family-runtime.d.mts +3 -1
  14. package/dist/family.d.mts +2 -1
  15. package/dist/family__control.d.mts +3 -1
  16. package/dist/init.d.mts +2 -1
  17. package/dist/init.d.mts.map +1 -1
  18. package/dist/migration-tools__aggregate.d.mts +3 -1
  19. package/dist/migration-tools__hash.d.mts +3 -1
  20. package/dist/migration-tools__io.d.mts +3 -1
  21. package/dist/migration-tools__spaces.d.mts +3 -1
  22. package/dist/migration.d.mts +3 -1
  23. package/dist/{mongo-static-CsA9y8_L-Bd252BaW.mjs → mongo-static-b_EkTdd5-xWveruVP.mjs} +4 -4
  24. package/dist/mongo-static-b_EkTdd5-xWveruVP.mjs.map +1 -0
  25. package/dist/orm.d.mts +3 -1
  26. package/dist/query-ast__execution.d.mts +3 -1
  27. package/dist/query-builder.d.mts +3 -1
  28. package/dist/runtime.d.mts +3 -1
  29. package/dist/runtime.d.mts.map +1 -1
  30. package/dist/runtime.mjs +6 -6
  31. package/dist/runtime.mjs.map +1 -1
  32. package/dist/static.d.mts +2 -1
  33. package/dist/static.d.mts.map +1 -1
  34. package/dist/static.mjs +1 -1
  35. package/dist/target.d.mts +2 -1
  36. package/dist/target__codec-ids.d.mts +3 -1
  37. package/dist/target__codec-types.d.mts +3 -1
  38. package/dist/target__migration.d.mts +3 -1
  39. package/dist/target__runtime.d.mts +2 -1
  40. package/dist/value.d.mts +3 -1
  41. package/dist/vite-plugin-contract-emit.d.mts +3 -1
  42. package/package.json +12 -81
  43. package/skills/prisma-8/SKILL.md +9 -9
  44. package/skills/prisma-8/references/contract.md +2 -2
  45. package/skills/prisma-8/references/debug.md +13 -13
  46. package/skills/prisma-8/references/migration-model.md +17 -17
  47. package/skills/prisma-8/references/migration-review.md +21 -21
  48. package/skills/prisma-8/references/migrations.md +58 -42
  49. package/skills/prisma-8/references/queries-mongo.md +9 -8
  50. package/skills/prisma-8/references/queries-postgres.md +59 -16
  51. package/skills/prisma-8/references/queries.md +2 -2
  52. package/skills/prisma-8/references/quickstart.md +11 -11
  53. package/skills/prisma-8/references/runtime.md +5 -5
  54. package/skills/prisma-8/references/scripts/find-detection-hits.ts +57 -0
  55. package/skills/prisma-8/references/upgrade-app.md +81 -24
  56. package/skills/prisma-8/references/upgrade-extension.md +57 -17
  57. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2482 -0
  58. 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 +2200 -0
  59. 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 +759 -0
  60. 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 +689 -0
  61. 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 +2053 -0
  62. 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 +671 -0
  63. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +102 -0
  64. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
  65. package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +2 -1
  66. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +1 -1
  67. package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/instructions.md +1 -1
  68. package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/instructions.md +1 -1
  69. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2057 -0
  70. 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 +2200 -0
  71. 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 +759 -0
  72. 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 +689 -0
  73. 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 +2053 -0
  74. 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 +671 -0
  75. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +56 -0
  76. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
  77. package/dist/adapter.d.mts +0 -1
  78. package/dist/adapter.mjs +0 -2
  79. package/dist/adapter__control.d.mts +0 -3
  80. package/dist/adapter__control.mjs +0 -3
  81. package/dist/adapter__runtime.d.mts +0 -3
  82. package/dist/adapter__runtime.mjs +0 -3
  83. package/dist/components.d.mts +0 -1
  84. package/dist/components.mjs +0 -2
  85. package/dist/components__authoring.d.mts +0 -1
  86. package/dist/components__authoring.mjs +0 -2
  87. package/dist/components__codec.d.mts +0 -1
  88. package/dist/components__codec.mjs +0 -2
  89. package/dist/components__components.d.mts +0 -1
  90. package/dist/components__components.mjs +0 -2
  91. package/dist/components__control.d.mts +0 -1
  92. package/dist/components__control.mjs +0 -2
  93. package/dist/components__emission.d.mts +0 -1
  94. package/dist/components__emission.mjs +0 -2
  95. package/dist/components__execution.d.mts +0 -1
  96. package/dist/components__execution.mjs +0 -2
  97. package/dist/components__ir.d.mts +0 -1
  98. package/dist/components__ir.mjs +0 -2
  99. package/dist/components__psl-ast.d.mts +0 -1
  100. package/dist/components__psl-ast.mjs +0 -2
  101. package/dist/components__utils.d.mts +0 -1
  102. package/dist/components__utils.mjs +0 -2
  103. package/dist/contract.d.mts +0 -1
  104. package/dist/contract.mjs +0 -2
  105. package/dist/contract__apply-specifier-default-control-policy.d.mts +0 -1
  106. package/dist/contract__apply-specifier-default-control-policy.mjs +0 -2
  107. package/dist/contract__contract-validation-error.d.mts +0 -1
  108. package/dist/contract__contract-validation-error.mjs +0 -2
  109. package/dist/contract__default-namespace.d.mts +0 -1
  110. package/dist/contract__default-namespace.mjs +0 -2
  111. package/dist/contract__enum-accessor.d.mts +0 -1
  112. package/dist/contract__enum-accessor.mjs +0 -2
  113. package/dist/contract__format-version.d.mts +0 -1
  114. package/dist/contract__format-version.mjs +0 -2
  115. package/dist/contract__hashing-utils.d.mts +0 -1
  116. package/dist/contract__hashing-utils.mjs +0 -2
  117. package/dist/contract__hashing.d.mts +0 -1
  118. package/dist/contract__hashing.mjs +0 -2
  119. package/dist/contract__internal__format-version.d.mts +0 -1
  120. package/dist/contract__internal__format-version.mjs +0 -2
  121. package/dist/contract__is-plain-record.d.mts +0 -1
  122. package/dist/contract__is-plain-record.mjs +0 -2
  123. package/dist/contract__resolve-domain-model.d.mts +0 -1
  124. package/dist/contract__resolve-domain-model.mjs +0 -2
  125. package/dist/contract__validate-domain.d.mts +0 -1
  126. package/dist/contract__validate-domain.mjs +0 -2
  127. package/dist/contract__validate-once.d.mts +0 -1
  128. package/dist/contract__validate-once.mjs +0 -2
  129. package/dist/contract__validate-storage.d.mts +0 -1
  130. package/dist/contract__validate-storage.mjs +0 -2
  131. package/dist/driver.d.mts +0 -1
  132. package/dist/driver.mjs +0 -2
  133. package/dist/driver__control.d.mts +0 -3
  134. package/dist/driver__control.mjs +0 -3
  135. package/dist/driver__runtime.d.mts +0 -3
  136. package/dist/driver__runtime.mjs +0 -3
  137. package/dist/family-contract__data-type.d.mts +0 -1
  138. package/dist/family-contract__data-type.mjs +0 -2
  139. package/dist/family-contract__entity-kinds.d.mts +0 -1
  140. package/dist/family-contract__entity-kinds.mjs +0 -2
  141. package/dist/family-contract__normal-form.d.mts +0 -1
  142. package/dist/family-contract__normal-form.mjs +0 -2
  143. package/dist/family__control-adapter.d.mts +0 -1
  144. package/dist/family__control-adapter.mjs +0 -2
  145. package/dist/family__ir.d.mts +0 -1
  146. package/dist/family__ir.mjs +0 -2
  147. package/dist/family__migration.d.mts +0 -1
  148. package/dist/family__migration.mjs +0 -2
  149. package/dist/family__pack.d.mts +0 -3
  150. package/dist/family__pack.mjs +0 -3
  151. package/dist/family__runtime.d.mts +0 -1
  152. package/dist/family__runtime.mjs +0 -2
  153. package/dist/family__schema-verify.d.mts +0 -1
  154. package/dist/family__schema-verify.mjs +0 -2
  155. package/dist/migration-tools__contract-snapshot-store.d.mts +0 -1
  156. package/dist/migration-tools__contract-snapshot-store.mjs +0 -2
  157. package/dist/mongo-static-CsA9y8_L-Bd252BaW.mjs.map +0 -1
  158. package/dist/query-ast.d.mts +0 -1
  159. package/dist/query-ast.mjs +0 -2
  160. package/dist/query-ast__control.d.mts +0 -1
  161. package/dist/query-ast__control.mjs +0 -2
  162. package/dist/query-builder__contract-free.d.mts +0 -1
  163. package/dist/query-builder__contract-free.mjs +0 -2
  164. package/dist/target__codecs.d.mts +0 -1
  165. package/dist/target__codecs.mjs +0 -2
  166. package/dist/target__control.d.mts +0 -1
  167. package/dist/target__control.mjs +0 -2
  168. package/dist/target__data-types.d.mts +0 -1
  169. package/dist/target__data-types.mjs +0 -2
  170. package/dist/target__pack.d.mts +0 -3
  171. package/dist/target__pack.mjs +0 -3
  172. package/dist/target__server-version.d.mts +0 -1
  173. package/dist/target__server-version.mjs +0 -2
  174. package/dist/utils.d.mts +0 -1
  175. package/dist/utils.mjs +0 -2
  176. package/dist/utils__abortable.d.mts +0 -1
  177. package/dist/utils__abortable.mjs +0 -2
  178. package/dist/utils__array-equal.d.mts +0 -1
  179. package/dist/utils__array-equal.mjs +0 -2
  180. package/dist/utils__assertions.d.mts +0 -1
  181. package/dist/utils__assertions.mjs +0 -2
  182. package/dist/utils__canonical-stringify.d.mts +0 -1
  183. package/dist/utils__canonical-stringify.mjs +0 -2
  184. package/dist/utils__casts.d.mts +0 -1
  185. package/dist/utils__casts.mjs +0 -2
  186. package/dist/utils__defined.d.mts +0 -1
  187. package/dist/utils__defined.mjs +0 -2
  188. package/dist/utils__guards.d.mts +0 -1
  189. package/dist/utils__guards.mjs +0 -2
  190. package/dist/utils__hash-content.d.mts +0 -1
  191. package/dist/utils__hash-content.mjs +0 -2
  192. package/dist/utils__internal-error.d.mts +0 -1
  193. package/dist/utils__internal-error.mjs +0 -2
  194. package/dist/utils__json.d.mts +0 -1
  195. package/dist/utils__json.mjs +0 -2
  196. package/dist/utils__promise.d.mts +0 -1
  197. package/dist/utils__promise.mjs +0 -2
  198. package/dist/utils__redact-db-url.d.mts +0 -1
  199. package/dist/utils__redact-db-url.mjs +0 -2
  200. package/dist/utils__result.d.mts +0 -1
  201. package/dist/utils__result.mjs +0 -2
  202. package/dist/utils__simplify-deep.d.mts +0 -1
  203. package/dist/utils__simplify-deep.mjs +0 -2
  204. package/dist/utils__structured-error.d.mts +0 -1
  205. package/dist/utils__structured-error.mjs +0 -2
  206. package/dist/utils__suppress-idle-connection-errors.d.mts +0 -1
  207. package/dist/utils__suppress-idle-connection-errors.mjs +0 -2
  208. package/dist/utils__text.d.mts +0 -1
  209. package/dist/utils__text.mjs +0 -2
  210. package/dist/utils__types.d.mts +0 -1
  211. package/dist/utils__types.mjs +0 -2
  212. package/dist/utils__upgrade-guides.d.mts +0 -1
  213. package/dist/utils__upgrade-guides.mjs +0 -2
  214. package/dist/value__mongodb-types.d.mts +0 -1
  215. package/dist/value__mongodb-types.mjs +0 -2
@@ -0,0 +1,759 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Renames what Prisma called the contract "marker" to its new name, the contract signature, in a project's code, scripts and CI files.
4
+ *
5
+ * Usage: node contract-signature-names.ts [project-root]
6
+ *
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
+ *
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
+ * - in code, the values `'orphanMarker'`, `'markerChanged'` and `'marker-verification'`, written as strings, which only Prisma's errors and logs carry;
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
+ * - 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
+ * - 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
+ *
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
+ *
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.
19
+ *
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.
21
+ */
22
+ import { spawnSync } from 'node:child_process';
23
+ import { readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
24
+ import { createRequire } from 'node:module';
25
+ import { basename, join, relative, resolve, sep } from 'node:path';
26
+ import { fileURLToPath, pathToFileURL } from 'node:url';
27
+ import type * as TS from 'typescript';
28
+
29
+ type TypeScript = typeof TS;
30
+
31
+ /** Each renamed error code; two old codes for one condition share their new one. `CONTRACT.MARKER_REQUIRED` and `CONFIG.FAMILY_READ_MARKER_REQUIRED` are gone, with no replacement. */
32
+ export const CODES: Readonly<Record<string, string>> = {
33
+ 'CONTRACT.MARKER_MISMATCH': 'CONTRACT.SIGNATURE_MISMATCH',
34
+ 'CONTRACT.MARKER_MISSING': 'CONTRACT.SIGNATURE_MISSING',
35
+ 'CONTRACT.MARKER_READ_FAILED': 'CONTRACT.SIGNATURE_READ_FAILED',
36
+ 'CONTRACT.MARKER_ROW_CORRUPT': 'CONTRACT.SIGNATURE_ROW_CORRUPT',
37
+ 'MIGRATION.MARKER_CAS_FAILURE': 'MIGRATION.CONCURRENT_CHANGE',
38
+ 'MIGRATION.MARKER_LOCK_TIMEOUT': 'MIGRATION.SIGNATURE_LOCK_TIMEOUT',
39
+ 'MIGRATION.MARKER_MISMATCH': 'MIGRATION.SIGNATURE_NOT_IN_GRAPH',
40
+ 'MIGRATION.MARKER_NOT_IN_HISTORY': 'MIGRATION.SIGNATURE_NOT_IN_GRAPH',
41
+ 'MIGRATION.MARKER_ORIGIN_MISMATCH': 'MIGRATION.SIGNATURE_ORIGIN_MISMATCH',
42
+ };
43
+
44
+ /** String values only Prisma's errors and logs carry: a violation's `kind`, a failure's `reason`, and the scope of the client's warnings. */
45
+ export const VALUES: Readonly<Record<string, string>> = {
46
+ orphanMarker: 'orphanSignature',
47
+ markerChanged: 'signatureChanged',
48
+ 'marker-verification': 'contract-signature-verification',
49
+ };
50
+
51
+ /** Each published path that was renamed. */
52
+ export const PATHS: Readonly<Record<string, string>> = {
53
+ '@prisma/orm-target-mysql/target/marker-lock': '@prisma/orm-target-mysql/target/signature-lock',
54
+ };
55
+
56
+ /** Each name an `@prisma/orm-*` package exports that was renamed: renamed where a file imports it. */
57
+ export const EXPORTS: Readonly<Record<string, string>> = {
58
+ acquireMarkerLock: 'acquireSignatureLock',
59
+ buildSignMarkerBootstrapQueries: 'buildSignBootstrapQueries',
60
+ contractHashAtMarker: 'contractHashAtSignature',
61
+ ContractMarkerRecord: 'ContractSignatureRecord',
62
+ ContractMarkerRecordLike: 'ContractSignatureRecordLike',
63
+ ContractMarkerRow: 'ContractSignatureRow',
64
+ errorHashMismatch: 'errorSignatureMismatch',
65
+ errorMarkerMissing: 'errorSignatureMissing',
66
+ errorMarkerReadFailed: 'errorSignatureReadFailed',
67
+ errorMarkerRowCorrupt: 'errorSignatureRowCorrupt',
68
+ MARKER_LOCK_TIMEOUT_SECONDS: 'SIGNATURE_LOCK_TIMEOUT_SECONDS',
69
+ MarkerCheckResult: 'ContractSignatureCheckResult',
70
+ MarkerCheckSection: 'ContractSignatureCheckSection',
71
+ MarkerDestination: 'ContractSignatureDestination',
72
+ MarkerHashes: 'ContractSignatureHashes',
73
+ MarkerInsert: 'ContractSignatureInsert',
74
+ MarkerOperations: 'ContractSignatureOperations',
75
+ MarkerReader: 'ContractSignatureReader',
76
+ MarkerReadResult: 'ContractSignatureReadResult',
77
+ markerSwapFailure: 'signatureSwapFailure',
78
+ MarkerSwapFailure: 'ContractSignatureSwapFailure',
79
+ parseContractMarkerRow: 'parseContractSignatureRow',
80
+ parseMarkerRowSafely: 'parseSignatureRowSafely',
81
+ releaseMarkerLock: 'releaseSignatureLock',
82
+ rethrowMarkerReadError: 'rethrowSignatureReadError',
83
+ sameMarkerHashes: 'sameContractSignatureHashes',
84
+ SpaceMarkerConflict: 'SpaceSignConflict',
85
+ SpaceMarkerHashConflict: 'SpaceSignatureHashConflict',
86
+ SpaceMarkerRecord: 'SpaceSignatureRecord',
87
+ SpaceSignature: 'SpaceSignOutcome',
88
+ VERIFY_CODE_HASH_MISMATCH: 'VERIFY_CODE_SIGNATURE_MISMATCH',
89
+ VERIFY_CODE_MARKER_MISSING: 'VERIFY_CODE_SIGNATURE_MISSING',
90
+ VerifyMarkerOption: 'VerifyContractSignatureOption',
91
+ withMarkerLock: 'withSignatureLock',
92
+ withMarkerReadErrorHandling: 'withSignatureReadErrorHandling',
93
+ };
94
+
95
+ /** Each member of a published interface or options object that was renamed: a method, a property or a client option. */
96
+ export const MEMBERS: Readonly<Record<string, string>> = {
97
+ bootstrapSignMarkerQueries: 'bootstrapSignQueries',
98
+ currentMarker: 'currentSignature',
99
+ currentMarkerHash: 'currentSignatureHash',
100
+ currentMarkerInvariants: 'currentSignatureInvariants',
101
+ currentMarkerStorageHash: 'currentSignatureStorageHash',
102
+ databaseMarkerHashBySpace: 'databaseSignatureHashBySpace',
103
+ holdMarkerLock: 'holdSignatureLock',
104
+ initMarker: 'initSignature',
105
+ insertMarker: 'insertSignature',
106
+ lockMarker: 'lockSignature',
107
+ markerCheck: 'signatureCheck',
108
+ markerDrift: 'signatureDrift',
109
+ markerHash: 'signatureHash',
110
+ markerInvariants: 'signatureInvariants',
111
+ markerLocation: 'signatureLocation',
112
+ markerOps: 'signatureOps',
113
+ markerReader: 'signatureReader',
114
+ markerRowsBySpace: 'signatureRowsBySpace',
115
+ markersBySpaceId: 'signaturesBySpaceId',
116
+ orphanMarkers: 'orphanSignatures',
117
+ readAllMarkers: 'readAllSignatures',
118
+ readMarker: 'readSignature',
119
+ readMarkerDiscriminated: 'readSignatureDiscriminated',
120
+ skipMarker: 'skipSignature',
121
+ updateMarker: 'updateSignature',
122
+ verifyMarker: 'verifyContractSignature',
123
+ };
124
+
125
+ /** The fields of `--json` output that were renamed. */
126
+ export const JSON_FIELDS: Readonly<Record<string, string>> = {
127
+ marker: 'signature',
128
+ markerHash: 'signatureHash',
129
+ };
130
+
131
+ const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
+ const alternation = (names: readonly string[]): string =>
133
+ [...names]
134
+ .sort((a, b) => b.length - a.length)
135
+ .map(escapeRegExp)
136
+ .join('|');
137
+ const IDENTIFIER = '[A-Za-z_$][\\w$]*';
138
+
139
+ const CODE = new RegExp(`(?<![\\w.])(?:${alternation(Object.keys(CODES))})(?![\\w])`, 'g');
140
+ const QUOTED_VALUE = new RegExp(`(['"\`])(${alternation(Object.keys(VALUES))})\\1`, 'g');
141
+ const PATH = new RegExp(`${alternation(Object.keys(PATHS))}(?![\\w/-])`, 'g');
142
+ const FLAG = /(?<![\w-])--marker-only(?![\w-])/g;
143
+ const PRISMA_MODULE = /^@prisma\/orm-[a-z0-9-]+(?:\/[\w./-]*)?$/;
144
+ const IMPORTS_PRISMA =
145
+ /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*)['"`]@prisma\/orm-[a-z0-9-]+/;
146
+ const RUNS_JSON =
147
+ /(?:\bdb\s+(?:verify|init|update|migrate)\b|['"`]db['"`]\s*,\s*['"`](?:verify|init|update|migrate)['"`])[\s\S]*--json|--json[\s\S]*(?:\bdb\s+(?:verify|init|update|migrate)\b|['"`]db['"`]\s*,\s*['"`](?:verify|init|update|migrate)['"`])/;
148
+
149
+ interface Edit {
150
+ readonly at: number;
151
+ readonly length: number;
152
+ readonly text: string;
153
+ }
154
+
155
+ function applyEdits(source: string, edits: readonly Edit[]): string {
156
+ const sorted = [...edits].sort((a, b) => b.at - a.at);
157
+ let text = source;
158
+ let limit = Number.POSITIVE_INFINITY;
159
+ for (const edit of sorted) {
160
+ if (edit.at + edit.length > limit) continue;
161
+ text = `${text.slice(0, edit.at)}${edit.text}${text.slice(edit.at + edit.length)}`;
162
+ limit = edit.at;
163
+ }
164
+ return text;
165
+ }
166
+
167
+ /** The source with each comment and the inside of each string replaced by spaces, so positions stay the same and only code is searched. */
168
+ function codeOnly(source: string): string {
169
+ const out = source.split('');
170
+ let i = 0;
171
+ const blank = (from: number, to: number) => {
172
+ for (let j = from; j < to; j++) if (out[j] !== '\n') out[j] = ' ';
173
+ };
174
+ while (i < source.length) {
175
+ const char = source[i];
176
+ if (char === '/' && source[i + 1] === '/') {
177
+ const end = source.indexOf('\n', i);
178
+ const stop = end === -1 ? source.length : end;
179
+ blank(i, stop);
180
+ i = stop;
181
+ } else if (char === '/' && source[i + 1] === '*') {
182
+ const end = source.indexOf('*/', i + 2);
183
+ const stop = end === -1 ? source.length : end + 2;
184
+ blank(i, stop);
185
+ i = stop;
186
+ } else if (char === "'" || char === '"') {
187
+ let j = i + 1;
188
+ while (j < source.length && source[j] !== char) j += source[j] === '\\' ? 2 : 1;
189
+ blank(i + 1, j);
190
+ i = j + 1;
191
+ } else if (char === '`') {
192
+ // A template's text is blanked; each `${…}` in it is code.
193
+ let j = i + 1;
194
+ let from = j;
195
+ while (j < source.length && source[j] !== '`') {
196
+ if (source[j] === '\\') {
197
+ j += 2;
198
+ } else if (source[j] === '$' && source[j + 1] === '{') {
199
+ blank(from, j);
200
+ const end = interpolationEnd(source, j + 2);
201
+ const inner = codeOnly(source.slice(j + 2, end));
202
+ for (let k = 0; k < inner.length; k++) out[j + 2 + k] = inner[k] ?? ' ';
203
+ j = end + 1;
204
+ from = j;
205
+ } else {
206
+ j++;
207
+ }
208
+ }
209
+ blank(from, j);
210
+ i = j + 1;
211
+ } else {
212
+ i++;
213
+ }
214
+ }
215
+ return out.join('');
216
+ }
217
+
218
+ /** The position of the `}` that closes a template interpolation whose expression starts at `from`. */
219
+ function interpolationEnd(source: string, from: number): number {
220
+ let depth = 0;
221
+ for (let i = from; i < source.length; i++) {
222
+ const char = source[i];
223
+ if (char === "'" || char === '"' || char === '`') {
224
+ let j = i + 1;
225
+ while (j < source.length && source[j] !== char) j += source[j] === '\\' ? 2 : 1;
226
+ i = j;
227
+ } else if (char === '{') depth++;
228
+ else if (char === '}') {
229
+ if (depth === 0) return i;
230
+ depth--;
231
+ }
232
+ }
233
+ return source.length;
234
+ }
235
+
236
+ /** The innermost bracket open at `at` in `code`, and its position. */
237
+ function enclosing(
238
+ code: string,
239
+ at: number,
240
+ ): { readonly bracket: string; readonly at: number } | undefined {
241
+ let depth = 0;
242
+ for (let i = at - 1; i >= 0; i--) {
243
+ const char = code[i];
244
+ if (char === ')' || char === ']' || char === '}') depth++;
245
+ else if (char === '(' || char === '[' || char === '{') {
246
+ if (depth === 0) return { bracket: char, at: i };
247
+ depth--;
248
+ }
249
+ }
250
+ return undefined;
251
+ }
252
+
253
+ /** The position just after the bracket that closes the one at `open`. */
254
+ function closing(code: string, open: number): number {
255
+ let depth = 0;
256
+ for (let i = open; i < code.length; i++) {
257
+ const char = code[i];
258
+ if (char === '(' || char === '[' || char === '{') depth++;
259
+ else if (char === ')' || char === ']' || char === '}') {
260
+ depth--;
261
+ if (depth === 0) return i + 1;
262
+ }
263
+ }
264
+ return code.length;
265
+ }
266
+
267
+ const before = (code: string, at: number): string => code.slice(0, at).replace(/\s+$/, '');
268
+ const MODIFIERS =
269
+ /(?:^|[\s;{},])(?:(?:public|private|protected|static|readonly|override|declare|abstract|async|get|set)\s+)+$/;
270
+
271
+ /** Whether the name at `at` is a key of an object written in braces: after `{` or `,`, inside braces. */
272
+ function isObjectKey(code: string, at: number): boolean {
273
+ return /[{,]$/.test(before(code, at)) && enclosing(code, at)?.bracket === '{';
274
+ }
275
+
276
+ /** Whether the brace at `open` opens the body of a class: the heading before it may hold brackets of its own, as in `class A extends Base<{ x: 1 }> {`. */
277
+ function opensClassBody(code: string, open: number): boolean {
278
+ const heading = /\bclass\b(?![\s\S]*\bclass\b)([\s\S]*)$/.exec(code.slice(0, open));
279
+ if (heading === null) return false;
280
+ const text = heading[1] ?? '';
281
+ let depth = 0;
282
+ let angles = 0;
283
+ for (let i = 0; i < text.length; i++) {
284
+ const char = text[i];
285
+ if (char === '<') angles++;
286
+ else if (char === '>' && text[i - 1] !== '=') angles--;
287
+ else if (char === '{' && depth === 0 && angles === 0) return false;
288
+ if (char === '(' || char === '[' || char === '{') depth++;
289
+ else if (char === ')' || char === ']' || char === '}') depth--;
290
+ else if (depth === 0 && char === ';') return false;
291
+ if (depth < 0 || angles < 0) return false;
292
+ }
293
+ return depth === 0 && angles === 0;
294
+ }
295
+
296
+ /** Whether the name at `at` declares a member of a class, an interface or an object: a field, a property or a method. In a class body, `name = …` is a field; elsewhere it is an assignment, and only a modifier makes it a declaration. */
297
+ function isMemberDeclaration(code: string, at: number, length: number): boolean {
298
+ const body = enclosing(code, at);
299
+ if (body?.bracket !== '{') return false;
300
+ const prefix = before(code, at);
301
+ const startsMember =
302
+ /(?:^|[{;},])$/.test(prefix) ||
303
+ /\n$/.test(code.slice(0, at).replace(/[ \t]+$/, '')) ||
304
+ MODIFIERS.test(code.slice(0, at));
305
+ if (!startsMember) return false;
306
+ const rest = code.slice(at + length);
307
+ if (/^\s*\??\s*:/.test(rest)) return true;
308
+ if (/^\s*=(?![=>])/.test(rest))
309
+ return MODIFIERS.test(code.slice(0, at)) || opensClassBody(code, body.at);
310
+ const call = /^\s*(?:<[^>]*>)?\s*\(/.exec(rest);
311
+ if (call === null) return false;
312
+ const open = at + length + call[0].length - 1;
313
+ return /^\s*(?::|\{)/.test(code.slice(closing(code, open)));
314
+ }
315
+
316
+ interface ImportUses {
317
+ /** The start of each use that refers to a binding of the file's own, such as a parameter, and not to the import of that name. */
318
+ readonly shadowed: ReadonlySet<number>;
319
+ /** The start of each use of the import written as a shorthand property, `{ name }`, whose key must keep the old name. */
320
+ readonly shorthand: ReadonlySet<number>;
321
+ }
322
+
323
+ function importUses(
324
+ ts: TypeScript,
325
+ fileName: string,
326
+ source: string,
327
+ names: ReadonlySet<string>,
328
+ ): ImportUses {
329
+ const kind = /\.(tsx|jsx)$/.test(fileName)
330
+ ? ts.ScriptKind.TSX
331
+ : /\.(js|mjs|cjs)$/.test(fileName)
332
+ ? ts.ScriptKind.JS
333
+ : ts.ScriptKind.TS;
334
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, kind);
335
+ const host = ts.createCompilerHost({});
336
+ host.getSourceFile = (name) => (name === file.fileName ? file : undefined);
337
+ host.fileExists = (name) => name === file.fileName;
338
+ const program = ts.createProgram({
339
+ rootNames: [file.fileName],
340
+ options: { noLib: true, noResolve: true, allowJs: true },
341
+ host,
342
+ });
343
+ if (program.getSourceFile(file.fileName) !== file)
344
+ throw new ScriptStop(
345
+ `TypeScript did not take in ${fileName}, so the script cannot tell a local binding from an import there.`,
346
+ );
347
+ const checker = program.getTypeChecker();
348
+ const imported = new Set<TS.Symbol | undefined>();
349
+ const uses: TS.Identifier[] = [];
350
+ const visit = (node: TS.Node): void => {
351
+ if (ts.isIdentifier(node) && names.has(node.text)) {
352
+ if (ts.isImportSpecifier(node.parent) || ts.isNamespaceImport(node.parent))
353
+ imported.add(checker.getSymbolAtLocation(node));
354
+ else uses.push(node);
355
+ }
356
+ ts.forEachChild(node, visit);
357
+ };
358
+ visit(file);
359
+ const shadowed = new Set<number>();
360
+ const shorthand = new Set<number>();
361
+ for (const node of uses) {
362
+ const parent = node.parent;
363
+ const isShorthand = ts.isShorthandPropertyAssignment(parent) && parent.name === node;
364
+ const symbol = isShorthand
365
+ ? checker.getShorthandAssignmentValueSymbol(parent)
366
+ : ts.isExportSpecifier(parent)
367
+ ? checker.getExportSpecifierLocalTargetSymbol(parent)
368
+ : checker.getSymbolAtLocation(node);
369
+ if (symbol !== undefined && !imported.has(symbol)) shadowed.add(node.getStart(file));
370
+ else if (isShorthand) shorthand.add(node.getStart(file));
371
+ }
372
+ return { shadowed, shorthand };
373
+ }
374
+
375
+ function renamedImports(
376
+ source: string,
377
+ code: string,
378
+ usesOf: (names: ReadonlySet<string>) => ImportUses,
379
+ ): Edit[] {
380
+ const edits: Edit[] = [];
381
+ const locals = new Map<string, string>();
382
+ const declarations: Array<readonly [number, number]> = [];
383
+ const statement =
384
+ /\b(import|export)(\s+type)?\s+(?:[\w$]+\s*,\s*)?\{([^}]*)\}\s*from\s*(['"])([^'"]+)\4/g;
385
+ for (const match of source.matchAll(statement)) {
386
+ if (!PRISMA_MODULE.test(match[5] ?? '')) continue;
387
+ const listAt = (match.index ?? 0) + match[0].indexOf('{') + 1;
388
+ declarations.push([match.index ?? 0, (match.index ?? 0) + match[0].length]);
389
+ const reexport = match[1] === 'export';
390
+ const specifier = new RegExp(
391
+ `(?<![\\w$])(?:type\\s+)?(${IDENTIFIER})(\\s+as\\s+${IDENTIFIER})?`,
392
+ 'g',
393
+ );
394
+ for (const entry of (match[3] ?? '').matchAll(specifier)) {
395
+ const name = entry[1] ?? '';
396
+ const now = EXPORTS[name];
397
+ if (now === undefined) continue;
398
+ const at =
399
+ listAt +
400
+ (entry.index ?? 0) +
401
+ entry[0].lastIndexOf(name, entry[0].length - (entry[2]?.length ?? 0));
402
+ const aliased = entry[2] !== undefined;
403
+ edits.push({
404
+ at,
405
+ length: name.length,
406
+ text: reexport && !aliased ? `${now} as ${name}` : now,
407
+ });
408
+ if (!reexport && !aliased) locals.set(name, now);
409
+ }
410
+ }
411
+ const namespaces = /\bimport\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s*(['"])([^'"]+)\2/g;
412
+ const spaces = [...source.matchAll(namespaces)]
413
+ .filter((match) => PRISMA_MODULE.test(match[3] ?? ''))
414
+ .map((match) => match[1] ?? '');
415
+ if (spaces.length > 0) {
416
+ const qualified = new RegExp(
417
+ `(?<![\\w$.])(?:${spaces.map(escapeRegExp).join('|')})\\s*\\.\\s*(${alternation(Object.keys(EXPORTS))})(?![\\w$])`,
418
+ 'g',
419
+ );
420
+ const matches = [...code.matchAll(qualified)];
421
+ const { shadowed } =
422
+ matches.length > 0 ? usesOf(new Set(spaces)) : { shadowed: new Set<number>() };
423
+ for (const match of matches) {
424
+ if (shadowed.has(match.index ?? 0)) continue;
425
+ const name = match[1] ?? '';
426
+ edits.push({
427
+ at: (match.index ?? 0) + match[0].length - name.length,
428
+ length: name.length,
429
+ text: EXPORTS[name] ?? name,
430
+ });
431
+ }
432
+ }
433
+ if (locals.size > 0) {
434
+ const localExports = [...code.matchAll(/\bexport(?:\s+type)?\s*\{[^}]*\}(?!\s*from\b)/g)].map(
435
+ (match) => [match.index ?? 0, (match.index ?? 0) + match[0].length] as const,
436
+ );
437
+ const uses = new RegExp(`(?<![\\w$.])(?:${alternation([...locals.keys()])})(?![\\w$])`, 'g');
438
+ const { shadowed, shorthand } = usesOf(new Set(locals.keys()));
439
+ for (const match of code.matchAll(uses)) {
440
+ const at = match.index ?? 0;
441
+ if (declarations.some(([from, to]) => at >= from && at < to)) continue;
442
+ if (shadowed.has(at)) continue;
443
+ const now = locals.get(match[0]) ?? match[0];
444
+ // `export { name }` keeps the name other files import; `export { name as other }` keeps its alias.
445
+ if (localExports.some(([from, to]) => at >= from && at < to)) {
446
+ // After `as` the name is the one the module exports, not a local.
447
+ if (/\bas\s+$/.test(code.slice(0, at))) continue;
448
+ const aliased = /^\s+as\s/.test(code.slice(at + match[0].length));
449
+ edits.push({ at, length: match[0].length, text: aliased ? now : `${now} as ${match[0]}` });
450
+ continue;
451
+ }
452
+ if (isObjectKey(code, at) && /^\s*:/.test(code.slice(at + match[0].length))) continue;
453
+ edits.push({
454
+ at,
455
+ length: match[0].length,
456
+ text: shorthand.has(at) ? `${match[0]}: ${now}` : now,
457
+ });
458
+ }
459
+ }
460
+ return edits;
461
+ }
462
+
463
+ const MEMBER_IN_TYPE = /(?:\b(?:Pick|Omit)\s*<[^;{}()]*|\[\s*)$/;
464
+
465
+ function renamedMembers(source: string, code: string): Edit[] {
466
+ const edits: Edit[] = [];
467
+ const quoted = new RegExp(`(['"])(${alternation(Object.keys(MEMBERS))})\\1`, 'g');
468
+ for (const match of source.matchAll(quoted)) {
469
+ const at = match.index ?? 0;
470
+ if (code[at] !== match[1] || !MEMBER_IN_TYPE.test(code.slice(0, at))) continue;
471
+ const name = match[2] ?? '';
472
+ edits.push({ at: at + 1, length: name.length, text: MEMBERS[name] ?? name });
473
+ }
474
+ const names = new RegExp(`(?<![\\w$])(${alternation(Object.keys(MEMBERS))})(?![\\w$])`, 'g');
475
+ for (const match of code.matchAll(names)) {
476
+ const at = match.index ?? 0;
477
+ const name = match[1] ?? '';
478
+ const read = /(?:\?\.|\.)\s*$/.test(code.slice(0, at)) && !/\.\.\.\s*$/.test(code.slice(0, at));
479
+ const key = isObjectKey(code, at) && /^\s*\??\s*:/.test(code.slice(at + name.length));
480
+ if (read || key || isMemberDeclaration(code, at, name.length))
481
+ edits.push({ at, length: name.length, text: MEMBERS[name] ?? name });
482
+ }
483
+ return edits;
484
+ }
485
+
486
+ /** Whether the name at `at`, followed by `rest`, is a key: of an object, a type literal or an interface (`{ marker: …`, `; markerHash?: string`, or a member on a line of its own). */
487
+ function isKey(code: string, at: number, rest: string): boolean {
488
+ if (enclosing(code, at)?.bracket !== '{') return false;
489
+ if (/[{,;]$/.test(before(code, at))) return /^\s*\??\s*:/.test(rest);
490
+ return (
491
+ /\n[ \t]*$/.test(code.slice(0, at)) &&
492
+ /[\w$)\]}>'"`]$/.test(before(code, at)) &&
493
+ /^[ \t]*\??[ \t]*:/.test(rest)
494
+ );
495
+ }
496
+
497
+ /** Whether `text` is a type annotation, `: T`, followed by `=`: the type may hold brackets of its own. */
498
+ function assignedAfterType(text: string): boolean {
499
+ const colon = /^\s*:/.exec(text);
500
+ if (colon === null) return false;
501
+ let depth = 0;
502
+ for (let i = colon[0].length; i < text.length; i++) {
503
+ const char = text[i];
504
+ if (char === '(' || char === '[' || char === '{' || char === '<') depth++;
505
+ else if (
506
+ char === ')' ||
507
+ char === ']' ||
508
+ char === '}' ||
509
+ (char === '>' && text[i - 1] !== '=')
510
+ ) {
511
+ if (depth === 0) return false;
512
+ depth--;
513
+ } else if (depth === 0 && (char === ';' || char === ',')) return false;
514
+ else if (depth === 0 && char === '=' && !/[=>]/.test(text[i + 1] ?? '')) return true;
515
+ }
516
+ return false;
517
+ }
518
+
519
+ /** Whether the braces at `open` destructure: `{ … } = …`, `{ … }: T = …`, or a parameter of an arrow function, a function or a method, `({ … }) =>` or `({ … }: T) {`. */
520
+ function isDestructuring(code: string, open: number): boolean {
521
+ const after = code.slice(closing(code, open));
522
+ if (/^\s*=(?![=>])/.test(after) || assignedAfterType(after)) return true;
523
+ const parameters = enclosing(code, open);
524
+ if (parameters?.bracket !== '(' || /=$/.test(before(code, open))) return false;
525
+ const afterParameters = code.slice(closing(code, parameters.at));
526
+ return /^\s*(?::[^=;{}]*)?=>/.test(afterParameters) || /^\s*(?::[^;{]*)?\{/.test(afterParameters);
527
+ }
528
+
529
+ function renamedJsonFields(source: string, code: string): Edit[] {
530
+ const edits: Edit[] = [];
531
+ const fields = new RegExp(`(?<![\\w$])(${alternation(Object.keys(JSON_FIELDS))})(?![\\w$])`, 'g');
532
+ for (const match of code.matchAll(fields)) {
533
+ const at = match.index ?? 0;
534
+ const name = match[1] ?? '';
535
+ const now = JSON_FIELDS[name] ?? name;
536
+ const prefix = code.slice(0, at);
537
+ const rest = code.slice(at + name.length);
538
+ if (/(?:\?\.|\.)\s*$/.test(prefix) && !/\.\.\.\s*$/.test(prefix)) {
539
+ edits.push({ at, length: name.length, text: now });
540
+ } else if (isKey(code, at, rest)) {
541
+ edits.push({ at, length: name.length, text: now });
542
+ } else if (isObjectKey(code, at) && /^\s*(?:[,}]|=(?![=>]))/.test(rest)) {
543
+ if (isDestructuring(code, enclosing(code, at)?.at ?? 0))
544
+ edits.push({ at, length: name.length, text: `${now}: ${name}` });
545
+ }
546
+ }
547
+ const quoted = /(['"])(marker(?:Hash)?|marker-only)\1/g;
548
+ for (const match of source.matchAll(quoted)) {
549
+ const value = match[2] ?? '';
550
+ const now = value === 'marker-only' ? 'signature-only' : (JSON_FIELDS[value] ?? value);
551
+ edits.push({ at: (match.index ?? 0) + 1, length: value.length, text: now });
552
+ }
553
+ return edits;
554
+ }
555
+
556
+ export function rewriteCode(ts: () => TypeScript, fileName: string, source: string): string {
557
+ const text = source
558
+ .replace(FLAG, '--signature-only')
559
+ .replace(CODE, (code) => CODES[code] ?? code)
560
+ .replace(PATH, (path) => PATHS[path] ?? path)
561
+ .replace(
562
+ QUOTED_VALUE,
563
+ (_, quote: string, value: string) => `${quote}${VALUES[value] ?? value}${quote}`,
564
+ );
565
+ const code = codeOnly(text);
566
+ const edits: Edit[] = [];
567
+ if (IMPORTS_PRISMA.test(text))
568
+ edits.push(
569
+ ...renamedImports(text, code, (names) => importUses(ts(), fileName, text, names)),
570
+ ...renamedMembers(text, code),
571
+ );
572
+ if (RUNS_JSON.test(text)) edits.push(...renamedJsonFields(text, code));
573
+ return applyEdits(text, edits);
574
+ }
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
+
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. */
582
+ export function rewriteScript(source: string): string {
583
+ return source
584
+ .replace(FLAG, '--signature-only')
585
+ .replace(CODE, (code) => CODES[code] ?? code)
586
+ .split('\n')
587
+ .map((line) =>
588
+ runsDbWithJson(line) ? line.replace(JSON_FIELD, (_, hash = '') => `.signature${hash}`) : line,
589
+ )
590
+ .join('\n');
591
+ }
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
+
611
+ const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build']);
612
+ const CI_DIRECTORIES = new Set(['.github', '.circleci', '.gitlab', '.buildkite']);
613
+ const CODE_FILE = /\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;
614
+ const MARKDOWN_FILE = /\.mdx?$/;
615
+ const SCRIPT_FILE =
616
+ /(^package\.json$|^Makefile$|^Dockerfile$|^justfile$|\.(sh|bash|zsh|ya?ml|toml|md|mdx)$)/;
617
+
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> {
638
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
639
+ const path = join(dir, entry.name);
640
+ if (ignored(path)) continue;
641
+ if (entry.isDirectory()) {
642
+ if (SKIPPED_DIRECTORIES.has(entry.name)) continue;
643
+ if (entry.name.startsWith('.') && !CI_DIRECTORIES.has(entry.name)) continue;
644
+ yield* files(path, ignored);
645
+ } else if (entry.isFile() && (CODE_FILE.test(entry.name) || SCRIPT_FILE.test(entry.name))) {
646
+ yield path;
647
+ }
648
+ }
649
+ }
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
+
672
+ /** TypeScript's compiler, from the project the script works on, or else from beside the script. */
673
+ export function loadTypeScript(root: string): TypeScript {
674
+ const withoutCompiler = new Set<string>();
675
+ for (const from of [join(root, 'package.json'), fileURLToPath(import.meta.url)]) {
676
+ let found: unknown;
677
+ try {
678
+ found = createRequire(from)('typescript');
679
+ } catch {
680
+ continue;
681
+ }
682
+ if (hasCompilerApi(found)) return found;
683
+ withoutCompiler.add(versionOf(found));
684
+ }
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(
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.',
691
+ );
692
+ }
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
+
700
+ function main(): void {
701
+ const root = resolve(process.argv[2] ?? process.cwd());
702
+ let typescript: TypeScript | undefined;
703
+ const ts = () => {
704
+ typescript ??= loadTypeScript(root);
705
+ return typescript;
706
+ };
707
+ const changes: Array<readonly [string, string]> = [];
708
+ const markdown: string[] = [];
709
+ try {
710
+ for (const file of files(root, gitIgnores(root))) {
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
+ }
717
+ const rewritten = CODE_FILE.test(file)
718
+ ? rewriteCode(ts, file, source)
719
+ : rewriteScript(source);
720
+ if (rewritten !== source) changes.push([file, rewritten]);
721
+ }
722
+ } catch (error) {
723
+ console.error(stopMessage(error));
724
+ process.exitCode = 1;
725
+ return;
726
+ }
727
+ let written = 0;
728
+ try {
729
+ for (const [file, rewritten] of changes) {
730
+ writeFileSync(file, rewritten);
731
+ written++;
732
+ console.log(relative(root, file));
733
+ }
734
+ } catch (error) {
735
+ console.error(
736
+ [
737
+ error instanceof Error ? error.message : String(error),
738
+ `The write to ${relative(root, changes[written]?.[0] ?? root)} failed, so that file may be partly written.`,
739
+ 'The script changed the files listed above, and none of these:',
740
+ ...changes.slice(written + 1).map(([file]) => ` ${relative(root, file)}`),
741
+ 'Fix the cause and run the script again, or restore the changed files from version control.',
742
+ ].join('\n'),
743
+ );
744
+ process.exitCode = 1;
745
+ return;
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}`);
752
+ }
753
+
754
+ // Node names the module by its real path, so a script reached through a symbolic link compares that.
755
+ if (
756
+ process.argv[1] !== undefined &&
757
+ import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href
758
+ )
759
+ main();