@venizia/dev-configs 0.5.0-0 → 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 +251 -68
  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
@@ -4,6 +4,7 @@ exports.BindingKeysCommand = exports.BindingKeysCodemod = void 0;
4
4
  const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const files_1 = require("./files");
7
+ const cli_output_1 = require("../../common/cli-output");
7
8
  const USAGE = `Usage: devz codemod binding-keys [paths...] [--write [--all] | --check] [--import-from <module>]
8
9
 
9
10
  Rewrites the raw binding keys of the @venizia/ignis-inversion release where a key is made by BindingKeys.build<T>:
@@ -28,9 +29,12 @@ It rewrites a call named get, gets, getBinding, bind, isBound or unbind whose ar
28
29
  test. A string key, a substitution-free template literal, a { namespace, key } literal and a template written
29
30
  \${namespace}.Name or \${namespace}.\${name} are rewritten. These are listed
30
31
  as "manual" and left alone: a key made at run time (a template with substitutions, a call) and a Symbol key (symbols are no
31
- longer keys). A key that is a const of the file (const MAILER = 'services.Mailer') is rewritten where it is declared. Any
32
- other name or property (Keys.MAILER) is left alone without a line: it may already be a built key, and your typecheck
33
- names a raw one.
32
+ longer keys). A key written Foo.name or this.constructor.name (a string TypeScript's own lib declares) is wrapped in
33
+ place. A key held in a name (MAILER, Keys.MAILER) is built where it is declared, in any file of the run: a const, a
34
+ readonly property or a property of an object literal, with a string initializer and no type annotation. Its type is the
35
+ one type its use sites claim (get<Mailer>, the type of a decorated parameter), else unknown (listed as "type"); the use
36
+ sites are not edited. A name declared another way (a let, an annotation, a parameter, a call, a package you do not own)
37
+ is listed as "manual". build throws on an empty key, so a computed constant that comes out '' now throws when its class loads.
34
38
 
35
39
  BindingKeys is imported from the module the file already takes inject from, else from the first @venizia/ignis import,
36
40
  or from --import-from <module>; a file with none of them is listed as manual and not rewritten. An existing import of
@@ -45,7 +49,7 @@ It reads TypeScript files (.ts, .tsx, .mts, .cts). A .js, .cjs or .mjs file is n
45
49
  --help print this text and exit
46
50
 
47
51
  With no flag it lists what would change and writes nothing. Inside a git repository it reads the files git knows, and
48
- --write refuses a file with local changes: commit or stash it first, so git can undo it.
52
+ --write refuses a file with local changes: commit, stash or "git add" it first, so git can undo it.
49
53
  There is no --reverse: a downgrade restores the files from git.`;
50
54
  /** A usage error: nothing was read or written. */
51
55
  const USAGE_ERROR_CODE = 2;
@@ -58,6 +62,8 @@ const KEY_DECORATORS = new Set(['inject', 'provide']);
58
62
  /** Where a file already imports the container API from. */
59
63
  const IGNIS_MODULE = /^@venizia\/ignis(?:-kernel|-inversion)?$/;
60
64
  const BUILDER = 'BindingKeys';
65
+ /** A declaration file of TypeScript's own `lib` (where `Function.name` is declared). */
66
+ const LIB_FILE = /[\\/]typescript[\\/]lib[\\/]lib\.[^\\/]*\.d\.ts$/;
61
67
  /** The classes and interfaces whose key methods are the container's. */
62
68
  const CONTAINER_TYPES = new Set([
63
69
  'IContainer',
@@ -146,8 +152,35 @@ class BindingKeysCodemod {
146
152
  }
147
153
  return BUILDER;
148
154
  }
155
+ /**
156
+ * The type a key constant is built with: the one type its use sites claim, else `undefined` (`unknown`). A type is copied as
157
+ * text into the declaration's file, so it counts only when every name in it means the same symbol at each use site and
158
+ * at the declaration (a type of another file, not imported there, would not compile); no import is added.
159
+ */
160
+ static agreedType(opts) {
161
+ const { typescript: ts, checker, entry } = opts;
162
+ const named = entry.claims.filter((claim) => claim.text !== undefined);
163
+ const texts = new Set(named.map((claim) => claim.text));
164
+ if (texts.size !== 1) {
165
+ return undefined;
166
+ }
167
+ // An exported declaration has a local symbol and an export symbol; an import resolves to the export one.
168
+ const dealias = (symbol) => symbol === undefined
169
+ ? undefined
170
+ : checker.getExportSymbolOfSymbol(symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol);
171
+ const flags = ts.SymbolFlags.Type | ts.SymbolFlags.Value | ts.SymbolFlags.Namespace | ts.SymbolFlags.Alias;
172
+ const inScope = checker.getSymbolsInScope(entry.declaration, flags);
173
+ for (const { name } of named[0].names) {
174
+ const here = dealias(inScope.find((candidate) => candidate.name === name));
175
+ if (here === undefined ||
176
+ named.some((claim) => claim.names.some((other) => other.name === name && dealias(other.symbol) !== here))) {
177
+ return undefined;
178
+ }
179
+ }
180
+ return named[0].text;
181
+ }
149
182
  static rewrite(opts) {
150
- const { typescript: ts, fileName, importFrom, program, readFile = (path) => ts.sys.readFile(path), } = opts;
183
+ const { typescript: ts, fileName, importFrom, program, readFile = (path) => ts.sys.readFile(path), claims = new Map(), } = opts;
151
184
  const language = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
152
185
  const file = program?.sourceFile ??
153
186
  ts.createSourceFile(fileName, opts.source, ts.ScriptTarget.Latest, true, language);
@@ -158,11 +191,9 @@ class BindingKeysCodemod {
158
191
  const manual = [];
159
192
  const unnamed = [];
160
193
  const handled = new Set();
161
- /** `const NAME = 'literal'` declared once in the file: a key held in a constant is rewritten where it is declared. */
162
- const constants = new Map();
163
- const duplicates = new Set();
164
194
  let rewritten = 0;
165
195
  const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
196
+ const isEditable = opts.isEditable ?? ((name) => name === file.fileName);
166
197
  const propertyOf = (node, name) => {
167
198
  for (const property of node.properties) {
168
199
  if (ts.isPropertyAssignment(property) &&
@@ -218,17 +249,115 @@ class BindingKeysCodemod {
218
249
  }
219
250
  return undefined;
220
251
  };
252
+ /** An object literal under `as const`: its properties are readonly, as a `readonly` class property is. */
253
+ const isConstObject = (node) => ts.isObjectLiteralExpression(node) &&
254
+ ts.isAsExpression(node.parent) &&
255
+ ts.isTypeReferenceNode(node.parent.type) &&
256
+ ts.isIdentifier(node.parent.type.typeName) &&
257
+ node.parent.type.typeName.text === 'const';
258
+ /** `Foo.name`, `this.constructor.name`: the `name` that TypeScript's own lib declares, so there is no constant of yours to build. Another lib string (`err.message`, `location.href`) is not a key. */
259
+ const isLibString = (value) => {
260
+ if (checker === undefined ||
261
+ !ts.isPropertyAccessExpression(value) ||
262
+ value.name.text !== 'name') {
263
+ return false;
264
+ }
265
+ const declared = checker.getSymbolAtLocation(value.name)?.declarations?.[0]?.getSourceFile();
266
+ return (declared !== undefined &&
267
+ declared.isDeclarationFile &&
268
+ LIB_FILE.test(declared.fileName) &&
269
+ (checker.getTypeAtLocation(value).flags & ts.TypeFlags.StringLike) !== 0);
270
+ };
271
+ /**
272
+ * The declaration of a key held in a name (`MAILER`, `Keys.MAILER`) that the codemod may build where it is made: a const, a
273
+ * readonly property or a property of an object literal, with a string initializer, no type annotation, in a file of the
274
+ * run (not a declaration file, not node_modules). `undefined` when the name is anything else.
275
+ */
276
+ const heldDeclaration = (value) => {
277
+ if (checker === undefined) {
278
+ return undefined;
279
+ }
280
+ const name = ts.isPropertyAccessExpression(value) ? value.name : value;
281
+ let symbol = checker.getSymbolAtLocation(name);
282
+ if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias) {
283
+ symbol = checker.getAliasedSymbol(symbol);
284
+ }
285
+ const declaration = symbol?.valueDeclaration;
286
+ const initializer = declaration !== undefined &&
287
+ (ts.isVariableDeclaration(declaration) ||
288
+ ts.isPropertyDeclaration(declaration) ||
289
+ ts.isPropertyAssignment(declaration))
290
+ ? declaration.initializer
291
+ : undefined;
292
+ if (declaration === undefined || initializer === undefined) {
293
+ return undefined;
294
+ }
295
+ const isHeld = ts.isVariableDeclaration(declaration)
296
+ ? ts.isIdentifier(declaration.name) &&
297
+ (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 &&
298
+ declaration.type === undefined
299
+ : ts.isPropertyDeclaration(declaration)
300
+ ? (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0 &&
301
+ declaration.type === undefined
302
+ : isConstObject(declaration.parent);
303
+ const declared = declaration.getSourceFile();
304
+ const type = checker.getTypeAtLocation(initializer);
305
+ if (!isHeld ||
306
+ declared.isDeclarationFile ||
307
+ declared.fileName.includes('/node_modules/') ||
308
+ !isEditable(declared.fileName) ||
309
+ !(type.flags & ts.TypeFlags.StringLike) ||
310
+ type.getProperty('valueType') !== undefined) {
311
+ return undefined;
312
+ }
313
+ return {
314
+ initializer,
315
+ key: `${declared.fileName}:${initializer.getStart(declared)}`,
316
+ declaration,
317
+ };
318
+ };
319
+ /** The names a type mentions (`Mailer`, the head of `ns.Mailer`, `typeof X`) with what each means at the use site. */
320
+ const namesOf = (type) => {
321
+ const found = new Map();
322
+ const flags = ts.SymbolFlags.Type |
323
+ ts.SymbolFlags.Value |
324
+ ts.SymbolFlags.Namespace |
325
+ ts.SymbolFlags.Alias;
326
+ const inScope = checker?.getSymbolsInScope(type, flags) ?? [];
327
+ const head = (name) => ts.isIdentifier(name) ? name.text : head(name.left);
328
+ const search = (node) => {
329
+ // `import('../mailer').Mailer` names a path that means something only from the file that wrote it.
330
+ if (ts.isImportTypeNode(node)) {
331
+ found.set(`import(${node.argument.getText()})`, undefined);
332
+ }
333
+ const name = ts.isTypeReferenceNode(node)
334
+ ? node.typeName
335
+ : ts.isTypeQueryNode(node)
336
+ ? node.exprName
337
+ : undefined;
338
+ if (name !== undefined) {
339
+ const text = head(name);
340
+ found.set(text, inScope.find((candidate) => candidate.name === text));
341
+ }
342
+ ts.forEachChild(node, search);
343
+ };
344
+ search(type);
345
+ return [...found].map(([name, symbol]) => ({ name, symbol }));
346
+ };
221
347
  /**
222
348
  * Wraps the key of one options object. `typeText` is the value type the call already claimed, or `undefined` for
223
349
  * `unknown`. Answers whether the key was rewritten.
224
350
  */
225
- const rewriteKey = (options, typeText) => {
351
+ const rewriteKey = (options, typeText, typeNode) => {
226
352
  const property = propertyOf(options, 'key');
227
353
  if (property === undefined) {
228
354
  return false;
229
355
  }
230
356
  const value = property.initializer;
231
357
  const text = typeText ?? 'unknown';
358
+ const held = ts.isIdentifier(value) || ts.isPropertyAccessExpression(value)
359
+ ? heldDeclaration(value)
360
+ : undefined;
232
361
  if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
233
362
  edits.push({
234
363
  start: value.getStart(file),
@@ -254,24 +383,23 @@ class BindingKeysCodemod {
254
383
  text: `${builder}.build<${text}>(${namespaceKeyOf(value)})`,
255
384
  });
256
385
  }
257
- else if (ts.isIdentifier(value) &&
258
- constants.has(value.text) &&
259
- !duplicates.has(value.text)) {
260
- const declaration = constants.get(value.text);
261
- if (declaration?.initializer === undefined || handled.has(declaration)) {
262
- return false;
263
- }
264
- handled.add(declaration);
386
+ else if (held !== undefined) {
387
+ // The key is built where it is declared (the claim is answered once every file is read); this site needs no edit.
388
+ const entry = claims.get(held.key) ?? { declaration: held.declaration, claims: [] };
389
+ entry.claims.push({
390
+ text: typeText,
391
+ names: typeNode === undefined ? [] : namesOf(typeNode),
392
+ });
393
+ claims.set(held.key, entry);
394
+ return false;
395
+ }
396
+ else if (isLibString(value)) {
397
+ // `Foo.name` is wrapped in place, like a literal: the type the call claimed moves into build<T>.
265
398
  edits.push({
266
- start: declaration.initializer.getStart(file),
267
- end: declaration.initializer.getEnd(),
268
- text: `${builder}.build<${text}>({ key: ${declaration.initializer.getText(file)} })`,
399
+ start: value.getStart(file),
400
+ end: value.getEnd(),
401
+ text: `${builder}.build<${text}>({ key: ${value.getText(file)} })`,
269
402
  });
270
- if (typeText === undefined) {
271
- unnamed.push(lineOf(declaration));
272
- }
273
- rewritten += 1;
274
- return true;
275
403
  }
276
404
  else if (isBuilderCall(value)) {
277
405
  if (value.typeArguments !== undefined) {
@@ -324,7 +452,11 @@ class BindingKeysCodemod {
324
452
  /** The declaration the checker resolves a call to, or `undefined` when it cannot (an unresolved receiver). */
325
453
  const declarationOf = (node) => checker?.getResolvedSignature(node)?.declaration;
326
454
  const packageNames = new Map();
327
- /** The name in the nearest package.json above `directory`, or `undefined` when there is none. */
455
+ /**
456
+ * The name in the nearest package.json above `directory` that has one, or `undefined` when there is none. A package.json
457
+ * without a name does not end the walk: an installed package ships `dist/esm/package.json` (`{ "type": "module" }`) beside
458
+ * the declarations, and the package's own file is further up.
459
+ */
328
460
  const packageNameAbove = (directory) => {
329
461
  if (packageNames.has(directory)) {
330
462
  return packageNames.get(directory);
@@ -334,15 +466,14 @@ class BindingKeysCodemod {
334
466
  let name;
335
467
  if (text !== undefined) {
336
468
  const parsed = JSON.parse(text);
337
- name =
338
- typeof parsed === 'object' &&
339
- parsed !== null &&
340
- 'name' in parsed &&
341
- typeof parsed.name === 'string'
342
- ? parsed.name
343
- : '';
344
- }
345
- else if (parent !== directory) {
469
+ if (typeof parsed === 'object' &&
470
+ parsed !== null &&
471
+ 'name' in parsed &&
472
+ typeof parsed.name === 'string') {
473
+ name = parsed.name;
474
+ }
475
+ }
476
+ if (name === undefined && parent !== directory) {
346
477
  name = packageNameAbove(parent);
347
478
  }
348
479
  packageNames.set(directory, name);
@@ -478,7 +609,7 @@ class BindingKeysCodemod {
478
609
  : decorated === undefined
479
610
  ? undefined
480
611
  : liftedTypeText(decorated);
481
- const done = rewriteKey(first, typeText);
612
+ const done = rewriteKey(first, typeText, callArgument ?? decorated);
482
613
  // The type argument moved into `build<T>`; the call no longer needs it. Comments inside it stay.
483
614
  if (done && callArgument !== undefined) {
484
615
  const open = node.expression.getEnd();
@@ -495,22 +626,36 @@ class BindingKeysCodemod {
495
626
  }
496
627
  ts.forEachChild(node, visit);
497
628
  };
498
- const collect = (node) => {
499
- if (ts.isVariableDeclaration(node) &&
500
- ts.isIdentifier(node.name) &&
501
- node.initializer !== undefined &&
502
- (ts.isStringLiteral(node.initializer) ||
503
- ts.isNoSubstitutionTemplateLiteral(node.initializer)) &&
504
- (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0) {
505
- if (constants.has(node.name.text)) {
506
- duplicates.add(node.name.text);
507
- }
508
- constants.set(node.name.text, node);
509
- }
510
- ts.forEachChild(node, collect);
511
- };
512
- collect(file);
513
629
  visit(file);
630
+ // A key constant of this file: build it with the type its use sites agree on, or the one the run settled.
631
+ const build = new Map(opts.declare);
632
+ for (const [key, entry] of claims) {
633
+ if (key.startsWith(`${file.fileName}:`) && !build.has(key) && checker !== undefined) {
634
+ build.set(key, BindingKeysCodemod.agreedType({ typescript: ts, checker, entry }));
635
+ }
636
+ }
637
+ if (build.size > 0) {
638
+ const declare = (node) => {
639
+ if ((ts.isVariableDeclaration(node) ||
640
+ ts.isPropertyDeclaration(node) ||
641
+ ts.isPropertyAssignment(node)) &&
642
+ node.initializer !== undefined &&
643
+ build.has(`${file.fileName}:${node.initializer.getStart(file)}`)) {
644
+ const type = build.get(`${file.fileName}:${node.initializer.getStart(file)}`);
645
+ edits.push({
646
+ start: node.initializer.getStart(file),
647
+ end: node.initializer.getEnd(),
648
+ text: `${builder}.build<${type ?? 'unknown'}>({ key: ${node.initializer.getText(file)} })`,
649
+ });
650
+ rewritten += 1;
651
+ if (type === undefined) {
652
+ unnamed.push(lineOf(node.initializer));
653
+ }
654
+ }
655
+ ts.forEachChild(node, declare);
656
+ };
657
+ declare(file);
658
+ }
514
659
  if (edits.length === 0) {
515
660
  return { output: source, changed: false, rewritten, unnamed, manual };
516
661
  }
@@ -564,7 +709,7 @@ class BindingKeysCommand {
564
709
  * codemod reads added, so a receiver resolves the way the project's typecheck resolves it.
565
710
  */
566
711
  static createProgram(opts) {
567
- const { typescript: ts, root, files } = opts;
712
+ const { typescript: ts, root, files, contents, withProjectFiles = false } = opts;
568
713
  const configPath = ts.findConfigFile(root, (path) => ts.sys.fileExists(path), 'tsconfig.json');
569
714
  const read = configPath === undefined
570
715
  ? undefined
@@ -584,12 +729,21 @@ class BindingKeysCommand {
584
729
  composite: false,
585
730
  allowJs: false,
586
731
  };
587
- return ts.createProgram({ rootNames: files, options });
732
+ const host = ts.createCompilerHost(options);
733
+ const readFile = host.readFile.bind(host);
734
+ // TypeScript asks with forward slashes, on Windows too.
735
+ const forward = (path) => path.replaceAll('\\', '/');
736
+ const replaced = new Map([...(contents ?? [])].map(([path, text]) => [forward(path), text]));
737
+ host.readFile = (fileName) => replaced.get(forward(fileName)) ?? readFile(fileName);
738
+ const rootNames = withProjectFiles
739
+ ? [...new Set([...files, ...(parsed?.fileNames ?? [])].map(forward))]
740
+ : files;
741
+ return ts.createProgram({ rootNames, options, host });
588
742
  }
589
743
  static async run(opts) {
590
744
  const { root, args } = opts;
591
745
  if (args.includes(BindingKeysFlags.HELP) || args.includes(BindingKeysFlags.HELP_SHORT)) {
592
- console.log(USAGE);
746
+ cli_output_1.CliOutput.log(USAGE);
593
747
  return 0;
594
748
  }
595
749
  const flags = [];
@@ -612,17 +766,17 @@ class BindingKeysCommand {
612
766
  }
613
767
  const unknown = flags.filter((flag) => !BindingKeysFlags.isValid(flag));
614
768
  if (hasImportFlag && (importFrom === undefined || importFrom.startsWith('-'))) {
615
- console.error(`devz codemod: ${BindingKeysFlags.IMPORT_FROM} needs a module\n${USAGE}`);
769
+ cli_output_1.CliOutput.error(`devz codemod: ${BindingKeysFlags.IMPORT_FROM} needs a module\n${USAGE}`);
616
770
  return USAGE_ERROR_CODE;
617
771
  }
618
772
  if (unknown.length > 0) {
619
- console.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
773
+ cli_output_1.CliOutput.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
620
774
  return USAGE_ERROR_CODE;
621
775
  }
622
776
  const isWrite = flags.includes(BindingKeysFlags.WRITE);
623
777
  const isCheck = flags.includes(BindingKeysFlags.CHECK);
624
778
  if (isWrite && isCheck) {
625
- console.error(`devz codemod: ${BindingKeysFlags.WRITE} and ${BindingKeysFlags.CHECK} contradict each other\n${USAGE}`);
779
+ cli_output_1.CliOutput.error(`devz codemod: ${BindingKeysFlags.WRITE} and ${BindingKeysFlags.CHECK} contradict each other\n${USAGE}`);
626
780
  return USAGE_ERROR_CODE;
627
781
  }
628
782
  const refusal = files_1.CodemodFiles.refusal({
@@ -632,7 +786,7 @@ class BindingKeysCommand {
632
786
  paths,
633
787
  });
634
788
  if (refusal) {
635
- console.error(`${refusal}\n${USAGE}`);
789
+ cli_output_1.CliOutput.error(`${refusal}\n${USAGE}`);
636
790
  return USAGE_ERROR_CODE;
637
791
  }
638
792
  let typescript;
@@ -641,7 +795,7 @@ class BindingKeysCommand {
641
795
  typescript = loaded.default;
642
796
  }
643
797
  catch {
644
- console.error('devz codemod: the "typescript" package is required to read your sources');
798
+ cli_output_1.CliOutput.error('devz codemod: the "typescript" package is required to read your sources');
645
799
  return 1;
646
800
  }
647
801
  const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
@@ -657,54 +811,83 @@ class BindingKeysCommand {
657
811
  files: collected.flat(),
658
812
  });
659
813
  const checker = program.getTypeChecker();
814
+ const prefilter = /\b(?:get|gets|getBinding|bind|isBound|unbind|inject|provide|build)\b/;
815
+ const editable = new Set(collected.flat().map((file) => (0, node_path_1.resolve)(file)));
816
+ const isEditable = (fileName) => editable.has((0, node_path_1.resolve)(fileName));
817
+ // First pass: every use site of a key held in a constant claims a type for the constant's declaration, which can be in
818
+ // another file. The answer is one type per declaration, so the second pass edits each declaration once.
819
+ const claims = new Map();
820
+ for (const file of collected.flat()) {
821
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
822
+ const sourceFile = program.getSourceFile(file);
823
+ if (sourceFile !== undefined && prefilter.test(source)) {
824
+ BindingKeysCodemod.rewrite({
825
+ typescript,
826
+ fileName: file,
827
+ source,
828
+ importFrom,
829
+ program: { sourceFile, checker },
830
+ claims,
831
+ isEditable,
832
+ });
833
+ }
834
+ }
835
+ const declare = new Map();
836
+ const declareFiles = new Set();
837
+ for (const [key, entry] of claims) {
838
+ declare.set(key, BindingKeysCodemod.agreedType({ typescript, checker, entry }));
839
+ declareFiles.add(entry.declaration.getSourceFile().fileName);
840
+ }
660
841
  for (const [index, target] of targets.entries()) {
661
842
  const files = collected[index];
662
843
  const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
663
844
  if (files.length === 0 && paths.length > 0) {
664
- console.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`);
845
+ 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`);
665
846
  }
666
847
  for (const file of files) {
667
848
  const source = (0, node_fs_1.readFileSync)(file, 'utf8');
668
- if (!/\b(?:get|gets|getBinding|bind|isBound|unbind|inject|provide|build)\b/.test(source)) {
849
+ const sourceFile = program.getSourceFile(file);
850
+ if (!prefilter.test(source) && !declareFiles.has(sourceFile?.fileName ?? file)) {
669
851
  continue;
670
852
  }
671
- const sourceFile = program.getSourceFile(file);
672
853
  const result = BindingKeysCodemod.rewrite({
673
854
  typescript,
674
855
  fileName: file,
675
856
  source,
676
857
  importFrom,
677
858
  program: sourceFile === undefined ? undefined : { sourceFile, checker },
859
+ declare,
860
+ isEditable,
678
861
  });
679
862
  const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
680
863
  for (const item of result.manual) {
681
864
  manualCount += 1;
682
- console.warn(`manual ${shown}:${item.line} ${item.reason}`);
865
+ cli_output_1.CliOutput.warn(`manual ${shown}:${item.line} ${item.reason}`);
683
866
  }
684
867
  for (const line of result.unnamed) {
685
868
  unnamedCount += 1;
686
- console.warn(`type ${shown}:${line} BindingKeys.build<unknown>: name the type of the value bound under this key`);
869
+ cli_output_1.CliOutput.warn(`type ${shown}:${line} BindingKeys.build<unknown>: name the type of the value bound under this key`);
687
870
  }
688
871
  if (!result.changed) {
689
872
  continue;
690
873
  }
691
874
  if (dirty?.has(file)) {
692
875
  refusedCount += 1;
693
- console.warn(`refused ${shown} has local changes (commit or stash them, then run again)`);
876
+ cli_output_1.CliOutput.warn(`refused ${shown} has local changes (commit, stash or "git add" them, then run again)`);
694
877
  continue;
695
878
  }
696
879
  changedCount += 1;
697
880
  rewrittenCount += result.rewritten;
698
- console.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} key(s))`);
881
+ cli_output_1.CliOutput.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} key(s))`);
699
882
  if (isWrite) {
700
883
  (0, node_fs_1.writeFileSync)(file, result.output);
701
884
  }
702
885
  }
703
886
  }
704
- console.log(`devz codemod binding-keys: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${rewrittenCount} key(s) ${isWrite ? 'rewritten' : 'would be rewritten'}, ${unnamedCount} to type, ${manualCount} manual` +
887
+ cli_output_1.CliOutput.log(`devz codemod binding-keys: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${rewrittenCount} key(s) ${isWrite ? 'rewritten' : 'would be rewritten'}, ${unnamedCount} to type, ${manualCount} manual` +
705
888
  (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
706
889
  if (!isWrite && changedCount > 0) {
707
- console.log(`Nothing was written. Run again with ${BindingKeysFlags.WRITE} to apply, then name each "type" site and run your typecheck.`);
890
+ cli_output_1.CliOutput.log(`Nothing was written. Run again with ${BindingKeysFlags.WRITE} to apply, then name each "type" site and run your typecheck.`);
708
891
  }
709
892
  if (isWrite && refusedCount > 0) {
710
893
  return 1;