@venizia/dev-configs 0.5.0-1 → 0.5.0-10

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 (177) hide show
  1. package/README.md +18 -13
  2. package/dist/checks/purity/manifest.js +11 -3
  3. package/dist/checks/purity/manifest.js.map +1 -1
  4. package/dist/checks/purity/probe.js +19 -2
  5. package/dist/checks/purity/probe.js.map +1 -1
  6. package/dist/checks/split-report.js +2 -1
  7. package/dist/checks/split-report.js.map +1 -1
  8. package/dist/checks/test-controls.d.ts +9 -1
  9. package/dist/checks/test-controls.js +9 -3
  10. package/dist/checks/test-controls.js.map +1 -1
  11. package/dist/checks/test-dead-code.d.ts +9 -1
  12. package/dist/checks/test-dead-code.js +13 -2
  13. package/dist/checks/test-dead-code.js.map +1 -1
  14. package/dist/checks/test-mutate.d.ts +9 -1
  15. package/dist/checks/test-mutate.js +12 -6
  16. package/dist/checks/test-mutate.js.map +1 -1
  17. package/dist/cli/check.js +42 -38
  18. package/dist/cli/check.js.map +1 -1
  19. package/dist/cli/clean.js +3 -2
  20. package/dist/cli/clean.js.map +1 -1
  21. package/dist/cli/codemod/any-aliases.d.ts +1 -1
  22. package/dist/cli/codemod/any-aliases.js +14 -13
  23. package/dist/cli/codemod/any-aliases.js.map +1 -1
  24. package/dist/cli/codemod/async-style.d.ts +1 -1
  25. package/dist/cli/codemod/async-style.js +18 -17
  26. package/dist/cli/codemod/async-style.js.map +1 -1
  27. package/dist/cli/codemod/binding-keys.d.ts +32 -1
  28. package/dist/cli/codemod/binding-keys.js +238 -58
  29. package/dist/cli/codemod/binding-keys.js.map +1 -1
  30. package/dist/cli/codemod/class-renames.d.ts +39 -0
  31. package/dist/cli/codemod/class-renames.js +297 -0
  32. package/dist/cli/codemod/class-renames.js.map +1 -0
  33. package/dist/cli/codemod/connector-imports.d.ts +1 -1
  34. package/dist/cli/codemod/connector-imports.js +13 -12
  35. package/dist/cli/codemod/connector-imports.js.map +1 -1
  36. package/dist/cli/codemod/const-class-sets.d.ts +55 -0
  37. package/dist/cli/codemod/const-class-sets.js +219 -0
  38. package/dist/cli/codemod/const-class-sets.js.map +1 -0
  39. package/dist/cli/codemod/const-classes.d.ts +21 -3
  40. package/dist/cli/codemod/const-classes.js +151 -36
  41. package/dist/cli/codemod/const-classes.js.map +1 -1
  42. package/dist/cli/codemod/drop-redundant-casts.d.ts +6 -1
  43. package/dist/cli/codemod/drop-redundant-casts.js +27 -19
  44. package/dist/cli/codemod/drop-redundant-casts.js.map +1 -1
  45. package/dist/cli/codemod/env-get.d.ts +3 -3
  46. package/dist/cli/codemod/env-get.js +19 -18
  47. package/dist/cli/codemod/env-get.js.map +1 -1
  48. package/dist/cli/codemod/files.d.ts +4 -2
  49. package/dist/cli/codemod/files.js +7 -8
  50. package/dist/cli/codemod/files.js.map +1 -1
  51. package/dist/cli/codemod/function-to-arrow.d.ts +76 -0
  52. package/dist/cli/codemod/function-to-arrow.js +357 -0
  53. package/dist/cli/codemod/function-to-arrow.js.map +1 -0
  54. package/dist/cli/codemod/index.js +25 -4
  55. package/dist/cli/codemod/index.js.map +1 -1
  56. package/dist/cli/codemod/namespace-functions/index.d.ts +1 -1
  57. package/dist/cli/codemod/namespace-functions/index.js +14 -13
  58. package/dist/cli/codemod/namespace-functions/index.js.map +1 -1
  59. package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js +3 -3
  60. package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js.map +1 -1
  61. package/dist/cli/codemod/namespace-functions/mappings/helpers.js +1 -1
  62. package/dist/cli/codemod/namespace-functions/mappings/helpers.js.map +1 -1
  63. package/dist/cli/codemod/typed-route-context.d.ts +58 -0
  64. package/dist/cli/codemod/typed-route-context.js +918 -0
  65. package/dist/cli/codemod/typed-route-context.js.map +1 -0
  66. package/dist/cli/index.js +5 -4
  67. package/dist/cli/index.js.map +1 -1
  68. package/dist/common/cli-output.d.ts +16 -0
  69. package/dist/common/cli-output.js +49 -0
  70. package/dist/common/cli-output.js.map +1 -0
  71. package/dist/compilers/bun.js +1 -1
  72. package/dist/compilers/bun.js.map +1 -1
  73. package/dist/linters/eslint.js +1 -1
  74. package/dist/linters/eslint.js.map +1 -1
  75. package/dist/linters/house/browser-api-patterns.d.ts +43 -0
  76. package/dist/linters/house/browser-api-patterns.js +87 -0
  77. package/dist/linters/house/browser-api-patterns.js.map +1 -0
  78. package/dist/linters/house/common.d.ts +17 -2
  79. package/dist/linters/house/common.js +18 -2
  80. package/dist/linters/house/common.js.map +1 -1
  81. package/dist/linters/house/configs.js +25 -0
  82. package/dist/linters/house/configs.js.map +1 -1
  83. package/dist/linters/house/const-class-values.rule.d.ts +2 -2
  84. package/dist/linters/house/const-class-values.rule.js +14 -5
  85. package/dist/linters/house/const-class-values.rule.js.map +1 -1
  86. package/dist/linters/house/effect-cleanup-consistency.rule.d.ts +2 -2
  87. package/dist/linters/house/effect-cleanup-consistency.rule.js +1 -1
  88. package/dist/linters/house/effect-cleanup-consistency.rule.js.map +1 -1
  89. package/dist/linters/house/framework-api-patterns.d.ts +54 -0
  90. package/dist/linters/house/framework-api-patterns.js +62 -0
  91. package/dist/linters/house/framework-api-patterns.js.map +1 -0
  92. package/dist/linters/house/framework-exports.d.ts +62 -0
  93. package/dist/linters/house/framework-exports.js +325 -0
  94. package/dist/linters/house/framework-exports.js.map +1 -0
  95. package/dist/linters/house/import-support.d.ts +56 -0
  96. package/dist/linters/house/import-support.js +179 -0
  97. package/dist/linters/house/import-support.js.map +1 -0
  98. package/dist/linters/house/index.d.ts +12 -0
  99. package/dist/linters/house/index.js +15 -1
  100. package/dist/linters/house/index.js.map +1 -1
  101. package/dist/linters/house/max-params-own.rule.d.ts +2 -2
  102. package/dist/linters/house/max-params-own.rule.js +1 -1
  103. package/dist/linters/house/max-params-own.rule.js.map +1 -1
  104. package/dist/linters/house/no-async-hook-callback.rule.d.ts +2 -2
  105. package/dist/linters/house/no-async-hook-callback.rule.js +1 -1
  106. package/dist/linters/house/no-async-hook-callback.rule.js.map +1 -1
  107. package/dist/linters/house/no-await-new-chain.rule.d.ts +2 -2
  108. package/dist/linters/house/no-await-new-chain.rule.js +1 -1
  109. package/dist/linters/house/no-await-new-chain.rule.js.map +1 -1
  110. package/dist/linters/house/no-await-promise-chain.rule.d.ts +2 -2
  111. package/dist/linters/house/no-await-promise-chain.rule.js +5 -5
  112. package/dist/linters/house/no-await-promise-chain.rule.js.map +1 -1
  113. package/dist/linters/house/no-inline-await.rule.d.ts +2 -2
  114. package/dist/linters/house/no-inline-await.rule.js +1 -1
  115. package/dist/linters/house/no-inline-await.rule.js.map +1 -1
  116. package/dist/linters/house/no-leaked-render.rule.d.ts +2 -2
  117. package/dist/linters/house/no-leaked-render.rule.js +1 -1
  118. package/dist/linters/house/no-leaked-render.rule.js.map +1 -1
  119. package/dist/linters/house/no-new-error.rule.d.ts +2 -2
  120. package/dist/linters/house/no-new-error.rule.js +2 -2
  121. package/dist/linters/house/no-new-error.rule.js.map +1 -1
  122. package/dist/linters/house/no-parent-import.rule.d.ts +45 -0
  123. package/dist/linters/house/no-parent-import.rule.js +176 -0
  124. package/dist/linters/house/no-parent-import.rule.js.map +1 -0
  125. package/dist/linters/house/no-return-await.rule.d.ts +2 -2
  126. package/dist/linters/house/no-return-await.rule.js +1 -1
  127. package/dist/linters/house/no-return-await.rule.js.map +1 -1
  128. package/dist/linters/house/no-shadow-framework-type.rule.d.ts +24 -0
  129. package/dist/linters/house/no-shadow-framework-type.rule.js +100 -0
  130. package/dist/linters/house/no-shadow-framework-type.rule.js.map +1 -0
  131. package/dist/linters/house/no-silent-catch.rule.d.ts +2 -2
  132. package/dist/linters/house/no-silent-catch.rule.js +3 -3
  133. package/dist/linters/house/no-silent-catch.rule.js.map +1 -1
  134. package/dist/linters/house/no-unbraced-case.rule.d.ts +2 -2
  135. package/dist/linters/house/no-unbraced-case.rule.js +1 -1
  136. package/dist/linters/house/no-unbraced-case.rule.js.map +1 -1
  137. package/dist/linters/house/plugin.d.ts +1 -1
  138. package/dist/linters/house/plugin.js +18 -2
  139. package/dist/linters/house/plugin.js.map +1 -1
  140. package/dist/linters/house/prefer-framework-api.rule.d.ts +83 -0
  141. package/dist/linters/house/prefer-framework-api.rule.js +562 -0
  142. package/dist/linters/house/prefer-framework-api.rule.js.map +1 -0
  143. package/dist/linters/house/prefer-http-method.rule.d.ts +22 -0
  144. package/dist/linters/house/prefer-http-method.rule.js +182 -0
  145. package/dist/linters/house/prefer-http-method.rule.js.map +1 -0
  146. package/dist/linters/house/prefer-promise-sleep.rule.d.ts +26 -0
  147. package/dist/linters/house/prefer-promise-sleep.rule.js +155 -0
  148. package/dist/linters/house/prefer-promise-sleep.rule.js.map +1 -0
  149. package/dist/linters/house/prefer-tnullable.rule.d.ts +25 -0
  150. package/dist/linters/house/prefer-tnullable.rule.js +124 -0
  151. package/dist/linters/house/prefer-tnullable.rule.js.map +1 -0
  152. package/dist/linters/house/typed-route-context.rule.d.ts +19 -0
  153. package/dist/linters/house/typed-route-context.rule.js +334 -0
  154. package/dist/linters/house/typed-route-context.rule.js.map +1 -0
  155. package/dist/linters/house/zod-schema-convention.rule.d.ts +82 -0
  156. package/dist/linters/house/zod-schema-convention.rule.js +477 -0
  157. package/dist/linters/house/zod-schema-convention.rule.js.map +1 -0
  158. package/dist/linters/oxlint.js +11 -1
  159. package/dist/linters/oxlint.js.map +1 -1
  160. package/dist/linters/react-eslint.js.map +1 -1
  161. package/dist/linters/rules/naming-convention.rule.d.ts +4 -1
  162. package/dist/linters/rules/naming-convention.rule.js +30 -1
  163. package/dist/linters/rules/naming-convention.rule.js.map +1 -1
  164. package/dist/linters/rules/no-restricted-properties.rule.js +1 -1
  165. package/dist/linters/rules/no-restricted-properties.rule.js.map +1 -1
  166. package/dist/testing/index.d.ts +2 -2
  167. package/dist/testing/index.js +2 -2
  168. package/dist/testing/index.js.map +1 -1
  169. package/dist/testing/{rejection.helper.d.ts → rejection.utility.d.ts} +4 -4
  170. package/dist/testing/{rejection.helper.js → rejection.utility.js} +7 -7
  171. package/dist/testing/rejection.utility.js.map +1 -0
  172. package/dist/testing/{spawn.helper.d.ts → spawn.utility.d.ts} +2 -2
  173. package/dist/testing/{spawn.helper.js → spawn.utility.js} +6 -6
  174. package/dist/testing/spawn.utility.js.map +1 -0
  175. package/package.json +7 -7
  176. package/dist/testing/rejection.helper.js.map +0 -1
  177. package/dist/testing/spawn.helper.js.map +0 -1
@@ -0,0 +1,918 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TypedRouteContextCommand = exports.TypedRouteContext = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const binding_keys_1 = require("./binding-keys");
7
+ const files_1 = require("./files");
8
+ const cli_output_1 = require("../../common/cli-output");
9
+ const USAGE = `Usage: devz codemod typed-route-context [paths...] [--write [--all] | --check]
10
+
11
+ Types route handlers from their route config (TContextOf). In a file that imports the types from @venizia/ignis or
12
+ @venizia/ignis-kernel:
13
+
14
+ - a decorated method (@api, @get, @post, @put, @patch, @del) whose configs is a name declared or imported in the
15
+ file: its TRouteContext becomes TContextOf<typeof CONFIG>, and valid<T>() on it loses its type argument;
16
+ - the same for a private method that only the handlers of one route config in its class pass their context to;
17
+ - TRouteContext<Env, Body> drops the body, and TRouteHandler<Response, Env> drops the response. What the argument
18
+ checked stays checked: each json() of that context takes "body satisfies Body", and a TJsonResponse<X> return type
19
+ of the function becomes TJsonResponse<unknown>, since json() no longer carries the body type.
20
+
21
+ Left as they are, for you: a handler of a CRUD override, a method that serves two routes or is also called another
22
+ way, an inline or this.* config, and a context typed through an alias of yours. The typecheck then names each place
23
+ where a type you wrote by hand differs from the schema. A valid<T>() keeps its argument
24
+ where, without it, the call answers unknown (the route config carries no schema type there) or its method has a type
25
+ error (your type differs from the schema's). The codemod asks the types of each file's project (its nearest
26
+ tsconfig.json), so upgrade the packages first.
27
+ An import or a local type that the rewrite leaves unused is removed. Every type error a rewritten file still has is
28
+ listed as "check by hand". Asking the types takes about twice as long as your typecheck.
29
+
30
+ A config declared as IAuthRouteConfig, or in a Record of it, carries no schema type: change it to
31
+ "satisfies" first (the lint rule @venizia/typed-route-context reports each one). A handler of such a config declared
32
+ in the same file is left as it is; one imported from another file cannot be seen, so change those first.
33
+
34
+ --write write the changed files (without it, nothing is written); it needs a path, or --all
35
+ --all with --write and no path: rewrite every source file under the working directory
36
+ --check dry run that exits 1 while a file would change (for CI)
37
+ --help print this text and exit
38
+
39
+ With no flag it lists what would change and writes nothing. Inside a git repository it reads the files git
40
+ knows (tracked, or untracked and not ignored), and --write refuses a file with local changes (changed since staged, or untracked): commit, stash or "git add" it first, so git can undo the codemod.`;
41
+ /** A usage error: nothing was read or written. */
42
+ const USAGE_ERROR_CODE = 2;
43
+ class TypedRouteContextFlags {
44
+ static { this.WRITE = '--write'; }
45
+ static { this.ALL = '--all'; }
46
+ static { this.CHECK = '--check'; }
47
+ static { this.HELP = '--help'; }
48
+ static { this.HELP_SHORT = '-h'; }
49
+ static { this.SCHEME_SET = new Set([
50
+ this.WRITE,
51
+ this.ALL,
52
+ this.CHECK,
53
+ this.HELP,
54
+ this.HELP_SHORT,
55
+ ]); }
56
+ static isValid(value) {
57
+ return this.SCHEME_SET.has(value);
58
+ }
59
+ }
60
+ const PACKAGES = ['@venizia/ignis', '@venizia/ignis-kernel'];
61
+ const DECORATORS = new Set(['api', 'get', 'post', 'put', 'patch', 'del']);
62
+ const CONTEXT = 'TRouteContext';
63
+ const HANDLER = 'TRouteHandler';
64
+ const TYPED = 'TContextOf';
65
+ const RESPONSE = 'TJsonResponse';
66
+ /** One file's rewrite: the edits found so far, applied from the end of the file. */
67
+ class RouteContextFile {
68
+ static { this.IDENTIFIER = /^[A-Za-z_$][\w$]*$/; }
69
+ constructor(options) {
70
+ this.options = options;
71
+ this.edits = new Map();
72
+ /** Where each call that lost its type argument starts. */
73
+ this.droppedAt = [];
74
+ /** The local names the framework's types were imported under. */
75
+ this.locals = new Map();
76
+ /** The names a `typeof` at the top of the file can read. */
77
+ this.topLevel = new Set();
78
+ /** The configs this file declares as `IAuthRouteConfig`, as a name or `Class.member`: their type holds no schema. */
79
+ this.wide = new Set();
80
+ const { typescript: ts, fileName, source } = options;
81
+ const scriptKind = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
82
+ this.file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, scriptKind);
83
+ }
84
+ rewrite() {
85
+ const { typescript: ts, source } = this.options;
86
+ this.readTopLevel();
87
+ if (this.locals.size === 0) {
88
+ return { output: source, changed: false, rewritten: 0, dropped: [] };
89
+ }
90
+ const visit = (node) => {
91
+ if (ts.isClassLike(node)) {
92
+ this.typeClass(node);
93
+ }
94
+ ts.forEachChild(node, visit);
95
+ };
96
+ visit(this.file);
97
+ this.keepBodyChecks(this.file);
98
+ this.dropRemovedArguments(this.file);
99
+ const rewritten = this.edits.size;
100
+ if (rewritten === 0) {
101
+ return { output: source, changed: false, rewritten, dropped: [] };
102
+ }
103
+ this.fixDeclarations();
104
+ let output = source;
105
+ for (const edit of [...this.edits.values()].sort((a, b) => b.start - a.start)) {
106
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
107
+ }
108
+ // An edit before a position moves it by what the edit adds or takes away.
109
+ const moved = (position) => [...this.edits.values()]
110
+ .filter((edit) => edit.end <= position)
111
+ .reduce((total, edit) => total + edit.text.length - (edit.end - edit.start), position);
112
+ const dropped = this.droppedAt.map(({ call, method }) => ({
113
+ source: call,
114
+ output: moved(call),
115
+ method: { start: moved(method.getStart(this.file)), end: moved(method.getEnd()) },
116
+ }));
117
+ return { output, changed: output !== source, rewritten, dropped };
118
+ }
119
+ replace(opts) {
120
+ this.edits.set(`${opts.start}:${opts.end}`, opts);
121
+ }
122
+ isReplaced(node) {
123
+ return this.edits.has(`${node.getStart(this.file)}:${node.getEnd()}`);
124
+ }
125
+ readTopLevel() {
126
+ const { typescript: ts } = this.options;
127
+ for (const statement of this.file.statements) {
128
+ if (ts.isVariableStatement(statement)) {
129
+ for (const declaration of statement.declarationList.declarations) {
130
+ const name = declaration.name.getText(this.file);
131
+ this.topLevel.add(name);
132
+ if (this.isWideDeclaration(declaration)) {
133
+ this.wide.add(name);
134
+ }
135
+ this.readWideMembers({ owner: name, value: declaration.initializer });
136
+ }
137
+ }
138
+ if (ts.isClassDeclaration(statement) && statement.name) {
139
+ const owner = statement.name.text;
140
+ this.topLevel.add(owner);
141
+ for (const member of statement.members) {
142
+ if (ts.isPropertyDeclaration(member) && this.isWideDeclaration(member)) {
143
+ this.wide.add(`${owner}.${member.name.getText(this.file)}`);
144
+ }
145
+ }
146
+ }
147
+ if (!ts.isImportDeclaration(statement)) {
148
+ continue;
149
+ }
150
+ const specifier = statement.moduleSpecifier.getText(this.file).slice(1, -1);
151
+ const bindings = statement.importClause?.namedBindings;
152
+ const defaultName = statement.importClause?.name;
153
+ if (defaultName) {
154
+ this.topLevel.add(defaultName.text);
155
+ }
156
+ if (!bindings) {
157
+ continue;
158
+ }
159
+ if (ts.isNamespaceImport(bindings)) {
160
+ this.topLevel.add(bindings.name.text);
161
+ continue;
162
+ }
163
+ const isFramework = PACKAGES.some((name) => specifier === name || specifier.startsWith(`${name}/`));
164
+ for (const element of bindings.elements) {
165
+ this.topLevel.add(element.name.text);
166
+ const imported = (element.propertyName ?? element.name).text;
167
+ if (isFramework && [CONTEXT, HANDLER, TYPED, RESPONSE].includes(imported)) {
168
+ this.locals.set(element.name.text, imported);
169
+ }
170
+ }
171
+ }
172
+ }
173
+ /** The members of an object literal asserted wide one by one: `{ A: { ... } as IAuthRouteConfig }`. */
174
+ readWideMembers(opts) {
175
+ const { typescript: ts } = this.options;
176
+ let { value } = opts;
177
+ while (value && (ts.isAsExpression(value) || ts.isSatisfiesExpression(value))) {
178
+ value = value.expression;
179
+ }
180
+ if (!value || !ts.isObjectLiteralExpression(value)) {
181
+ return;
182
+ }
183
+ for (const property of value.properties) {
184
+ if (ts.isPropertyAssignment(property) &&
185
+ ts.isAsExpression(property.initializer) &&
186
+ this.isWideType(property.initializer.type)) {
187
+ const key = ts.isStringLiteralLike(property.name)
188
+ ? property.name.text
189
+ : property.name.getText(this.file);
190
+ this.wide.add(`${opts.owner}.${key}`);
191
+ }
192
+ }
193
+ }
194
+ /** Whether a declaration is typed `IAuthRouteConfig`, in an `Omit` or a `Record` too, by annotation or by `as`. */
195
+ isWideDeclaration(declaration) {
196
+ const { typescript: ts } = this.options;
197
+ const { initializer } = declaration;
198
+ const asserted = initializer && ts.isAsExpression(initializer) ? initializer.type : undefined;
199
+ return this.isWideType(declaration.type) || this.isWideType(asserted);
200
+ }
201
+ isWideType(type) {
202
+ const { typescript: ts } = this.options;
203
+ if (!type || !ts.isTypeReferenceNode(type)) {
204
+ return false;
205
+ }
206
+ const name = type.typeName.getText(this.file);
207
+ const [first, second] = type.typeArguments ?? [];
208
+ if (name === 'Record') {
209
+ return this.isWideType(second);
210
+ }
211
+ return name === 'Omit' || name === 'Readonly'
212
+ ? this.isWideType(first)
213
+ : name === 'IAuthRouteConfig';
214
+ }
215
+ /** The framework type a type reference names. */
216
+ frameworkType(node) {
217
+ const { typescript: ts } = this.options;
218
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)
219
+ ? this.locals.get(node.typeName.text)
220
+ : undefined;
221
+ }
222
+ /**
223
+ * The type of a `configs` expression a `typeof` can read here (`typeof Routes.CREATE`, `(typeof Routes)['/create']`);
224
+ * `undefined` for anything else.
225
+ */
226
+ configOf(options) {
227
+ const { typescript: ts } = this.options;
228
+ if (!options || !ts.isObjectLiteralExpression(options)) {
229
+ return undefined;
230
+ }
231
+ const property = options.properties.find((item) => item.name?.getText(this.file) === 'configs');
232
+ if (!property || !ts.isPropertyAssignment(property)) {
233
+ return undefined;
234
+ }
235
+ const keys = [];
236
+ let current = property.initializer;
237
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
238
+ if (ts.isPropertyAccessExpression(current)) {
239
+ keys.unshift(current.name.text);
240
+ }
241
+ else if (ts.isStringLiteralLike(current.argumentExpression)) {
242
+ keys.unshift(current.argumentExpression.text);
243
+ }
244
+ else {
245
+ return undefined;
246
+ }
247
+ current = current.expression;
248
+ }
249
+ if (!ts.isIdentifier(current) || !this.topLevel.has(current.text)) {
250
+ return undefined;
251
+ }
252
+ if (this.wide.has(current.text) || this.wide.has(`${current.text}.${keys[0]}`)) {
253
+ return undefined;
254
+ }
255
+ const firstQuoted = keys.findIndex((key) => !RouteContextFile.IDENTIFIER.test(key));
256
+ const dotted = firstQuoted === -1 ? keys : keys.slice(0, firstQuoted);
257
+ const query = `typeof ${[current.text, ...dotted].join('.')}`;
258
+ if (firstQuoted === -1) {
259
+ return query;
260
+ }
261
+ const indexed = keys
262
+ .slice(firstQuoted)
263
+ .map((key) => `['${key.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}']`);
264
+ return `(${query})${indexed.join('')}`;
265
+ }
266
+ /** Types the decorated methods of a class, and the methods only one route's handlers pass their context to. */
267
+ typeClass(node) {
268
+ const { typescript: ts } = this.options;
269
+ const forwarded = this.forwardsOf(node);
270
+ for (const member of node.members) {
271
+ if (!ts.isMethodDeclaration(member)) {
272
+ continue;
273
+ }
274
+ const decorated = (ts.getDecorators(member) ?? []).flatMap((decorator) => {
275
+ const call = decorator.expression;
276
+ return ts.isCallExpression(call) && DECORATORS.has(call.expression.getText(this.file))
277
+ ? [this.configOf(call.arguments[0])]
278
+ : [];
279
+ });
280
+ const isPrivate = ts.isPrivateIdentifier(member.name) ||
281
+ member.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.PrivateKeyword) ===
282
+ true;
283
+ // Only a private method is known to be reached from this class alone.
284
+ if (decorated.length === 0 && !isPrivate) {
285
+ continue;
286
+ }
287
+ const routes = [...decorated, ...(forwarded.get(member.name.getText(this.file)) ?? [])];
288
+ const [config] = routes;
289
+ if (config !== undefined && routes.every((route) => route === config)) {
290
+ this.typeMethod({ method: member, config });
291
+ }
292
+ }
293
+ }
294
+ /**
295
+ * The routes whose handlers pass their context straight to each method of the class. A method also reached another
296
+ * way gets an `undefined` route, which keeps it as it is.
297
+ */
298
+ forwardsOf(node) {
299
+ const { typescript: ts } = this.options;
300
+ const routes = new Map();
301
+ const passed = new Set();
302
+ const add = (method, route) => {
303
+ routes.set(method, [...(routes.get(method) ?? []), route]);
304
+ };
305
+ const visit = (current) => {
306
+ if (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
307
+ const forward = this.forwardOf(current);
308
+ if (forward) {
309
+ passed.add(forward.access);
310
+ add(forward.method, forward.config);
311
+ }
312
+ }
313
+ if (ts.isPropertyAccessExpression(current) &&
314
+ current.expression.kind === ts.SyntaxKind.ThisKeyword &&
315
+ !passed.has(current)) {
316
+ add(current.name.text, undefined);
317
+ }
318
+ ts.forEachChild(current, visit);
319
+ };
320
+ ts.forEachChild(node, visit);
321
+ return routes;
322
+ }
323
+ /** The method a `defineRoute`, `defineJSXRoute` or `bindRoute().to` call forwards its context to. */
324
+ forwardOf(call) {
325
+ const { typescript: ts } = this.options;
326
+ const callee = call.expression;
327
+ if (!ts.isPropertyAccessExpression(callee)) {
328
+ return undefined;
329
+ }
330
+ const name = callee.name.text;
331
+ const [options] = call.arguments;
332
+ let routeOptions;
333
+ if (name === 'defineRoute' || name === 'defineJSXRoute') {
334
+ routeOptions = options;
335
+ }
336
+ else if (name === 'to' &&
337
+ ts.isCallExpression(callee.expression) &&
338
+ ts.isPropertyAccessExpression(callee.expression.expression) &&
339
+ callee.expression.expression.name.text === 'bindRoute') {
340
+ routeOptions = callee.expression.arguments[0];
341
+ }
342
+ if (!routeOptions || !options || !ts.isObjectLiteralExpression(options)) {
343
+ return undefined;
344
+ }
345
+ const handler = options.properties.find((item) => item.name?.getText(this.file) === 'handler');
346
+ if (!handler || !ts.isPropertyAssignment(handler) || !ts.isArrowFunction(handler.initializer)) {
347
+ return undefined;
348
+ }
349
+ const [parameter] = handler.initializer.parameters;
350
+ let body = handler.initializer.body;
351
+ if (ts.isBlock(body)) {
352
+ const [only, ...others] = body.statements;
353
+ body =
354
+ only && others.length === 0 && ts.isReturnStatement(only) ? only.expression : undefined;
355
+ }
356
+ if (body && ts.isAwaitExpression(body)) {
357
+ body = body.expression;
358
+ }
359
+ if (!parameter ||
360
+ !body ||
361
+ !ts.isCallExpression(body) ||
362
+ !ts.isPropertyAccessExpression(body.expression) ||
363
+ body.expression.expression.kind !== ts.SyntaxKind.ThisKeyword) {
364
+ return undefined;
365
+ }
366
+ const context = parameter.name.getText(this.file);
367
+ const passes = body.arguments.some((argument) => {
368
+ if (!ts.isObjectLiteralExpression(argument)) {
369
+ return argument.getText(this.file) === context;
370
+ }
371
+ return argument.properties.some((item) => item.name?.getText(this.file) === 'context' &&
372
+ (ts.isShorthandPropertyAssignment(item)
373
+ ? context === 'context'
374
+ : ts.isPropertyAssignment(item) && item.initializer.getText(this.file) === context));
375
+ });
376
+ return passes
377
+ ? {
378
+ access: body.expression,
379
+ method: body.expression.name.text,
380
+ config: this.configOf(routeOptions),
381
+ }
382
+ : undefined;
383
+ }
384
+ /** Writes `TContextOf<typeof config>` on the method's context, and drops the type arguments of its `valid()`. */
385
+ typeMethod(opts) {
386
+ const { typescript: ts } = this.options;
387
+ const { method, config } = opts;
388
+ /** The paths that hold the retyped context, as written: `context`, `opts.context`. */
389
+ const holders = new Set();
390
+ for (const parameter of method.parameters) {
391
+ let type = parameter.type;
392
+ let path = parameter.name.getText(this.file);
393
+ if (type && ts.isTypeLiteralNode(type)) {
394
+ const member = type.members.find((item) => item.name?.getText(this.file) === 'context');
395
+ type = member && ts.isPropertySignature(member) ? member.type : undefined;
396
+ path = ts.isIdentifier(parameter.name) ? `${path}.context` : 'context';
397
+ }
398
+ if (!type || !ts.isTypeReferenceNode(type) || this.frameworkType(type) !== CONTEXT) {
399
+ continue;
400
+ }
401
+ const environment = type.typeArguments?.[0]?.getText(this.file);
402
+ const suffix = environment ? `, ${environment}` : '';
403
+ this.replace({
404
+ start: type.getStart(this.file),
405
+ end: type.getEnd(),
406
+ text: `${this.localName(TYPED)}<${config}${suffix}>`,
407
+ });
408
+ holders.add(path);
409
+ }
410
+ if (holders.size === 0 || !method.body) {
411
+ return;
412
+ }
413
+ const visit = (node) => {
414
+ if (ts.isVariableDeclaration(node) &&
415
+ ts.isObjectBindingPattern(node.name) &&
416
+ node.initializer &&
417
+ holders.has(`${node.initializer.getText(this.file)}.context`)) {
418
+ holders.add('context');
419
+ }
420
+ if (ts.isCallExpression(node) &&
421
+ node.typeArguments &&
422
+ ts.isPropertyAccessExpression(node.expression) &&
423
+ node.expression.name.text === 'valid' &&
424
+ ts.isPropertyAccessExpression(node.expression.expression) &&
425
+ node.expression.expression.name.text === 'req' &&
426
+ holders.has(node.expression.expression.expression.getText(this.file)) &&
427
+ !this.options.keep?.has(node.getStart(this.file))) {
428
+ this.droppedAt.push({ call: node.getStart(this.file), method });
429
+ this.replace({
430
+ start: node.expression.getEnd(),
431
+ end: node.typeArguments.end + 1,
432
+ text: '',
433
+ });
434
+ }
435
+ ts.forEachChild(node, visit);
436
+ };
437
+ visit(method.body);
438
+ }
439
+ /**
440
+ * Keeps what the removed body argument checked. In a function whose context, or whose `TRouteHandler` type, names a
441
+ * body: each `json()` of that context takes `body satisfies Body`, and a `TJsonResponse<X>` return type becomes
442
+ * `TJsonResponse<unknown>`, since `json()` no longer carries the body type.
443
+ */
444
+ keepBodyChecks(node) {
445
+ const { typescript: ts } = this.options;
446
+ if (ts.isFunctionLike(node)) {
447
+ const holders = new Map();
448
+ for (const parameter of node.parameters) {
449
+ let type = parameter.type;
450
+ let path = parameter.name.getText(this.file);
451
+ if (type && ts.isTypeLiteralNode(type)) {
452
+ const member = type.members.find((item) => item.name?.getText(this.file) === 'context');
453
+ type = member && ts.isPropertySignature(member) ? member.type : undefined;
454
+ path = ts.isIdentifier(parameter.name) ? `${path}.context` : 'context';
455
+ }
456
+ const body = this.bodyOf({ type, of: CONTEXT });
457
+ if (body !== undefined) {
458
+ holders.set(path, body);
459
+ }
460
+ }
461
+ const { parent } = node;
462
+ const handled = ts.isVariableDeclaration(parent)
463
+ ? this.bodyOf({ type: parent.type, of: HANDLER })
464
+ : undefined;
465
+ const [first] = node.parameters;
466
+ if (handled !== undefined && first && !first.type) {
467
+ holders.set(first.name.getText(this.file), handled);
468
+ }
469
+ if (holders.size > 0) {
470
+ this.checkBodies({ node, holders });
471
+ this.widenResponses(node.type);
472
+ }
473
+ }
474
+ ts.forEachChild(node, (child) => this.keepBodyChecks(child));
475
+ }
476
+ /** The body argument a `TRouteContext<Env, Body>` or `TRouteHandler<Body, Env>` names, unless it says nothing. */
477
+ bodyOf(opts) {
478
+ const { typescript: ts } = this.options;
479
+ const { type, of } = opts;
480
+ if (!type || !ts.isTypeReferenceNode(type) || this.frameworkType(type) !== of) {
481
+ return undefined;
482
+ }
483
+ const [first, second] = type.typeArguments ?? [];
484
+ const body = second ? (of === CONTEXT ? second : first) : undefined;
485
+ const text = body?.getText(this.file);
486
+ return text === 'unknown' || text === 'any' ? undefined : text;
487
+ }
488
+ /** Writes `satisfies Body` on the argument of each `json()` of a context that named a body. */
489
+ checkBodies(opts) {
490
+ const { typescript: ts } = this.options;
491
+ const { node, holders } = opts;
492
+ const visit = (current) => {
493
+ if (ts.isVariableDeclaration(current) &&
494
+ ts.isObjectBindingPattern(current.name) &&
495
+ current.initializer) {
496
+ const body = holders.get(`${current.initializer.getText(this.file)}.context`);
497
+ if (body !== undefined) {
498
+ holders.set('context', body);
499
+ }
500
+ }
501
+ if (ts.isCallExpression(current) &&
502
+ ts.isPropertyAccessExpression(current.expression) &&
503
+ current.expression.name.text === 'json') {
504
+ const body = holders.get(current.expression.expression.getText(this.file));
505
+ const [value] = current.arguments;
506
+ const isCheckable = value && !ts.isSatisfiesExpression(value) && !ts.isSpreadElement(value);
507
+ if (body !== undefined && isCheckable) {
508
+ this.writeSatisfies({ value, body });
509
+ }
510
+ }
511
+ ts.forEachChild(current, visit);
512
+ };
513
+ ts.forEachChild(node, visit);
514
+ }
515
+ writeSatisfies(opts) {
516
+ const { typescript: ts } = this.options;
517
+ const { value, body } = opts;
518
+ // `satisfies` binds tighter than these.
519
+ const isLoose = ts.isConditionalExpression(value) ||
520
+ ts.isBinaryExpression(value) ||
521
+ ts.isArrowFunction(value);
522
+ const start = value.getStart(this.file);
523
+ const end = value.getEnd();
524
+ if (isLoose) {
525
+ this.replace({ start, end: start, text: '(' });
526
+ }
527
+ this.replace({ start: end, end, text: `${isLoose ? ')' : ''} satisfies ${body}` });
528
+ }
529
+ /** `TJsonResponse<X, Status>` in a return type becomes `TJsonResponse<unknown, Status>`. */
530
+ widenResponses(type) {
531
+ const { typescript: ts } = this.options;
532
+ const visit = (node) => {
533
+ if (ts.isTypeReferenceNode(node) &&
534
+ this.frameworkType(node) === RESPONSE &&
535
+ node.typeArguments?.[0]) {
536
+ const [body] = node.typeArguments;
537
+ this.replace({ start: body.getStart(this.file), end: body.getEnd(), text: 'unknown' });
538
+ return;
539
+ }
540
+ ts.forEachChild(node, visit);
541
+ };
542
+ if (type) {
543
+ visit(type);
544
+ }
545
+ }
546
+ /** Drops the response arguments the framework's types no longer take, outside the contexts already retyped. */
547
+ dropRemovedArguments(node) {
548
+ const { typescript: ts } = this.options;
549
+ if (ts.isTypeReferenceNode(node) &&
550
+ node.typeArguments?.length === 2 &&
551
+ !this.isReplaced(node)) {
552
+ const type = this.frameworkType(node);
553
+ const [first, second] = node.typeArguments;
554
+ const kept = type === CONTEXT ? first : type === HANDLER ? second : undefined;
555
+ if (kept) {
556
+ this.replace({
557
+ start: node.getStart(this.file),
558
+ end: node.getEnd(),
559
+ text: `${node.typeName.getText(this.file)}<${kept.getText(this.file)}>`,
560
+ });
561
+ }
562
+ }
563
+ ts.forEachChild(node, (child) => this.dropRemovedArguments(child));
564
+ }
565
+ /** The local name of a framework type, or its own name when the file does not import it yet. */
566
+ localName(type) {
567
+ return [...this.locals].find(([, imported]) => imported === type)?.[0] ?? type;
568
+ }
569
+ /** Whether an edit takes this node away: one that writes the name back (`TRouteContext<Env>`) does not. */
570
+ isRemoved(node, name) {
571
+ return [...this.edits.values()].some((edit) => edit.start <= node.getStart(this.file) &&
572
+ edit.end >= node.getEnd() &&
573
+ !edit.text.split(/[^\w$]+/).includes(name));
574
+ }
575
+ /** Whether the edits take away every read of a name that was read: it is unused now, and was not before. */
576
+ isLeftUnused(name) {
577
+ const { typescript: ts } = this.options;
578
+ let reads = 0;
579
+ let removed = 0;
580
+ // An edit that writes the name keeps it read.
581
+ if ([...this.edits.values()].some((edit) => edit.text.split(/[^\w$]+/).includes(name))) {
582
+ return false;
583
+ }
584
+ const visit = (node) => {
585
+ if (ts.isImportDeclaration(node)) {
586
+ return;
587
+ }
588
+ if (ts.isIdentifier(node) && node.text === name && !this.isNaming(node)) {
589
+ reads += 1;
590
+ removed += this.isRemoved(node.parent, name) || this.isRemoved(node, name) ? 1 : 0;
591
+ }
592
+ ts.forEachChild(node, visit);
593
+ };
594
+ visit(this.file);
595
+ return reads > 0 && reads === removed;
596
+ }
597
+ /** Whether an identifier names a member or a declaration, and reads nothing. */
598
+ isNaming(node) {
599
+ const { typescript: ts } = this.options;
600
+ const { parent } = node;
601
+ if (ts.isQualifiedName(parent)) {
602
+ return parent.right === node;
603
+ }
604
+ return ((ts.isPropertyAccessExpression(parent) ||
605
+ ts.isPropertyAssignment(parent) ||
606
+ ts.isPropertySignature(parent) ||
607
+ ts.isPropertyDeclaration(parent) ||
608
+ ts.isMethodDeclaration(parent) ||
609
+ ts.isTypeAliasDeclaration(parent) ||
610
+ ts.isInterfaceDeclaration(parent)) &&
611
+ parent.name === node);
612
+ }
613
+ /** Removes the local types the edits leave unused; one removal can leave another unused. */
614
+ dropUnusedTypes() {
615
+ const { typescript: ts } = this.options;
616
+ let isChanged = true;
617
+ while (isChanged) {
618
+ isChanged = false;
619
+ for (const statement of this.file.statements) {
620
+ if (!ts.isTypeAliasDeclaration(statement) && !ts.isInterfaceDeclaration(statement)) {
621
+ continue;
622
+ }
623
+ // Its own text and its JSDoc: a comment above that belongs to the file or to a section stays.
624
+ const start = statement.getStart(this.file, true);
625
+ const end = this.pastLineBreak(statement.getEnd());
626
+ const isExported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
627
+ const isDropped = this.edits.has(`${start}:${end}`);
628
+ if (isExported || isDropped || !this.isLeftUnused(statement.name.text)) {
629
+ continue;
630
+ }
631
+ this.replace({ start, end, text: '' });
632
+ isChanged = true;
633
+ }
634
+ }
635
+ }
636
+ /** The position after the line break at `position`, or `position` when none is there. */
637
+ pastLineBreak(position) {
638
+ const { source } = this.options;
639
+ const found = ['\r\n', '\n'].find((lineBreak) => source.startsWith(lineBreak, position));
640
+ return position + (found?.length ?? 0);
641
+ }
642
+ /**
643
+ * Imports `TContextOf` beside the type it replaced, and removes the imports and local types the edits leave unused.
644
+ */
645
+ fixDeclarations() {
646
+ const { typescript: ts, source } = this.options;
647
+ this.dropUnusedTypes();
648
+ const contextName = this.localName(CONTEXT);
649
+ const usesTyped = [...this.edits.values()].some((edit) => edit.text.startsWith(`${this.localName(TYPED)}<`));
650
+ let needsImport = usesTyped && ![...this.locals.values()].includes(TYPED);
651
+ for (const statement of this.file.statements) {
652
+ if (!ts.isImportDeclaration(statement)) {
653
+ continue;
654
+ }
655
+ const clause = statement.importClause;
656
+ const bindings = clause?.namedBindings;
657
+ if (!clause || !bindings || !ts.isNamedImports(bindings)) {
658
+ continue;
659
+ }
660
+ let isChanged = false;
661
+ const names = bindings.elements.flatMap((element) => {
662
+ const isGone = this.isLeftUnused(element.name.text);
663
+ const isReplaced = needsImport && element.name.text === contextName;
664
+ const kept = isGone ? [] : [element.getText(this.file)];
665
+ if (isReplaced) {
666
+ needsImport = false;
667
+ kept.push(clause.isTypeOnly ? TYPED : `type ${TYPED}`);
668
+ }
669
+ isChanged ||= isGone || isReplaced;
670
+ return kept;
671
+ });
672
+ if (!isChanged) {
673
+ continue;
674
+ }
675
+ if (names.length === 0 && !clause.name) {
676
+ this.replace({
677
+ start: statement.getStart(this.file),
678
+ end: this.pastLineBreak(statement.getEnd()),
679
+ text: '',
680
+ });
681
+ continue;
682
+ }
683
+ // A default import stays without the braces and the comma before them.
684
+ if (names.length === 0 && clause.name) {
685
+ this.replace({ start: clause.name.getEnd(), end: bindings.getEnd(), text: '' });
686
+ continue;
687
+ }
688
+ const lineBreak = source.includes('\r\n') ? '\r\n' : '\n';
689
+ const isSpread = bindings.getText(this.file).includes('\n');
690
+ this.replace({
691
+ start: bindings.getStart(this.file),
692
+ end: bindings.getEnd(),
693
+ text: isSpread
694
+ ? `{${lineBreak} ${names.join(`,${lineBreak} `)},${lineBreak}}`
695
+ : `{ ${names.join(', ')} }`,
696
+ });
697
+ }
698
+ }
699
+ }
700
+ /** Types route handlers from their route configs. */
701
+ class TypedRouteContext {
702
+ static rewrite(opts) {
703
+ return new RouteContextFile(opts).rewrite();
704
+ }
705
+ /**
706
+ * Which of the dropped type arguments must stay, per file: those whose call answers `unknown` or `any` once the files
707
+ * are rewritten, and all of a method where the rewritten file has a type error, since the type written there may
708
+ * differ from the schema's.
709
+ */
710
+ static keptCalls(opts) {
711
+ const asked = [...opts.results].filter(([, result]) => result.dropped.length > 0);
712
+ const kept = new Map();
713
+ for (const { file, program } of TypedRouteContext.check({
714
+ ...opts,
715
+ files: asked.map(([path]) => path),
716
+ })) {
717
+ const found = TypedRouteContext.keptIn({
718
+ typescript: opts.typescript,
719
+ program,
720
+ file,
721
+ dropped: opts.results.get(file)?.dropped ?? [],
722
+ });
723
+ if (found.size > 0) {
724
+ kept.set(file, found);
725
+ }
726
+ }
727
+ return kept;
728
+ }
729
+ /** The type errors the rewritten files still have, as `line TScode`, per file that has any. */
730
+ static remainingErrors(opts) {
731
+ const remaining = new Map();
732
+ for (const { file, program } of TypedRouteContext.check({
733
+ ...opts,
734
+ files: [...opts.results.keys()],
735
+ })) {
736
+ const sourceFile = program.getSourceFile(file);
737
+ const found = sourceFile
738
+ ? program.getSemanticDiagnostics(sourceFile).map((error) => {
739
+ const { line } = sourceFile.getLineAndCharacterOfPosition(error.start ?? 0);
740
+ return `${line + 1} TS${error.code}`;
741
+ })
742
+ : [];
743
+ if (found.length > 0) {
744
+ remaining.set(file, found);
745
+ }
746
+ }
747
+ return remaining;
748
+ }
749
+ /** Each of `files` with the program of its own project (its nearest tsconfig.json), the rewritten text read. */
750
+ static check(opts) {
751
+ const { typescript: ts, root, results, files } = opts;
752
+ const projects = new Map();
753
+ for (const file of files) {
754
+ const config = ts.findConfigFile((0, node_path_1.dirname)(file), (path) => ts.sys.fileExists(path));
755
+ const project = config === undefined ? root : (0, node_path_1.dirname)(config);
756
+ projects.set(project, [...(projects.get(project) ?? []), file]);
757
+ }
758
+ const contents = new Map([...results].map(([file, result]) => [file, result.output]));
759
+ return [...projects].flatMap(([project, owned]) => {
760
+ const program = binding_keys_1.BindingKeysCommand.createProgram({
761
+ typescript: ts,
762
+ root: project,
763
+ files: owned,
764
+ contents,
765
+ withProjectFiles: true,
766
+ });
767
+ return owned.map((file) => ({ file, program }));
768
+ });
769
+ }
770
+ static keptIn(opts) {
771
+ const { typescript: ts, program, file, dropped } = opts;
772
+ const sourceFile = program.getSourceFile(file);
773
+ const kept = new Set();
774
+ if (!sourceFile) {
775
+ return new Set(dropped.map((call) => call.source));
776
+ }
777
+ const checker = program.getTypeChecker();
778
+ const errors = program.getSemanticDiagnostics(sourceFile).map((error) => error.start ?? 0);
779
+ const positions = new Map(dropped.map((call) => [call.output, call]));
780
+ const visit = (node) => {
781
+ const call = positions.get(node.getStart(sourceFile));
782
+ if (call && ts.isCallExpression(node)) {
783
+ const isUntyped = checker.getTypeAtLocation(node).flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any);
784
+ const isBroken = errors.some((error) => error >= call.method.start && error < call.method.end);
785
+ if (isUntyped || isBroken) {
786
+ kept.add(call.source);
787
+ }
788
+ }
789
+ ts.forEachChild(node, visit);
790
+ };
791
+ visit(sourceFile);
792
+ return kept;
793
+ }
794
+ }
795
+ exports.TypedRouteContext = TypedRouteContext;
796
+ /**
797
+ * `devz codemod typed-route-context [paths...] [--write [--all] | --check]`. It is a dry run unless `--write` is
798
+ * given. `--check` is the same dry run, and exits 1 while a file would change.
799
+ */
800
+ class TypedRouteContextCommand {
801
+ static { this.USAGE = USAGE; }
802
+ static async run(opts) {
803
+ const { root, args } = opts;
804
+ if (args.includes(TypedRouteContextFlags.HELP) ||
805
+ args.includes(TypedRouteContextFlags.HELP_SHORT)) {
806
+ cli_output_1.CliOutput.log(USAGE);
807
+ return 0;
808
+ }
809
+ const flags = args.filter((argument) => argument.startsWith('-'));
810
+ const paths = args.filter((argument) => !argument.startsWith('-'));
811
+ const unknown = flags.filter((flag) => !TypedRouteContextFlags.isValid(flag));
812
+ if (unknown.length > 0) {
813
+ cli_output_1.CliOutput.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
814
+ return USAGE_ERROR_CODE;
815
+ }
816
+ const isWrite = flags.includes(TypedRouteContextFlags.WRITE);
817
+ const isCheck = flags.includes(TypedRouteContextFlags.CHECK);
818
+ if (isWrite && isCheck) {
819
+ cli_output_1.CliOutput.error(`devz codemod: ${TypedRouteContextFlags.WRITE} and ${TypedRouteContextFlags.CHECK} contradict each other\n${USAGE}`);
820
+ return USAGE_ERROR_CODE;
821
+ }
822
+ const refusal = files_1.CodemodFiles.refusal({
823
+ command: 'typed-route-context',
824
+ isWrite,
825
+ isAll: flags.includes(TypedRouteContextFlags.ALL),
826
+ paths,
827
+ });
828
+ if (refusal) {
829
+ cli_output_1.CliOutput.error(`${refusal}\n${USAGE}`);
830
+ return USAGE_ERROR_CODE;
831
+ }
832
+ let typescript;
833
+ try {
834
+ const loaded = await import('typescript');
835
+ typescript = loaded.default;
836
+ }
837
+ catch {
838
+ cli_output_1.CliOutput.error('devz codemod: the "typescript" package is required to read your sources');
839
+ return 1;
840
+ }
841
+ const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
842
+ let changedCount = 0;
843
+ let rewrittenCount = 0;
844
+ let refusedCount = 0;
845
+ const results = new Map();
846
+ const sources = new Map();
847
+ const dirtyFiles = new Set();
848
+ for (const target of targets) {
849
+ const files = files_1.CodemodFiles.collect({ target });
850
+ const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
851
+ if (files.length === 0 && paths.length > 0) {
852
+ cli_output_1.CliOutput.warn(`devz codemod: no source files under "${(0, node_path_1.relative)(root, target) || target}" (git ignores the path, or it holds none): nothing was read`);
853
+ }
854
+ for (const file of files) {
855
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
856
+ if (!source.includes(CONTEXT) && !source.includes(HANDLER)) {
857
+ continue;
858
+ }
859
+ const result = TypedRouteContext.rewrite({ typescript, fileName: file, source });
860
+ if (!result.changed) {
861
+ continue;
862
+ }
863
+ sources.set(file, source);
864
+ results.set(file, result);
865
+ if (dirty?.has(file)) {
866
+ dirtyFiles.add(file);
867
+ }
868
+ }
869
+ }
870
+ const kept = TypedRouteContext.keptCalls({ typescript, root, results });
871
+ const finals = new Map();
872
+ for (const [file, first] of results) {
873
+ const keep = kept.get(file);
874
+ finals.set(file, keep
875
+ ? TypedRouteContext.rewrite({
876
+ typescript,
877
+ fileName: file,
878
+ source: sources.get(file) ?? '',
879
+ keep,
880
+ })
881
+ : first);
882
+ }
883
+ const remaining = TypedRouteContext.remainingErrors({ typescript, root, results: finals });
884
+ for (const [file, result] of finals) {
885
+ const keep = kept.get(file);
886
+ const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
887
+ if (dirtyFiles.has(file)) {
888
+ refusedCount += 1;
889
+ cli_output_1.CliOutput.warn(`refused ${shown} has local changes (commit, stash or "git add" them, then run again)`);
890
+ continue;
891
+ }
892
+ changedCount += 1;
893
+ rewrittenCount += result.rewritten;
894
+ cli_output_1.CliOutput.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} place(s))`);
895
+ if (keep) {
896
+ cli_output_1.CliOutput.warn(`kept ${shown} ${keep.size} valid<T>() type argument(s): without them the method does not type-check, or a call answers unknown; compare each with the route's schema`);
897
+ }
898
+ for (const error of remaining.get(file) ?? []) {
899
+ const [line, code] = error.split(' ');
900
+ cli_output_1.CliOutput.warn(`check by hand ${shown}:${line} ${code}`);
901
+ }
902
+ if (isWrite) {
903
+ (0, node_fs_1.writeFileSync)(file, result.output);
904
+ }
905
+ }
906
+ cli_output_1.CliOutput.log(`devz codemod typed-route-context: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${rewrittenCount} place(s) ${isWrite ? 'rewritten' : 'would be rewritten'}` +
907
+ (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
908
+ if (!isWrite && changedCount > 0) {
909
+ cli_output_1.CliOutput.log(`Nothing was written. Run again with ${TypedRouteContextFlags.WRITE} to apply, then run your typecheck.`);
910
+ }
911
+ if (isWrite && refusedCount > 0) {
912
+ return 1;
913
+ }
914
+ return isCheck && changedCount > 0 ? 1 : 0;
915
+ }
916
+ }
917
+ exports.TypedRouteContextCommand = TypedRouteContextCommand;
918
+ //# sourceMappingURL=typed-route-context.js.map