@murky-web/typebuddy 2.1.0 → 3.0.1

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 (46) hide show
  1. package/README.md +184 -72
  2. package/dist/collections.js +1 -2
  3. package/dist/empty.js +34 -13
  4. package/dist/guards.js +33 -9
  5. package/dist/ids.js +6 -6
  6. package/dist/oxlint.js +7 -7
  7. package/dist/parse.js +39 -15
  8. package/dist/result.js +6 -6
  9. package/dist/rules/async_rule.js +39 -25
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +99 -40
  12. package/dist/rules/maybe_rule.js +7 -5
  13. package/dist/rules/nullable_rule.js +7 -5
  14. package/dist/rules/optional_rule.js +8 -4
  15. package/dist/rules/own_subtree.js +1 -2
  16. package/dist/rules/test_file.js +63 -0
  17. package/dist/rules/typebuddy_import.js +242 -35
  18. package/dist/rules/use_server.js +1 -2
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +24 -23
  21. package/oxlint/index.ts +9 -7
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +91 -75
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +238 -111
  26. package/rules/maybe_rule.ts +76 -49
  27. package/rules/nullable_rule.ts +77 -52
  28. package/rules/optional_rule.ts +79 -53
  29. package/rules/own_subtree.ts +33 -33
  30. package/rules/test_file.ts +114 -0
  31. package/rules/typebuddy_import.ts +479 -87
  32. package/rules/use_server.ts +5 -4
  33. package/src/collections.ts +1 -1
  34. package/src/empty.ts +58 -20
  35. package/src/guards.ts +100 -34
  36. package/src/ids.ts +10 -4
  37. package/src/index.ts +1 -18
  38. package/src/parse.ts +108 -29
  39. package/src/public_api.ts +22 -0
  40. package/src/result.ts +8 -7
  41. package/src/types/globals.ts +11 -11
  42. package/src/types/index.ts +21 -21
  43. package/src/types/json.ts +48 -11
  44. package/src/types/maybe_promise.ts +17 -12
  45. package/src/types/nullable.ts +2 -2
  46. package/src/types/optional.ts +6 -6
@@ -1,6 +1,6 @@
1
1
  import { throwsDeliberately } from "./deliberate_throw.js";
2
- import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
3
2
  import { walkOwnSubtree } from "./own_subtree.js";
3
+ import { canAddImport, createImportPlanner } from "./typebuddy_import.js";
4
4
  import { createUseServerGuard } from "./use_server.js";
5
5
 
6
6
  type AstNode = {
@@ -9,26 +9,29 @@ type AstNode = {
9
9
  [key: string]: unknown;
10
10
  };
11
11
 
12
+ type RuleFixer = {
13
+ replaceText(node: unknown, text: string): unknown;
14
+ insertTextBeforeRange(range: [number, number], text: string): unknown;
15
+ };
16
+
17
+ type RuleSuggestion = {
18
+ messageId: string;
19
+ fix(fixer: RuleFixer): unknown;
20
+ };
21
+
12
22
  type RuleContext = {
13
- getSourceCode(): { getText(node: unknown): string };
23
+ getSourceCode(): {
24
+ getText(node: unknown): string;
25
+ getScope(node: unknown): unknown;
26
+ };
14
27
  report(descriptor: {
15
28
  node: unknown;
16
29
  messageId: string;
17
- fix?(fixer: {
18
- replaceText(node: unknown, text: string): unknown;
19
- insertTextBeforeRange(
20
- range: [number, number],
21
- text: string,
22
- ): unknown;
23
- }): unknown;
30
+ fix?(fixer: RuleFixer): unknown;
31
+ suggest?: RuleSuggestion[];
24
32
  }): void;
25
33
  };
26
34
 
27
- type RuleFixer = {
28
- replaceText(node: unknown, text: string): unknown;
29
- insertTextBeforeRange(range: [number, number], text: string): unknown;
30
- };
31
-
32
35
  function isNode(value: unknown): value is AstNode {
33
36
  return typeof value === "object" && value !== null && "type" in value;
34
37
  }
@@ -112,7 +115,7 @@ function hasIsErrorFlag(node: unknown, expected: boolean): boolean {
112
115
 
113
116
  function getObjectPropertyValue(
114
117
  node: unknown,
115
- propertyName: string,
118
+ propertyName: string
116
119
  ): AstNode | null {
117
120
  if (
118
121
  !isNode(node) ||
@@ -136,6 +139,30 @@ function getObjectPropertyValue(
136
139
  return null;
137
140
  }
138
141
 
142
+ const RESULT_PROPERTY_COUNT = 2;
143
+
144
+ /** An object literal with exactly `isError` and `value`: no spread, no extras. */
145
+ function hasOnlyResultProperties(node: unknown): boolean {
146
+ if (
147
+ !isNode(node) ||
148
+ node.type !== "ObjectExpression" ||
149
+ !Array.isArray(node["properties"]) ||
150
+ node["properties"].length !== RESULT_PROPERTY_COUNT
151
+ ) {
152
+ return false;
153
+ }
154
+
155
+ return node["properties"].every((property) => {
156
+ return (
157
+ isNode(property) &&
158
+ property.type === "Property" &&
159
+ property["computed"] !== true &&
160
+ (isIdentifierNamed(property["key"], "isError") ||
161
+ isIdentifierNamed(property["key"], "value"))
162
+ );
163
+ });
164
+ }
165
+
139
166
  function isBooleanLiteral(node: unknown, expected: boolean): boolean {
140
167
  return (
141
168
  isNode(node) && node.type === "Literal" && node["value"] === expected
@@ -149,7 +176,7 @@ function isNullLiteral(node: unknown): boolean {
149
176
  const rule = {
150
177
  create(context: RuleContext) {
151
178
  const sourceCode = context.getSourceCode();
152
- const scheduledHelperImports = new Set<"ok" | "err">();
179
+ const imports = createImportPlanner(sourceCode);
153
180
 
154
181
  function isTypeReference(node: unknown): node is AstNode {
155
182
  return isNode(node) && node.type === "TSTypeReference";
@@ -175,9 +202,9 @@ const rule = {
175
202
  /**
176
203
  * The awaited type behind an async function's return annotation.
177
204
  *
178
- * Every spelling counts. Matching only `Promise` meant the rule read the
179
- * return type of code it had not migrated yet and went blind the moment
180
- * `MaybePromise` was there — so a bare `return;` in a
205
+ * Every spelling counts. Matching only `Promise` meant the rule read
206
+ * the return type of code it had not migrated yet and went blind the
207
+ * moment `MaybePromise` was there — so a bare `return;` in a
181
208
  * `MaybePromise<void>` function never became `return ok();`, while the
182
209
  * identical `Promise<void>` function was fixed. It only ever worked
183
210
  * because the rename and this lookup happen in the same pass, off the
@@ -192,28 +219,59 @@ const rule = {
192
219
  return getTypeArgument(node);
193
220
  }
194
221
 
195
- function ensureResultHelperImportFixes(
196
- node: AstNode,
222
+ /**
223
+ * The fixes that rewrite `at` and make `helperName` available there, or
224
+ * `null` when the name is something else at that spot (a catch
225
+ * parameter called `err`, a local called `ok`): the rule then reports
226
+ * without offering a fix, because a fix would call the wrong thing.
227
+ */
228
+ function withHelperFixes(
229
+ at: AstNode,
197
230
  fixer: RuleFixer,
198
231
  helperName: "ok" | "err",
199
- ): unknown[] {
200
- if (scheduledHelperImports.has(helperName)) {
201
- return [];
202
- }
203
-
204
- const insertion = getTypeBuddyImportInsertion(node, helperName);
205
- if (!insertion) {
206
- return [];
207
- }
232
+ rewrite: unknown
233
+ ): unknown[] | null {
234
+ const importFixes = imports.fixes(at, fixer, helperName, "value");
235
+ if (importFixes === null) return null;
208
236
 
209
- scheduledHelperImports.add(helperName);
237
+ return [...importFixes, rewrite];
238
+ }
210
239
 
240
+ /**
241
+ * Same as `withHelperFixes`, as a suggestion. A suggestion is applied
242
+ * alone, so it carries its own import too.
243
+ */
244
+ function suggestWithHelper(
245
+ at: AstNode,
246
+ messageId: string,
247
+ helperName: "ok" | "err",
248
+ rewrite: (fixer: RuleFixer) => unknown
249
+ ): RuleSuggestion[] {
211
250
  return [
212
- fixer.insertTextBeforeRange(insertion.range, insertion.text),
251
+ {
252
+ messageId,
253
+ fix(fixer) {
254
+ return withHelperFixes(
255
+ at,
256
+ fixer,
257
+ helperName,
258
+ rewrite(fixer)
259
+ );
260
+ }
261
+ }
213
262
  ];
214
263
  }
215
264
 
216
- function reportPromiseReturnType(node: AstNode) {
265
+ /**
266
+ * `Promise<T>` to `MaybePromise<T>`.
267
+ *
268
+ * Only on a function this file defines (`own`) is it a fix: the author
269
+ * is moving that function's contract to `MaybePromise`. A function
270
+ * type, an interface method or an overload describes a shape that other
271
+ * code, often a library's, has to match, so there it is a suggestion
272
+ * the author decides on.
273
+ */
274
+ function reportPromiseReturnType(node: AstNode, own: boolean) {
217
275
  if (!isNode(node["returnType"])) return;
218
276
 
219
277
  const typeAnnotation = node["returnType"]["typeAnnotation"];
@@ -221,23 +279,60 @@ const rule = {
221
279
  if (getTypeName(typeAnnotation) !== "Promise") return;
222
280
 
223
281
  const typeName = typeAnnotation["typeName"];
282
+ const rewrite = (fixer: RuleFixer) => {
283
+ const typeImport = imports.fixes(
284
+ typeName,
285
+ fixer,
286
+ "MaybePromise",
287
+ "type"
288
+ );
289
+ if (typeImport === null) return null;
290
+
291
+ return [
292
+ ...typeImport,
293
+ fixer.replaceText(typeName, "MaybePromise")
294
+ ];
295
+ };
296
+
297
+ // The rename is the first half of a migration: the returns of the
298
+ // function then have to become `ok(...)` and `err()`, and those
299
+ // fixes need an import. In a file that cannot take one (a script)
300
+ // they are not offered, so a rename by `--fix` would leave code
301
+ // that does not compile and never heals. There it is a suggestion.
302
+ if (own && canAddImport(node)) {
303
+ context.report({
304
+ node: typeName,
305
+ messageId: "replaceWithMaybePromise",
306
+ fix(fixer) {
307
+ return rewrite(fixer);
308
+ }
309
+ });
310
+ return;
311
+ }
312
+
224
313
  context.report({
225
314
  node: typeName,
226
315
  messageId: "replaceWithMaybePromise",
227
- fix(fixer) {
228
- return fixer.replaceText(typeName, "MaybePromise");
229
- },
316
+ suggest: [
317
+ {
318
+ messageId: "suggestMaybePromise",
319
+ fix(fixer) {
320
+ return rewrite(fixer);
321
+ }
322
+ }
323
+ ]
230
324
  });
231
325
  }
232
326
 
233
327
  function checkReturnType(node: AstNode) {
234
328
  if (!isAsyncFunction(node)) return;
329
+ if (node["generator"] === true) return;
235
330
  if (isCallArgumentCallback(node)) return;
236
331
  // Same exemption as `require-try-catch`: a deliberate throw is not a
237
332
  // result waiting to be wrapped.
238
333
  if (throwsDeliberately(node["body"])) return;
239
334
 
240
- reportPromiseReturnType(node);
335
+ reportPromiseReturnType(node, true);
241
336
  }
242
337
 
243
338
  /**
@@ -250,17 +345,21 @@ const rule = {
250
345
  * Ambient declarations are the exception: `declare` describes code the
251
346
  * project does not own, and rewriting a third-party framework's
252
347
  * callback shape to `MaybePromise` would be a lie about that API.
348
+ *
349
+ * Every other signature is a suggestion, never a fix: a function type
350
+ * or an interface method is often the shape a library hands in or
351
+ * expects back, and only the author knows which.
253
352
  */
254
353
  function checkSignatureReturnType(node: AstNode) {
255
354
  if (isAmbient(node)) return;
256
355
 
257
- reportPromiseReturnType(node);
356
+ reportPromiseReturnType(node, false);
258
357
  }
259
358
 
260
359
  function wrapReturnValue(
261
360
  node: AstNode,
262
361
  isAsync: boolean,
263
- returnType: AstNode | null,
362
+ returnType: AstNode | null
264
363
  ) {
265
364
  if (!isAsync) return;
266
365
 
@@ -271,15 +370,13 @@ const rule = {
271
370
  node,
272
371
  messageId: "returnVoidPromise",
273
372
  fix(fixer) {
274
- return [
275
- ...ensureResultHelperImportFixes(
276
- node,
277
- fixer,
278
- "ok",
279
- ),
280
- fixer.replaceText(node, "return ok()"),
281
- ];
282
- },
373
+ return withHelperFixes(
374
+ node,
375
+ fixer,
376
+ "ok",
377
+ fixer.replaceText(node, "return ok();")
378
+ );
379
+ }
283
380
  });
284
381
  }
285
382
  return;
@@ -303,42 +400,55 @@ const rule = {
303
400
  const isErrorValue = getObjectPropertyValue(argument, "isError");
304
401
  const objectValue = getObjectPropertyValue(argument, "value");
305
402
 
306
- if (isBooleanLiteral(isErrorValue, false) && objectValue) {
403
+ // The inline object is only the same thing as `ok(value)` when it
404
+ // holds exactly these two properties. `{ isError: false, value,
405
+ // extra }` would lose `extra`.
406
+ if (
407
+ isBooleanLiteral(isErrorValue, false) &&
408
+ objectValue &&
409
+ hasOnlyResultProperties(argument)
410
+ ) {
307
411
  context.report({
308
412
  node: argument,
309
413
  messageId: "preferOkResult",
310
414
  fix(fixer) {
311
415
  const valueText = sourceCode.getText(objectValue);
312
- return [
313
- ...ensureResultHelperImportFixes(node, fixer, "ok"),
314
- fixer.replaceText(argument, `ok(${valueText})`),
315
- ];
316
- },
416
+ return withHelperFixes(
417
+ node,
418
+ fixer,
419
+ "ok",
420
+ fixer.replaceText(argument, `ok(${valueText})`)
421
+ );
422
+ }
317
423
  });
318
424
  return;
319
425
  }
320
426
 
321
427
  if (
322
428
  isBooleanLiteral(isErrorValue, true) &&
323
- isNullLiteral(objectValue)
429
+ isNullLiteral(objectValue) &&
430
+ hasOnlyResultProperties(argument)
324
431
  ) {
325
432
  context.report({
326
433
  node: argument,
327
434
  messageId: "preferErrResult",
328
435
  fix(fixer) {
329
- return [
330
- ...ensureResultHelperImportFixes(
331
- node,
332
- fixer,
333
- "err",
334
- ),
335
- fixer.replaceText(argument, "err()"),
336
- ];
337
- },
436
+ return withHelperFixes(
437
+ node,
438
+ fixer,
439
+ "err",
440
+ fixer.replaceText(argument, "err()")
441
+ );
442
+ }
338
443
  });
339
444
  return;
340
445
  }
341
446
 
447
+ // Anything else is a suggestion, never a fix. `return session`
448
+ // may already be a failed Result, `return await load()` may
449
+ // already be a `MaybePromise`: wrapping either in `ok(...)` turns
450
+ // a failure into a success holding a failure. Only the author
451
+ // knows what the expression is.
342
452
  if (
343
453
  !hasIsErrorFlag(argument, true) &&
344
454
  !hasIsErrorFlag(argument, false)
@@ -346,13 +456,18 @@ const rule = {
346
456
  context.report({
347
457
  node: argument,
348
458
  messageId: "wrapReturn",
349
- fix(fixer) {
350
- const argumentText = sourceCode.getText(argument);
351
- return [
352
- ...ensureResultHelperImportFixes(node, fixer, "ok"),
353
- fixer.replaceText(argument, `ok(${argumentText})`),
354
- ];
355
- },
459
+ suggest: suggestWithHelper(
460
+ node,
461
+ "suggestWrapReturn",
462
+ "ok",
463
+ (fixer) => {
464
+ const argumentText = sourceCode.getText(argument);
465
+ return fixer.replaceText(
466
+ argument,
467
+ `ok(${argumentText})`
468
+ );
469
+ }
470
+ )
356
471
  });
357
472
  }
358
473
  }
@@ -387,33 +502,33 @@ const rule = {
387
502
  /**
388
503
  * Push a single `return` inside a catch block towards `err()`.
389
504
  *
390
- * Only the lossless rewrites carry a fix. Replacing
391
- * `return ok("defaults")` with `return err()` would silently drop the
392
- * author's fallback, and the old behaviour — appending `return err()`
393
- * after it — produced unreachable code and a report that could never be
394
- * satisfied. Where the fallback matters, moving it into the try block is
395
- * a decision the author has to make, so the rule reports and stops.
505
+ * Only the lossless rewrites carry a fix. Replacing `return
506
+ * ok("defaults")` with `return err()` would silently drop the author's
507
+ * fallback, and the old behaviour — appending `return err()` after it —
508
+ * produced unreachable code and a report that could never be satisfied.
509
+ * Where the fallback matters, moving it into the try block is a
510
+ * decision the author has to make, so the rule reports and stops.
396
511
  */
397
- function reportCatchReturn(tryNode: AstNode, statement: AstNode) {
512
+ function reportCatchReturn(statement: AstNode) {
398
513
  const argument = statement["argument"];
399
514
 
400
515
  if (isSettledFailure(argument)) return;
401
516
 
402
517
  // `return;` — adding the result is pure addition, nothing is lost.
518
+ // `statement` is where the scope is read: the catch parameter is in
519
+ // scope there, and `catch (err)` makes `err()` the caught value.
403
520
  if (!isNode(argument)) {
404
521
  context.report({
405
522
  node: statement,
406
523
  messageId: "returnFailedPromise",
407
524
  fix(fixer) {
408
- return [
409
- ...ensureResultHelperImportFixes(
410
- tryNode,
411
- fixer,
412
- "err",
413
- ),
414
- fixer.replaceText(statement, "return err()"),
415
- ];
416
- },
525
+ return withHelperFixes(
526
+ statement,
527
+ fixer,
528
+ "err",
529
+ fixer.replaceText(statement, "return err();")
530
+ );
531
+ }
417
532
  });
418
533
  return;
419
534
  }
@@ -421,20 +536,21 @@ const rule = {
421
536
  if (hasIsErrorFlag(argument, true)) {
422
537
  // `{ isError: true, value: null }` says the right thing the
423
538
  // long way round; `err()` is the same value.
424
- if (isNullLiteral(getObjectPropertyValue(argument, "value"))) {
539
+ if (
540
+ isNullLiteral(getObjectPropertyValue(argument, "value")) &&
541
+ hasOnlyResultProperties(argument)
542
+ ) {
425
543
  context.report({
426
544
  node: argument,
427
545
  messageId: "preferErrResult",
428
546
  fix(fixer) {
429
- return [
430
- ...ensureResultHelperImportFixes(
431
- tryNode,
432
- fixer,
433
- "err",
434
- ),
435
- fixer.replaceText(argument, "err()"),
436
- ];
437
- },
547
+ return withHelperFixes(
548
+ statement,
549
+ fixer,
550
+ "err",
551
+ fixer.replaceText(argument, "err()")
552
+ );
553
+ }
438
554
  });
439
555
  }
440
556
  return;
@@ -442,7 +558,7 @@ const rule = {
442
558
 
443
559
  context.report({
444
560
  node: statement,
445
- messageId: "returnFailedPromise",
561
+ messageId: "returnFailedPromise"
446
562
  });
447
563
  }
448
564
 
@@ -465,6 +581,9 @@ const rule = {
465
581
  }
466
582
 
467
583
  if (!isAsync || !parentFunction) return;
584
+ // An async generator yields; what it returns is the end of the
585
+ // iteration, not a result for a caller to read.
586
+ if (parentFunction["generator"] === true) return;
468
587
  if (isCallArgumentCallback(parentFunction)) return;
469
588
  if (throwsDeliberately(parentFunction["body"])) return;
470
589
 
@@ -501,7 +620,7 @@ const rule = {
501
620
  const catchReturns = collectOwnReturns(handler["body"]);
502
621
 
503
622
  for (const statement of catchReturns) {
504
- reportCatchReturn(node, statement);
623
+ reportCatchReturn(statement);
505
624
  }
506
625
 
507
626
  // A nested try/catch inside this catch settles the branch on its
@@ -529,20 +648,25 @@ const rule = {
529
648
  return null;
530
649
  }
531
650
 
532
- return [
533
- ...ensureResultHelperImportFixes(node, fixer, "err"),
651
+ // The scope is the catch body's: `catch (err)` puts the
652
+ // caught value under the name `err`, and `return err()`
653
+ // would call it.
654
+ return withHelperFixes(
655
+ handlerBody,
656
+ fixer,
657
+ "err",
534
658
  fixer.insertTextBeforeRange(
535
659
  [
536
660
  handlerBody["range"][1] - 1,
537
- handlerBody["range"][1] - 1,
661
+ handlerBody["range"][1] - 1
538
662
  ],
539
663
  // The newline matters: `catch { log() }` would
540
664
  // otherwise become `catch { log() return err(); }`,
541
665
  // which does not parse.
542
- "\nreturn err();\n",
543
- ),
544
- ];
545
- },
666
+ "\nreturn err();\n"
667
+ )
668
+ );
669
+ }
546
670
  });
547
671
  }
548
672
 
@@ -556,7 +680,7 @@ const rule = {
556
680
  TSDeclareFunction: guard(checkSignatureReturnType),
557
681
  TSFunctionType: guard(checkSignatureReturnType),
558
682
  TSMethodSignature: guard(checkSignatureReturnType),
559
- TryStatement: guard(processTryCatch),
683
+ TryStatement: guard(processTryCatch)
560
684
  };
561
685
  },
562
686
  defaultOptions: [],
@@ -564,14 +688,17 @@ const rule = {
564
688
  type: "suggestion",
565
689
  docs: {
566
690
  description:
567
- "Ensure async functions' return values follow the MaybePromise pattern.",
691
+ "Ensure async functions' return values follow the MaybePromise pattern."
568
692
  },
569
693
  fixable: "code",
694
+ hasSuggestions: true,
570
695
  schema: [],
571
696
  messages: {
572
697
  replaceWithMaybePromise:
573
698
  "Use 'MaybePromise' instead of 'Promise' as the return type in async functions.",
699
+ suggestMaybePromise: "Replace 'Promise' with 'MaybePromise'.",
574
700
  wrapReturn: "Wrap return value with ok(value).",
701
+ suggestWrapReturn: "Wrap the return value in ok(...).",
575
702
  preferOkResult:
576
703
  "Use ok(value) instead of an inline success result object.",
577
704
  preferErrResult:
@@ -579,9 +706,9 @@ const rule = {
579
706
  returnVoidPromise:
580
707
  "Return ok() for async functions with Promise<void> return type.",
581
708
  returnFailedPromise:
582
- "Return err() in the catch block of async functions.",
583
- },
584
- },
709
+ "Return err() in the catch block of async functions."
710
+ }
711
+ }
585
712
  };
586
713
 
587
714
  export { rule as errorSafeAsyncRule };