@venizia/dev-configs 0.5.0-8 → 0.5.0-9

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 (165) hide show
  1. package/README.md +15 -11
  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.d.ts +0 -1
  18. package/dist/cli/check.js +41 -67
  19. package/dist/cli/check.js.map +1 -1
  20. package/dist/cli/clean.js +3 -2
  21. package/dist/cli/clean.js.map +1 -1
  22. package/dist/cli/codemod/any-aliases.js +13 -12
  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 +17 -16
  26. package/dist/cli/codemod/async-style.js.map +1 -1
  27. package/dist/cli/codemod/binding-keys.js +14 -13
  28. package/dist/cli/codemod/binding-keys.js.map +1 -1
  29. package/dist/cli/codemod/class-renames.d.ts +1 -1
  30. package/dist/cli/codemod/class-renames.js +30 -11
  31. package/dist/cli/codemod/class-renames.js.map +1 -1
  32. package/dist/cli/codemod/connector-imports.js +12 -11
  33. package/dist/cli/codemod/connector-imports.js.map +1 -1
  34. package/dist/cli/codemod/const-classes.d.ts +1 -1
  35. package/dist/cli/codemod/const-classes.js +21 -20
  36. package/dist/cli/codemod/const-classes.js.map +1 -1
  37. package/dist/cli/codemod/drop-redundant-casts.d.ts +6 -1
  38. package/dist/cli/codemod/drop-redundant-casts.js +27 -19
  39. package/dist/cli/codemod/drop-redundant-casts.js.map +1 -1
  40. package/dist/cli/codemod/env-get.d.ts +3 -3
  41. package/dist/cli/codemod/env-get.js +18 -17
  42. package/dist/cli/codemod/env-get.js.map +1 -1
  43. package/dist/cli/codemod/files.js +2 -2
  44. package/dist/cli/codemod/files.js.map +1 -1
  45. package/dist/cli/codemod/function-to-arrow.d.ts +76 -0
  46. package/dist/cli/codemod/function-to-arrow.js +357 -0
  47. package/dist/cli/codemod/function-to-arrow.js.map +1 -0
  48. package/dist/cli/codemod/index.js +19 -4
  49. package/dist/cli/codemod/index.js.map +1 -1
  50. package/dist/cli/codemod/namespace-functions/index.js +13 -12
  51. package/dist/cli/codemod/namespace-functions/index.js.map +1 -1
  52. package/dist/cli/codemod/typed-route-context.d.ts +27 -0
  53. package/dist/cli/codemod/typed-route-context.js +570 -0
  54. package/dist/cli/codemod/typed-route-context.js.map +1 -0
  55. package/dist/cli/index.js +5 -5
  56. package/dist/cli/index.js.map +1 -1
  57. package/dist/common/cli-output.d.ts +16 -0
  58. package/dist/common/cli-output.js +49 -0
  59. package/dist/common/cli-output.js.map +1 -0
  60. package/dist/compilers/bun.js +1 -1
  61. package/dist/compilers/bun.js.map +1 -1
  62. package/dist/linters/eslint.js +1 -1
  63. package/dist/linters/eslint.js.map +1 -1
  64. package/dist/linters/house/browser-api-patterns.d.ts +1 -3
  65. package/dist/linters/house/browser-api-patterns.js +1 -3
  66. package/dist/linters/house/browser-api-patterns.js.map +1 -1
  67. package/dist/linters/house/common.d.ts +8 -2
  68. package/dist/linters/house/common.js +8 -2
  69. package/dist/linters/house/common.js.map +1 -1
  70. package/dist/linters/house/configs.js +8 -6
  71. package/dist/linters/house/configs.js.map +1 -1
  72. package/dist/linters/house/const-class-values.rule.d.ts +2 -2
  73. package/dist/linters/house/const-class-values.rule.js +14 -5
  74. package/dist/linters/house/const-class-values.rule.js.map +1 -1
  75. package/dist/linters/house/effect-cleanup-consistency.rule.d.ts +2 -2
  76. package/dist/linters/house/effect-cleanup-consistency.rule.js +1 -1
  77. package/dist/linters/house/effect-cleanup-consistency.rule.js.map +1 -1
  78. package/dist/linters/house/framework-api-patterns.d.ts +54 -0
  79. package/dist/linters/house/framework-api-patterns.js +62 -0
  80. package/dist/linters/house/framework-api-patterns.js.map +1 -0
  81. package/dist/linters/house/framework-exports.js +3 -3
  82. package/dist/linters/house/framework-exports.js.map +1 -1
  83. package/dist/linters/house/index.d.ts +3 -4
  84. package/dist/linters/house/index.js +4 -6
  85. package/dist/linters/house/index.js.map +1 -1
  86. package/dist/linters/house/max-params-own.rule.d.ts +2 -2
  87. package/dist/linters/house/max-params-own.rule.js +1 -1
  88. package/dist/linters/house/max-params-own.rule.js.map +1 -1
  89. package/dist/linters/house/no-async-hook-callback.rule.d.ts +2 -2
  90. package/dist/linters/house/no-async-hook-callback.rule.js +1 -1
  91. package/dist/linters/house/no-async-hook-callback.rule.js.map +1 -1
  92. package/dist/linters/house/no-await-new-chain.rule.d.ts +2 -2
  93. package/dist/linters/house/no-await-new-chain.rule.js +1 -1
  94. package/dist/linters/house/no-await-new-chain.rule.js.map +1 -1
  95. package/dist/linters/house/no-await-promise-chain.rule.d.ts +2 -2
  96. package/dist/linters/house/no-await-promise-chain.rule.js +1 -1
  97. package/dist/linters/house/no-await-promise-chain.rule.js.map +1 -1
  98. package/dist/linters/house/no-inline-await.rule.d.ts +2 -2
  99. package/dist/linters/house/no-inline-await.rule.js +1 -1
  100. package/dist/linters/house/no-inline-await.rule.js.map +1 -1
  101. package/dist/linters/house/no-leaked-render.rule.d.ts +2 -2
  102. package/dist/linters/house/no-leaked-render.rule.js +1 -1
  103. package/dist/linters/house/no-leaked-render.rule.js.map +1 -1
  104. package/dist/linters/house/no-new-error.rule.d.ts +2 -2
  105. package/dist/linters/house/no-new-error.rule.js +2 -2
  106. package/dist/linters/house/no-new-error.rule.js.map +1 -1
  107. package/dist/linters/house/no-parent-import.rule.d.ts +5 -2
  108. package/dist/linters/house/no-parent-import.rule.js +5 -2
  109. package/dist/linters/house/no-parent-import.rule.js.map +1 -1
  110. package/dist/linters/house/no-return-await.rule.d.ts +2 -2
  111. package/dist/linters/house/no-return-await.rule.js +1 -1
  112. package/dist/linters/house/no-return-await.rule.js.map +1 -1
  113. package/dist/linters/house/no-shadow-framework-type.rule.d.ts +2 -2
  114. package/dist/linters/house/no-shadow-framework-type.rule.js +2 -2
  115. package/dist/linters/house/no-shadow-framework-type.rule.js.map +1 -1
  116. package/dist/linters/house/no-silent-catch.rule.d.ts +2 -2
  117. package/dist/linters/house/no-silent-catch.rule.js +3 -3
  118. package/dist/linters/house/no-silent-catch.rule.js.map +1 -1
  119. package/dist/linters/house/no-unbraced-case.rule.d.ts +2 -2
  120. package/dist/linters/house/no-unbraced-case.rule.js +1 -1
  121. package/dist/linters/house/no-unbraced-case.rule.js.map +1 -1
  122. package/dist/linters/house/plugin.d.ts +1 -1
  123. package/dist/linters/house/plugin.js +6 -5
  124. package/dist/linters/house/plugin.js.map +1 -1
  125. package/dist/linters/house/prefer-framework-api.rule.d.ts +39 -7
  126. package/dist/linters/house/prefer-framework-api.rule.js +285 -12
  127. package/dist/linters/house/prefer-framework-api.rule.js.map +1 -1
  128. package/dist/linters/house/prefer-promise-sleep.rule.d.ts +2 -2
  129. package/dist/linters/house/prefer-promise-sleep.rule.js +3 -2
  130. package/dist/linters/house/prefer-promise-sleep.rule.js.map +1 -1
  131. package/dist/linters/house/prefer-tnullable.rule.d.ts +2 -2
  132. package/dist/linters/house/prefer-tnullable.rule.js +2 -2
  133. package/dist/linters/house/prefer-tnullable.rule.js.map +1 -1
  134. package/dist/linters/house/typed-route-context.rule.d.ts +19 -0
  135. package/dist/linters/house/typed-route-context.rule.js +322 -0
  136. package/dist/linters/house/typed-route-context.rule.js.map +1 -0
  137. package/dist/linters/house/zod-schema-convention.rule.d.ts +82 -0
  138. package/dist/linters/house/zod-schema-convention.rule.js +477 -0
  139. package/dist/linters/house/zod-schema-convention.rule.js.map +1 -0
  140. package/dist/linters/oxlint.js +11 -1
  141. package/dist/linters/oxlint.js.map +1 -1
  142. package/dist/linters/react-eslint.js.map +1 -1
  143. package/dist/linters/rules/naming-convention.rule.d.ts +4 -1
  144. package/dist/linters/rules/naming-convention.rule.js +30 -1
  145. package/dist/linters/rules/naming-convention.rule.js.map +1 -1
  146. package/dist/linters/rules/no-restricted-properties.rule.js +1 -1
  147. package/dist/linters/rules/no-restricted-properties.rule.js.map +1 -1
  148. package/dist/testing/spawn.utility.js +1 -1
  149. package/dist/testing/spawn.utility.js.map +1 -1
  150. package/package.json +5 -5
  151. package/dist/checks/use-when-baseline.d.ts +0 -25
  152. package/dist/checks/use-when-baseline.js +0 -38
  153. package/dist/checks/use-when-baseline.js.map +0 -1
  154. package/dist/linters/house/framework-rule-apis.d.ts +0 -24
  155. package/dist/linters/house/framework-rule-apis.js +0 -48
  156. package/dist/linters/house/framework-rule-apis.js.map +0 -1
  157. package/dist/linters/house/public-surface.d.ts +0 -57
  158. package/dist/linters/house/public-surface.js +0 -174
  159. package/dist/linters/house/public-surface.js.map +0 -1
  160. package/dist/linters/house/published-package-configs.d.ts +0 -23
  161. package/dist/linters/house/published-package-configs.js +0 -42
  162. package/dist/linters/house/published-package-configs.js.map +0 -1
  163. package/dist/linters/house/require-use-when.rule.d.ts +0 -42
  164. package/dist/linters/house/require-use-when.rule.js +0 -175
  165. package/dist/linters/house/require-use-when.rule.js.map +0 -1
@@ -0,0 +1,570 @@
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 files_1 = require("./files");
7
+ const cli_output_1 = require("../../common/cli-output");
8
+ const USAGE = `Usage: devz codemod typed-route-context [paths...] [--write [--all] | --check]
9
+
10
+ Types route handlers from their route config (TContextOf). In a file that imports the types from @venizia/ignis or
11
+ @venizia/ignis-kernel:
12
+
13
+ - a decorated method (@api, @get, @post, @put, @patch, @del) whose configs is a name declared or imported in the
14
+ file: its TRouteContext becomes TContextOf<typeof CONFIG>, and valid<T>() on it loses its type argument;
15
+ - the same for a private method that only the handlers of one route config in its class pass their context to;
16
+ - TRouteContext<Env, Body> drops the body, and TRouteHandler<Response, Env> drops the response.
17
+
18
+ Left as they are, for you: a handler of a CRUD override, a method that serves two routes or is also called another
19
+ way, an inline or this.* config, and a context typed through an alias of yours. The typecheck then names each place
20
+ where a type you wrote by hand differs from the schema.
21
+
22
+ A config declared as IAuthRouteConfig, or in a Record of it, carries no schema type: change it to
23
+ "satisfies" first (the lint rule @venizia/typed-route-context reports each one). A handler of such a config declared
24
+ in the same file is left as it is; one imported from another file cannot be seen, so change those first.
25
+
26
+ --write write the changed files (without it, nothing is written); it needs a path, or --all
27
+ --all with --write and no path: rewrite every source file under the working directory
28
+ --check dry run that exits 1 while a file would change (for CI)
29
+ --help print this text and exit
30
+
31
+ With no flag it lists what would change and writes nothing. Inside a git repository it reads the files git
32
+ 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.`;
33
+ /** A usage error: nothing was read or written. */
34
+ const USAGE_ERROR_CODE = 2;
35
+ class TypedRouteContextFlags {
36
+ static { this.WRITE = '--write'; }
37
+ static { this.ALL = '--all'; }
38
+ static { this.CHECK = '--check'; }
39
+ static { this.HELP = '--help'; }
40
+ static { this.HELP_SHORT = '-h'; }
41
+ static { this.SCHEME_SET = new Set([
42
+ this.WRITE,
43
+ this.ALL,
44
+ this.CHECK,
45
+ this.HELP,
46
+ this.HELP_SHORT,
47
+ ]); }
48
+ static isValid(value) {
49
+ return this.SCHEME_SET.has(value);
50
+ }
51
+ }
52
+ const PACKAGES = ['@venizia/ignis', '@venizia/ignis-kernel'];
53
+ const DECORATORS = new Set(['api', 'get', 'post', 'put', 'patch', 'del']);
54
+ const CONTEXT = 'TRouteContext';
55
+ const HANDLER = 'TRouteHandler';
56
+ const TYPED = 'TContextOf';
57
+ /** One file's rewrite: the edits found so far, applied from the end of the file. */
58
+ class RouteContextFile {
59
+ static { this.IDENTIFIER = /^[A-Za-z_$][\w$]*$/; }
60
+ constructor(options) {
61
+ this.options = options;
62
+ this.edits = new Map();
63
+ /** The local names the framework's types were imported under. */
64
+ this.locals = new Map();
65
+ /** The names a `typeof` at the top of the file can read. */
66
+ this.topLevel = new Set();
67
+ /** The configs this file declares as `IAuthRouteConfig`, as a name or `Class.member`: their type holds no schema. */
68
+ this.wide = new Set();
69
+ const { typescript: ts, fileName, source } = options;
70
+ const scriptKind = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
71
+ this.file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, scriptKind);
72
+ }
73
+ rewrite() {
74
+ const { typescript: ts, source } = this.options;
75
+ this.readTopLevel();
76
+ if (this.locals.size === 0) {
77
+ return { output: source, changed: false, rewritten: 0 };
78
+ }
79
+ const visit = (node) => {
80
+ if (ts.isClassLike(node)) {
81
+ this.typeClass(node);
82
+ }
83
+ ts.forEachChild(node, visit);
84
+ };
85
+ visit(this.file);
86
+ this.dropRemovedArguments(this.file);
87
+ const rewritten = this.edits.size;
88
+ if (rewritten === 0) {
89
+ return { output: source, changed: false, rewritten };
90
+ }
91
+ this.fixImport();
92
+ let output = source;
93
+ for (const edit of [...this.edits.values()].sort((a, b) => b.start - a.start)) {
94
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
95
+ }
96
+ return { output, changed: output !== source, rewritten };
97
+ }
98
+ replace(opts) {
99
+ this.edits.set(opts.start, opts);
100
+ }
101
+ readTopLevel() {
102
+ const { typescript: ts } = this.options;
103
+ for (const statement of this.file.statements) {
104
+ if (ts.isVariableStatement(statement)) {
105
+ for (const declaration of statement.declarationList.declarations) {
106
+ const name = declaration.name.getText(this.file);
107
+ this.topLevel.add(name);
108
+ if (this.isWideDeclaration(declaration)) {
109
+ this.wide.add(name);
110
+ }
111
+ }
112
+ }
113
+ if (ts.isClassDeclaration(statement) && statement.name) {
114
+ const owner = statement.name.text;
115
+ this.topLevel.add(owner);
116
+ for (const member of statement.members) {
117
+ if (ts.isPropertyDeclaration(member) && this.isWideDeclaration(member)) {
118
+ this.wide.add(`${owner}.${member.name.getText(this.file)}`);
119
+ }
120
+ }
121
+ }
122
+ if (!ts.isImportDeclaration(statement)) {
123
+ continue;
124
+ }
125
+ const specifier = statement.moduleSpecifier.getText(this.file).slice(1, -1);
126
+ const bindings = statement.importClause?.namedBindings;
127
+ const defaultName = statement.importClause?.name;
128
+ if (defaultName) {
129
+ this.topLevel.add(defaultName.text);
130
+ }
131
+ if (!bindings) {
132
+ continue;
133
+ }
134
+ if (ts.isNamespaceImport(bindings)) {
135
+ this.topLevel.add(bindings.name.text);
136
+ continue;
137
+ }
138
+ const isFramework = PACKAGES.some((name) => specifier === name || specifier.startsWith(`${name}/`));
139
+ for (const element of bindings.elements) {
140
+ this.topLevel.add(element.name.text);
141
+ const imported = (element.propertyName ?? element.name).text;
142
+ if (isFramework && (imported === CONTEXT || imported === HANDLER || imported === TYPED)) {
143
+ this.locals.set(element.name.text, imported);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ /** Whether a declaration is typed `IAuthRouteConfig`, in an `Omit` or a `Record` too, by annotation or by `as`. */
149
+ isWideDeclaration(declaration) {
150
+ const { typescript: ts } = this.options;
151
+ const { initializer } = declaration;
152
+ const asserted = initializer && ts.isAsExpression(initializer) ? initializer.type : undefined;
153
+ const isWide = (type) => {
154
+ if (!type || !ts.isTypeReferenceNode(type)) {
155
+ return false;
156
+ }
157
+ const name = type.typeName.getText(this.file);
158
+ const [first, second] = type.typeArguments ?? [];
159
+ if (name === 'Record') {
160
+ return isWide(second);
161
+ }
162
+ return name === 'Omit' ? isWide(first) : name === 'IAuthRouteConfig';
163
+ };
164
+ return isWide(declaration.type) || isWide(asserted);
165
+ }
166
+ /** The framework type a type reference names. */
167
+ frameworkType(node) {
168
+ const { typescript: ts } = this.options;
169
+ return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)
170
+ ? this.locals.get(node.typeName.text)
171
+ : undefined;
172
+ }
173
+ /**
174
+ * The type of a `configs` expression a `typeof` can read here (`typeof Routes.CREATE`, `(typeof Routes)['/create']`);
175
+ * `undefined` for anything else.
176
+ */
177
+ configOf(options) {
178
+ const { typescript: ts } = this.options;
179
+ if (!options || !ts.isObjectLiteralExpression(options)) {
180
+ return undefined;
181
+ }
182
+ const property = options.properties.find((item) => item.name?.getText(this.file) === 'configs');
183
+ if (!property || !ts.isPropertyAssignment(property)) {
184
+ return undefined;
185
+ }
186
+ const keys = [];
187
+ let current = property.initializer;
188
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
189
+ if (ts.isPropertyAccessExpression(current)) {
190
+ keys.unshift(current.name.text);
191
+ }
192
+ else if (ts.isStringLiteralLike(current.argumentExpression)) {
193
+ keys.unshift(current.argumentExpression.text);
194
+ }
195
+ else {
196
+ return undefined;
197
+ }
198
+ current = current.expression;
199
+ }
200
+ if (!ts.isIdentifier(current) || !this.topLevel.has(current.text)) {
201
+ return undefined;
202
+ }
203
+ if (this.wide.has(current.text) || this.wide.has(`${current.text}.${keys[0]}`)) {
204
+ return undefined;
205
+ }
206
+ const firstQuoted = keys.findIndex((key) => !RouteContextFile.IDENTIFIER.test(key));
207
+ const dotted = firstQuoted === -1 ? keys : keys.slice(0, firstQuoted);
208
+ const query = `typeof ${[current.text, ...dotted].join('.')}`;
209
+ if (firstQuoted === -1) {
210
+ return query;
211
+ }
212
+ const indexed = keys
213
+ .slice(firstQuoted)
214
+ .map((key) => `['${key.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}']`);
215
+ return `(${query})${indexed.join('')}`;
216
+ }
217
+ /** Types the decorated methods of a class, and the methods only one route's handlers pass their context to. */
218
+ typeClass(node) {
219
+ const { typescript: ts } = this.options;
220
+ const forwarded = this.forwardsOf(node);
221
+ for (const member of node.members) {
222
+ if (!ts.isMethodDeclaration(member)) {
223
+ continue;
224
+ }
225
+ const decorated = (ts.getDecorators(member) ?? []).flatMap((decorator) => {
226
+ const call = decorator.expression;
227
+ return ts.isCallExpression(call) && DECORATORS.has(call.expression.getText(this.file))
228
+ ? [this.configOf(call.arguments[0])]
229
+ : [];
230
+ });
231
+ const isPrivate = ts.isPrivateIdentifier(member.name) ||
232
+ member.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.PrivateKeyword) ===
233
+ true;
234
+ // Only a private method is known to be reached from this class alone.
235
+ if (decorated.length === 0 && !isPrivate) {
236
+ continue;
237
+ }
238
+ const routes = [...decorated, ...(forwarded.get(member.name.getText(this.file)) ?? [])];
239
+ const [config] = routes;
240
+ if (config !== undefined && routes.every((route) => route === config)) {
241
+ this.typeMethod({ method: member, config });
242
+ }
243
+ }
244
+ }
245
+ /**
246
+ * The routes whose handlers pass their context straight to each method of the class. A method also reached another
247
+ * way gets an `undefined` route, which keeps it as it is.
248
+ */
249
+ forwardsOf(node) {
250
+ const { typescript: ts } = this.options;
251
+ const routes = new Map();
252
+ const passed = new Set();
253
+ const add = (method, route) => {
254
+ routes.set(method, [...(routes.get(method) ?? []), route]);
255
+ };
256
+ const visit = (current) => {
257
+ if (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
258
+ const forward = this.forwardOf(current);
259
+ if (forward) {
260
+ passed.add(forward.access);
261
+ add(forward.method, forward.config);
262
+ }
263
+ }
264
+ if (ts.isPropertyAccessExpression(current) &&
265
+ current.expression.kind === ts.SyntaxKind.ThisKeyword &&
266
+ !passed.has(current)) {
267
+ add(current.name.text, undefined);
268
+ }
269
+ ts.forEachChild(current, visit);
270
+ };
271
+ ts.forEachChild(node, visit);
272
+ return routes;
273
+ }
274
+ /** The method a `defineRoute`, `defineJSXRoute` or `bindRoute().to` call forwards its context to. */
275
+ forwardOf(call) {
276
+ const { typescript: ts } = this.options;
277
+ const callee = call.expression;
278
+ if (!ts.isPropertyAccessExpression(callee)) {
279
+ return undefined;
280
+ }
281
+ const name = callee.name.text;
282
+ const [options] = call.arguments;
283
+ let routeOptions;
284
+ if (name === 'defineRoute' || name === 'defineJSXRoute') {
285
+ routeOptions = options;
286
+ }
287
+ else if (name === 'to' &&
288
+ ts.isCallExpression(callee.expression) &&
289
+ ts.isPropertyAccessExpression(callee.expression.expression) &&
290
+ callee.expression.expression.name.text === 'bindRoute') {
291
+ routeOptions = callee.expression.arguments[0];
292
+ }
293
+ if (!routeOptions || !options || !ts.isObjectLiteralExpression(options)) {
294
+ return undefined;
295
+ }
296
+ const handler = options.properties.find((item) => item.name?.getText(this.file) === 'handler');
297
+ if (!handler || !ts.isPropertyAssignment(handler) || !ts.isArrowFunction(handler.initializer)) {
298
+ return undefined;
299
+ }
300
+ const [parameter] = handler.initializer.parameters;
301
+ let body = handler.initializer.body;
302
+ if (ts.isBlock(body)) {
303
+ const [only, ...others] = body.statements;
304
+ body =
305
+ only && others.length === 0 && ts.isReturnStatement(only) ? only.expression : undefined;
306
+ }
307
+ if (body && ts.isAwaitExpression(body)) {
308
+ body = body.expression;
309
+ }
310
+ if (!parameter ||
311
+ !body ||
312
+ !ts.isCallExpression(body) ||
313
+ !ts.isPropertyAccessExpression(body.expression) ||
314
+ body.expression.expression.kind !== ts.SyntaxKind.ThisKeyword) {
315
+ return undefined;
316
+ }
317
+ const context = parameter.name.getText(this.file);
318
+ const passes = body.arguments.some((argument) => {
319
+ if (!ts.isObjectLiteralExpression(argument)) {
320
+ return argument.getText(this.file) === context;
321
+ }
322
+ return argument.properties.some((item) => item.name?.getText(this.file) === 'context' &&
323
+ (ts.isShorthandPropertyAssignment(item)
324
+ ? context === 'context'
325
+ : ts.isPropertyAssignment(item) && item.initializer.getText(this.file) === context));
326
+ });
327
+ return passes
328
+ ? {
329
+ access: body.expression,
330
+ method: body.expression.name.text,
331
+ config: this.configOf(routeOptions),
332
+ }
333
+ : undefined;
334
+ }
335
+ /** Writes `TContextOf<typeof config>` on the method's context, and drops the type arguments of its `valid()`. */
336
+ typeMethod(opts) {
337
+ const { typescript: ts } = this.options;
338
+ const { method, config } = opts;
339
+ /** The paths that hold the retyped context, as written: `context`, `opts.context`. */
340
+ const holders = new Set();
341
+ for (const parameter of method.parameters) {
342
+ let type = parameter.type;
343
+ let path = parameter.name.getText(this.file);
344
+ if (type && ts.isTypeLiteralNode(type)) {
345
+ const member = type.members.find((item) => item.name?.getText(this.file) === 'context');
346
+ type = member && ts.isPropertySignature(member) ? member.type : undefined;
347
+ path = ts.isIdentifier(parameter.name) ? `${path}.context` : 'context';
348
+ }
349
+ if (!type || !ts.isTypeReferenceNode(type) || this.frameworkType(type) !== CONTEXT) {
350
+ continue;
351
+ }
352
+ const environment = type.typeArguments?.[0]?.getText(this.file);
353
+ const suffix = environment ? `, ${environment}` : '';
354
+ this.replace({
355
+ start: type.getStart(this.file),
356
+ end: type.getEnd(),
357
+ text: `${this.localName(TYPED)}<${config}${suffix}>`,
358
+ });
359
+ holders.add(path);
360
+ }
361
+ if (holders.size === 0 || !method.body) {
362
+ return;
363
+ }
364
+ const visit = (node) => {
365
+ if (ts.isVariableDeclaration(node) &&
366
+ ts.isObjectBindingPattern(node.name) &&
367
+ node.initializer &&
368
+ holders.has(`${node.initializer.getText(this.file)}.context`)) {
369
+ holders.add('context');
370
+ }
371
+ if (ts.isCallExpression(node) &&
372
+ node.typeArguments &&
373
+ ts.isPropertyAccessExpression(node.expression) &&
374
+ node.expression.name.text === 'valid' &&
375
+ ts.isPropertyAccessExpression(node.expression.expression) &&
376
+ node.expression.expression.name.text === 'req' &&
377
+ holders.has(node.expression.expression.expression.getText(this.file))) {
378
+ this.replace({
379
+ start: node.expression.getEnd(),
380
+ end: node.typeArguments.end + 1,
381
+ text: '',
382
+ });
383
+ }
384
+ ts.forEachChild(node, visit);
385
+ };
386
+ visit(method.body);
387
+ }
388
+ /** Drops the response arguments the framework's types no longer take, outside the contexts already retyped. */
389
+ dropRemovedArguments(node) {
390
+ const { typescript: ts } = this.options;
391
+ if (ts.isTypeReferenceNode(node) &&
392
+ node.typeArguments?.length === 2 &&
393
+ !this.edits.has(node.getStart(this.file))) {
394
+ const type = this.frameworkType(node);
395
+ const [first, second] = node.typeArguments;
396
+ const kept = type === CONTEXT ? first : type === HANDLER ? second : undefined;
397
+ if (kept) {
398
+ this.replace({
399
+ start: node.getStart(this.file),
400
+ end: node.getEnd(),
401
+ text: `${node.typeName.getText(this.file)}<${kept.getText(this.file)}>`,
402
+ });
403
+ }
404
+ }
405
+ ts.forEachChild(node, (child) => this.dropRemovedArguments(child));
406
+ }
407
+ /** The local name of a framework type, or its own name when the file does not import it yet. */
408
+ localName(type) {
409
+ return [...this.locals].find(([, imported]) => imported === type)?.[0] ?? type;
410
+ }
411
+ /** Imports `TContextOf` beside the type it replaced, and drops `TRouteContext` when nothing reads it any more. */
412
+ fixImport() {
413
+ const { typescript: ts } = this.options;
414
+ /** Whether an edit takes this node away: one that writes the name back (`TRouteContext<Env>`) does not. */
415
+ const isRemoved = (node, name) => [...this.edits.values()].some((edit) => edit.start <= node.getStart(this.file) &&
416
+ edit.end >= node.getEnd() &&
417
+ !edit.text.split(/[^\w$]+/).includes(name));
418
+ const usesTyped = [...this.edits.values()].some((edit) => edit.text.startsWith(`${this.localName(TYPED)}<`));
419
+ if (!usesTyped) {
420
+ return;
421
+ }
422
+ const contextName = this.localName(CONTEXT);
423
+ let isStillRead = false;
424
+ const visit = (node) => {
425
+ if (ts.isImportDeclaration(node)) {
426
+ return;
427
+ }
428
+ if (ts.isIdentifier(node) &&
429
+ node.text === contextName &&
430
+ !isRemoved(node.parent, contextName)) {
431
+ isStillRead = true;
432
+ }
433
+ ts.forEachChild(node, visit);
434
+ };
435
+ visit(this.file);
436
+ const needsImport = ![...this.locals.values()].includes(TYPED);
437
+ for (const statement of this.file.statements) {
438
+ if (!ts.isImportDeclaration(statement)) {
439
+ continue;
440
+ }
441
+ const bindings = statement.importClause?.namedBindings;
442
+ if (!bindings || !ts.isNamedImports(bindings)) {
443
+ continue;
444
+ }
445
+ const old = bindings.elements.find((element) => element.name.text === contextName);
446
+ if (!old) {
447
+ continue;
448
+ }
449
+ const isTypeOnly = statement.importClause?.isTypeOnly === true;
450
+ const added = isTypeOnly ? TYPED : `type ${TYPED}`;
451
+ const names = [
452
+ ...(isStillRead ? [old.getText(this.file)] : []),
453
+ ...(needsImport ? [added] : []),
454
+ ];
455
+ if (names.length > 0) {
456
+ this.replace({
457
+ start: old.getStart(this.file),
458
+ end: old.getEnd(),
459
+ text: names.join(', '),
460
+ });
461
+ return;
462
+ }
463
+ const others = bindings.elements.filter((element) => element !== old);
464
+ this.replace({
465
+ start: bindings.getStart(this.file),
466
+ end: bindings.getEnd(),
467
+ text: `{ ${others.map((element) => element.getText(this.file)).join(', ')} }`,
468
+ });
469
+ return;
470
+ }
471
+ }
472
+ }
473
+ /** Types route handlers from their route configs. */
474
+ class TypedRouteContext {
475
+ static rewrite(opts) {
476
+ return new RouteContextFile(opts).rewrite();
477
+ }
478
+ }
479
+ exports.TypedRouteContext = TypedRouteContext;
480
+ /**
481
+ * `devz codemod typed-route-context [paths...] [--write [--all] | --check]`. It is a dry run unless `--write` is
482
+ * given. `--check` is the same dry run, and exits 1 while a file would change.
483
+ */
484
+ class TypedRouteContextCommand {
485
+ static { this.USAGE = USAGE; }
486
+ static async run(opts) {
487
+ const { root, args } = opts;
488
+ if (args.includes(TypedRouteContextFlags.HELP) ||
489
+ args.includes(TypedRouteContextFlags.HELP_SHORT)) {
490
+ cli_output_1.CliOutput.log(USAGE);
491
+ return 0;
492
+ }
493
+ const flags = args.filter((argument) => argument.startsWith('-'));
494
+ const paths = args.filter((argument) => !argument.startsWith('-'));
495
+ const unknown = flags.filter((flag) => !TypedRouteContextFlags.isValid(flag));
496
+ if (unknown.length > 0) {
497
+ cli_output_1.CliOutput.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
498
+ return USAGE_ERROR_CODE;
499
+ }
500
+ const isWrite = flags.includes(TypedRouteContextFlags.WRITE);
501
+ const isCheck = flags.includes(TypedRouteContextFlags.CHECK);
502
+ if (isWrite && isCheck) {
503
+ cli_output_1.CliOutput.error(`devz codemod: ${TypedRouteContextFlags.WRITE} and ${TypedRouteContextFlags.CHECK} contradict each other\n${USAGE}`);
504
+ return USAGE_ERROR_CODE;
505
+ }
506
+ const refusal = files_1.CodemodFiles.refusal({
507
+ command: 'typed-route-context',
508
+ isWrite,
509
+ isAll: flags.includes(TypedRouteContextFlags.ALL),
510
+ paths,
511
+ });
512
+ if (refusal) {
513
+ cli_output_1.CliOutput.error(`${refusal}\n${USAGE}`);
514
+ return USAGE_ERROR_CODE;
515
+ }
516
+ let typescript;
517
+ try {
518
+ const loaded = await import('typescript');
519
+ typescript = loaded.default;
520
+ }
521
+ catch {
522
+ cli_output_1.CliOutput.error('devz codemod: the "typescript" package is required to read your sources');
523
+ return 1;
524
+ }
525
+ const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
526
+ let changedCount = 0;
527
+ let rewrittenCount = 0;
528
+ let refusedCount = 0;
529
+ for (const target of targets) {
530
+ const files = files_1.CodemodFiles.collect({ target });
531
+ const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
532
+ if (files.length === 0 && paths.length > 0) {
533
+ 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`);
534
+ }
535
+ for (const file of files) {
536
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
537
+ if (!source.includes(CONTEXT) && !source.includes(HANDLER)) {
538
+ continue;
539
+ }
540
+ const result = TypedRouteContext.rewrite({ typescript, fileName: file, source });
541
+ if (!result.changed) {
542
+ continue;
543
+ }
544
+ const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
545
+ if (dirty?.has(file)) {
546
+ refusedCount += 1;
547
+ cli_output_1.CliOutput.warn(`refused ${shown} has local changes (commit, stash or "git add" them, then run again)`);
548
+ continue;
549
+ }
550
+ changedCount += 1;
551
+ rewrittenCount += result.rewritten;
552
+ cli_output_1.CliOutput.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} place(s))`);
553
+ if (isWrite) {
554
+ (0, node_fs_1.writeFileSync)(file, result.output);
555
+ }
556
+ }
557
+ }
558
+ 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'}` +
559
+ (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
560
+ if (!isWrite && changedCount > 0) {
561
+ cli_output_1.CliOutput.log(`Nothing was written. Run again with ${TypedRouteContextFlags.WRITE} to apply, then run your typecheck.`);
562
+ }
563
+ if (isWrite && refusedCount > 0) {
564
+ return 1;
565
+ }
566
+ return isCheck && changedCount > 0 ? 1 : 0;
567
+ }
568
+ }
569
+ exports.TypedRouteContextCommand = TypedRouteContextCommand;
570
+ //# sourceMappingURL=typed-route-context.js.map