@murky-web/typebuddy 1.3.0 → 1.4.0

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.
@@ -1,4 +1,6 @@
1
1
  import { throwsDeliberately } from "./deliberate_throw.js";
2
+ import { getTypeBuddyImportInsertion } from "./typebuddy_import.js";
3
+ import { walkOwnSubtree } from "./own_subtree.js";
2
4
 
3
5
  type AstNode = {
4
6
  type: string;
@@ -11,7 +13,7 @@ type RuleContext = {
11
13
  report(descriptor: {
12
14
  node: unknown;
13
15
  messageId: string;
14
- fix(fixer: {
16
+ fix?(fixer: {
15
17
  replaceText(node: unknown, text: string): unknown;
16
18
  insertTextBeforeRange(
17
19
  range: [number, number],
@@ -48,48 +50,34 @@ function isCallArgumentCallback(node: AstNode): boolean {
48
50
  return false;
49
51
  }
50
52
 
51
- return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
53
+ return (
54
+ Array.isArray(parent["arguments"]) && parent["arguments"].includes(node)
55
+ );
52
56
  }
53
57
 
54
- function isIdentifierNamed(node: unknown, name: string): boolean {
55
- return isNode(node) && node.type === "Identifier" && node["name"] === name;
56
- }
58
+ /**
59
+ * Return-type names whose type argument is the value an async function settles
60
+ * on. `AsyncResult` is the preferred spelling of `MaybePromise`, so a function
61
+ * annotated with it has to be read the same way — otherwise the rule goes blind
62
+ * on exactly the code the package tells people to write.
63
+ */
64
+ const AWAITED_TYPE_NAMES = new Set(["AsyncResult", "MaybePromise", "Promise"]);
57
65
 
58
- function getProgram(node: AstNode): AstNode | null {
66
+ function isAmbient(node: AstNode): boolean {
59
67
  let current: AstNode | undefined = node;
60
68
 
61
- while (current?.parent) {
69
+ while (current) {
70
+ if (current["declare"] === true) {
71
+ return true;
72
+ }
62
73
  current = current.parent;
63
74
  }
64
75
 
65
- return current?.type === "Program" ? current : null;
66
- }
67
-
68
- function isImportDeclaration(node: unknown): node is AstNode {
69
- return isNode(node) && node.type === "ImportDeclaration";
70
- }
71
-
72
- function getStringLiteralValue(node: unknown): string | null {
73
- if (!isNode(node)) {
74
- return null;
75
- }
76
-
77
- if (
78
- (node.type === "Literal" || node.type === "StringLiteral") &&
79
- typeof node["value"] === "string"
80
- ) {
81
- return node["value"];
82
- }
83
-
84
- return null;
76
+ return false;
85
77
  }
86
78
 
87
- function getProgramBody(node: AstNode): AstNode[] {
88
- if (!Array.isArray(node["body"])) {
89
- return [];
90
- }
91
-
92
- return node["body"].filter(isNode);
79
+ function isIdentifierNamed(node: unknown, name: string): boolean {
80
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
93
81
  }
94
82
 
95
83
  function isResultHelperCall(node: unknown, name: "ok" | "err"): boolean {
@@ -148,61 +136,15 @@ function getObjectPropertyValue(
148
136
  }
149
137
 
150
138
  function isBooleanLiteral(node: unknown, expected: boolean): boolean {
151
- return isNode(node) && node.type === "Literal" && node["value"] === expected;
139
+ return (
140
+ isNode(node) && node.type === "Literal" && node["value"] === expected
141
+ );
152
142
  }
153
143
 
154
144
  function isNullLiteral(node: unknown): boolean {
155
145
  return isNode(node) && node.type === "Literal" && node["value"] === null;
156
146
  }
157
147
 
158
- function hasTypeBuddyHelperImport(program: AstNode, helperName: "ok" | "err") {
159
- return getProgramBody(program).some((statement) => {
160
- if (!isImportDeclaration(statement)) {
161
- return false;
162
- }
163
-
164
- if (
165
- getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy"
166
- ) {
167
- return false;
168
- }
169
-
170
- if (statement["importKind"] === "type") {
171
- return false;
172
- }
173
-
174
- const specifiers = Array.isArray(statement["specifiers"])
175
- ? statement["specifiers"]
176
- : [];
177
-
178
- return specifiers.some((specifier) => {
179
- return (
180
- isNode(specifier) &&
181
- specifier.type === "ImportSpecifier" &&
182
- isIdentifierNamed(specifier["local"], helperName)
183
- );
184
- });
185
- });
186
- }
187
-
188
- function getTypeBuddyImportInsertRange(
189
- program: AstNode,
190
- ): [number, number] | null {
191
- const body = getProgramBody(program);
192
- const imports = body.filter(isImportDeclaration);
193
- const anchor = imports.at(-1) ?? body[0] ?? program;
194
-
195
- if (!Array.isArray(anchor["range"]) || anchor["range"].length < 2) {
196
- return null;
197
- }
198
-
199
- if (imports.length > 0) {
200
- return [anchor["range"][1], anchor["range"][1]];
201
- }
202
-
203
- return [anchor["range"][0], anchor["range"][0]];
204
- }
205
-
206
148
  const rule = {
207
149
  create(context: RuleContext) {
208
150
  const sourceCode = context.getSourceCode();
@@ -216,7 +158,9 @@ const rule = {
216
158
  const typeName = node["typeName"];
217
159
  if (!isNode(typeName) || typeName.type !== "Identifier")
218
160
  return null;
219
- return typeof typeName["name"] === "string" ? typeName["name"] : null;
161
+ return typeof typeName["name"] === "string"
162
+ ? typeName["name"]
163
+ : null;
220
164
  }
221
165
 
222
166
  function getTypeArgument(node: AstNode): AstNode | null {
@@ -227,8 +171,23 @@ const rule = {
227
171
  return firstParam;
228
172
  }
229
173
 
230
- function getPromiseTypeArgument(node: AstNode): AstNode | null {
231
- if (getTypeName(node) !== "Promise") return null;
174
+ /**
175
+ * The awaited type behind an async function's return annotation.
176
+ *
177
+ * Every spelling counts. Matching only `Promise` meant the rule read the
178
+ * return type of code it had not migrated yet and went blind the moment
179
+ * `MaybePromise` was there — so a bare `return;` in a
180
+ * `MaybePromise<void>` function never became `return ok();`, while the
181
+ * identical `Promise<void>` function was fixed. It only ever worked
182
+ * because the rename and this lookup happen in the same pass, off the
183
+ * same AST.
184
+ */
185
+ function getAwaitedTypeArgument(node: AstNode): AstNode | null {
186
+ const typeName = getTypeName(node);
187
+ if (typeName === null || !AWAITED_TYPE_NAMES.has(typeName)) {
188
+ return null;
189
+ }
190
+
232
191
  return getTypeArgument(node);
233
192
  }
234
193
 
@@ -241,32 +200,19 @@ const rule = {
241
200
  return [];
242
201
  }
243
202
 
244
- const program = getProgram(node);
245
- if (!program || hasTypeBuddyHelperImport(program, helperName)) {
246
- return [];
247
- }
248
-
249
- const insertRange = getTypeBuddyImportInsertRange(program);
250
- if (!insertRange) {
203
+ const insertion = getTypeBuddyImportInsertion(node, helperName);
204
+ if (!insertion) {
251
205
  return [];
252
206
  }
253
207
 
254
208
  scheduledHelperImports.add(helperName);
255
209
 
256
- const hasImports = insertRange[0] !== 0;
257
- const importText = hasImports
258
- ? `\nimport { ${helperName} } from "@murky-web/typebuddy";`
259
- : `import { ${helperName} } from "@murky-web/typebuddy";\n`;
260
-
261
- return [fixer.insertTextBeforeRange(insertRange, importText)];
210
+ return [
211
+ fixer.insertTextBeforeRange(insertion.range, insertion.text),
212
+ ];
262
213
  }
263
214
 
264
- function checkReturnType(node: AstNode) {
265
- if (!isAsyncFunction(node)) return;
266
- if (isCallArgumentCallback(node)) return;
267
- // Same exemption as `require-try-catch`: a deliberate throw is not a
268
- // result waiting to be wrapped.
269
- if (throwsDeliberately(node["body"])) return;
215
+ function reportPromiseReturnType(node: AstNode) {
270
216
  if (!isNode(node["returnType"])) return;
271
217
 
272
218
  const typeAnnotation = node["returnType"]["typeAnnotation"];
@@ -283,6 +229,33 @@ const rule = {
283
229
  });
284
230
  }
285
231
 
232
+ function checkReturnType(node: AstNode) {
233
+ if (!isAsyncFunction(node)) return;
234
+ if (isCallArgumentCallback(node)) return;
235
+ // Same exemption as `require-try-catch`: a deliberate throw is not a
236
+ // result waiting to be wrapped.
237
+ if (throwsDeliberately(node["body"])) return;
238
+
239
+ reportPromiseReturnType(node);
240
+ }
241
+
242
+ /**
243
+ * A type-level signature — an interface method, a function type, an
244
+ * overload — can never carry `async`, so routing it through
245
+ * `checkReturnType` meant these three visitors never fired at all.
246
+ * `Promise<T>` in a signature is the same contract the rule rewrites
247
+ * everywhere else, so it gets reported here without the async gate.
248
+ *
249
+ * Ambient declarations are the exception: `declare` describes code the
250
+ * project does not own, and rewriting a third-party framework's
251
+ * callback shape to `MaybePromise` would be a lie about that API.
252
+ */
253
+ function checkSignatureReturnType(node: AstNode) {
254
+ if (isAmbient(node)) return;
255
+
256
+ reportPromiseReturnType(node);
257
+ }
258
+
286
259
  function wrapReturnValue(
287
260
  node: AstNode,
288
261
  isAsync: boolean,
@@ -383,6 +356,95 @@ const rule = {
383
356
  }
384
357
  }
385
358
 
359
+ function collectOwnReturns(root: unknown): AstNode[] {
360
+ const returns: AstNode[] = [];
361
+
362
+ walkOwnSubtree(root, (candidate) => {
363
+ if (candidate.type === "TryStatement") {
364
+ return false;
365
+ }
366
+
367
+ if (candidate.type === "ReturnStatement") {
368
+ returns.push(candidate);
369
+ }
370
+
371
+ return true;
372
+ });
373
+
374
+ return returns;
375
+ }
376
+
377
+ function isSettledFailure(argument: unknown): boolean {
378
+ return (
379
+ (isNode(argument) &&
380
+ argument.type === "Identifier" &&
381
+ argument["name"] === "FAILED_PROMISE") ||
382
+ isResultHelperCall(argument, "err")
383
+ );
384
+ }
385
+
386
+ /**
387
+ * Push a single `return` inside a catch block towards `err()`.
388
+ *
389
+ * Only the lossless rewrites carry a fix. Replacing
390
+ * `return ok("defaults")` with `return err()` would silently drop the
391
+ * author's fallback, and the old behaviour — appending `return err()`
392
+ * after it — produced unreachable code and a report that could never be
393
+ * satisfied. Where the fallback matters, moving it into the try block is
394
+ * a decision the author has to make, so the rule reports and stops.
395
+ */
396
+ function reportCatchReturn(tryNode: AstNode, statement: AstNode) {
397
+ const argument = statement["argument"];
398
+
399
+ if (isSettledFailure(argument)) return;
400
+
401
+ // `return;` — adding the result is pure addition, nothing is lost.
402
+ if (!isNode(argument)) {
403
+ context.report({
404
+ node: statement,
405
+ messageId: "returnFailedPromise",
406
+ fix(fixer) {
407
+ return [
408
+ ...ensureResultHelperImportFixes(
409
+ tryNode,
410
+ fixer,
411
+ "err",
412
+ ),
413
+ fixer.replaceText(statement, "return err()"),
414
+ ];
415
+ },
416
+ });
417
+ return;
418
+ }
419
+
420
+ if (hasIsErrorFlag(argument, true)) {
421
+ // `{ isError: true, value: null }` says the right thing the
422
+ // long way round; `err()` is the same value.
423
+ if (isNullLiteral(getObjectPropertyValue(argument, "value"))) {
424
+ context.report({
425
+ node: argument,
426
+ messageId: "preferErrResult",
427
+ fix(fixer) {
428
+ return [
429
+ ...ensureResultHelperImportFixes(
430
+ tryNode,
431
+ fixer,
432
+ "err",
433
+ ),
434
+ fixer.replaceText(argument, "err()"),
435
+ ];
436
+ },
437
+ });
438
+ }
439
+ return;
440
+ }
441
+
442
+ context.report({
443
+ node: statement,
444
+ messageId: "returnFailedPromise",
445
+ });
446
+ }
447
+
386
448
  function processTryCatch(node: AstNode) {
387
449
  let parent = node.parent;
388
450
  let isAsync = false;
@@ -407,109 +469,89 @@ const rule = {
407
469
 
408
470
  let returnType: AstNode | null = null;
409
471
  if (isNode(parentFunction["returnType"])) {
410
- const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
472
+ const typeAnnotation =
473
+ parentFunction["returnType"]["typeAnnotation"];
411
474
  if (isTypeReference(typeAnnotation)) {
412
- returnType = getPromiseTypeArgument(typeAnnotation);
475
+ returnType = getAwaitedTypeArgument(typeAnnotation);
413
476
  }
414
477
  }
415
478
 
416
- const blockBody =
417
- isNode(node["block"]) && Array.isArray(node["block"]["body"])
418
- ? node["block"]["body"]
419
- : [];
420
- for (const statement of blockBody) {
421
- if (isNode(statement) && statement.type === "ReturnStatement") {
422
- wrapReturnValue(statement, isAsync, returnType);
423
- }
479
+ // Every return the try block owns, not just the ones sitting
480
+ // directly in it. `try { if (flag) return "early"; return "late"; }`
481
+ // used to have only `"late"` wrapped, because the walk never looked
482
+ // inside the `if`.
483
+ //
484
+ // A nested `try` is left alone: the visitor fires for it separately,
485
+ // and its own catch branch has to stay the failure path rather than
486
+ // be read as another try-block return.
487
+ for (const statement of collectOwnReturns(node["block"])) {
488
+ wrapReturnValue(statement, isAsync, returnType);
424
489
  }
425
490
 
426
- if (!isNode(node["handler"]) || !isNode(node["handler"]["body"])) return;
427
- const catchBody = Array.isArray(node["handler"]["body"]["body"])
428
- ? node["handler"]["body"]["body"].filter(isNode)
429
- : [];
430
-
431
- for (const statement of catchBody) {
432
- if (
433
- statement.type === "ReturnStatement" &&
434
- isNode(statement["argument"])
435
- ) {
436
- wrapReturnValue(statement, isAsync, returnType);
437
- }
438
- }
491
+ const handler = node["handler"];
492
+ if (!isNode(handler) || !isNode(handler["body"])) return;
439
493
 
440
- const hasCorrectReturn = catchBody.some(
441
- (statement) =>
442
- statement.type === "ReturnStatement" &&
443
- isNode(statement["argument"]) &&
444
- ((statement["argument"].type === "Identifier" &&
445
- statement["argument"]["name"] === "FAILED_PROMISE") ||
446
- isResultHelperCall(statement["argument"], "err") ||
447
- hasIsErrorFlag(statement["argument"], true)),
448
- );
494
+ // The catch branch is the failure path, and it settles on `err()`
495
+ // — nothing else. A default belongs in the try block, where the
496
+ // absence is read as a value instead of being recovered from a
497
+ // throw. So a catch return is never offered `ok(...)`; feeding both
498
+ // suggestions to the same statement used to produce two reports
499
+ // with opposite fixes.
500
+ const catchReturns = collectOwnReturns(handler["body"]);
449
501
 
450
- if (!hasCorrectReturn) {
451
- context.report({
452
- node: node["handler"],
453
- messageId: "returnFailedPromise",
454
- fix(fixer) {
455
- const lastStatement = catchBody.at(-1);
456
- if (
457
- lastStatement?.type === "ReturnStatement" &&
458
- isNode(lastStatement["argument"]) &&
459
- lastStatement["argument"].type === "ObjectExpression"
460
- ) {
461
- return [
462
- ...ensureResultHelperImportFixes(
463
- node,
464
- fixer,
465
- "err",
466
- ),
467
- fixer.replaceText(
468
- lastStatement,
469
- "return err()",
470
- ),
471
- ];
472
- }
502
+ for (const statement of catchReturns) {
503
+ reportCatchReturn(node, statement);
504
+ }
473
505
 
474
- const handler = node["handler"];
475
- if (!isNode(handler)) {
476
- return null;
477
- }
506
+ // A nested try/catch inside this catch settles the branch on its
507
+ // own, so its returns count here even though `collectOwnReturns`
508
+ // hands them to the inner `processTryCatch`. Appending another
509
+ // `return err()` after them would be unreachable.
510
+ let settlesItself = false;
511
+ walkOwnSubtree(handler["body"], (candidate) => {
512
+ if (candidate.type === "ReturnStatement") {
513
+ settlesItself = true;
514
+ }
515
+ });
478
516
 
479
- const bodyRange = handler["body"];
480
- if (
481
- !isNode(bodyRange) ||
482
- !Array.isArray(bodyRange["range"])
483
- ) {
484
- return null;
485
- }
517
+ if (settlesItself) return;
486
518
 
487
- return [
488
- ...ensureResultHelperImportFixes(
489
- node,
490
- fixer,
491
- "err",
492
- ),
493
- fixer.insertTextBeforeRange(
494
- [
495
- bodyRange["range"][1] - 1,
496
- bodyRange["range"][1] - 1,
497
- ],
498
- "return err(); ",
499
- ),
500
- ];
501
- },
502
- });
503
- }
519
+ context.report({
520
+ node: handler,
521
+ messageId: "returnFailedPromise",
522
+ fix(fixer) {
523
+ const handlerBody = handler["body"];
524
+ if (
525
+ !isNode(handlerBody) ||
526
+ !Array.isArray(handlerBody["range"])
527
+ ) {
528
+ return null;
529
+ }
530
+
531
+ return [
532
+ ...ensureResultHelperImportFixes(node, fixer, "err"),
533
+ fixer.insertTextBeforeRange(
534
+ [
535
+ handlerBody["range"][1] - 1,
536
+ handlerBody["range"][1] - 1,
537
+ ],
538
+ // The newline matters: `catch { log() }` would
539
+ // otherwise become `catch { log() return err(); }`,
540
+ // which does not parse.
541
+ "\nreturn err();\n",
542
+ ),
543
+ ];
544
+ },
545
+ });
504
546
  }
505
547
 
506
548
  return {
507
549
  FunctionDeclaration: checkReturnType,
508
550
  FunctionExpression: checkReturnType,
509
551
  ArrowFunctionExpression: checkReturnType,
510
- TSDeclareFunction: checkReturnType,
511
- TSFunctionType: checkReturnType,
512
- TSMethodSignature: checkReturnType,
552
+ TSDeclareFunction: checkSignatureReturnType,
553
+ TSFunctionType: checkSignatureReturnType,
554
+ TSMethodSignature: checkSignatureReturnType,
513
555
  TryStatement: processTryCatch,
514
556
  };
515
557
  },
@@ -17,8 +17,12 @@ const rule = {
17
17
  const undefinedType = node.types.find(
18
18
  (typeNode) => typeNode.type === "TSUndefinedKeyword",
19
19
  );
20
+ // `null | undefined` has no non-nullish member to name, and rewriting
21
+ // it to `Optional<null>` only restated it with more syntax.
20
22
  const otherType = node.types.find(
21
- (typeNode) => typeNode.type !== "TSUndefinedKeyword",
23
+ (typeNode) =>
24
+ typeNode.type !== "TSUndefinedKeyword" &&
25
+ typeNode.type !== "TSNullKeyword",
22
26
  );
23
27
 
24
28
  if (undefinedType && otherType) {
@@ -0,0 +1,70 @@
1
+ type AstNode = {
2
+ type: string;
3
+ [key: string]: unknown;
4
+ };
5
+
6
+ const FUNCTION_TYPES = new Set([
7
+ "ArrowFunctionExpression",
8
+ "FunctionDeclaration",
9
+ "FunctionExpression",
10
+ ]);
11
+
12
+ function isNode(value: unknown): value is AstNode {
13
+ return typeof value === "object" && value !== null && "type" in value;
14
+ }
15
+
16
+ /**
17
+ * Visit every node that belongs to `root`, stopping at nested functions.
18
+ *
19
+ * Both async rules need the same notion of "this function's own code". A
20
+ * `throw` or a `return` inside a nested function belongs to that function, not
21
+ * to the one being linted, so the walk never descends into one — and `parent`
22
+ * points back up the tree, so following it would not terminate.
23
+ *
24
+ * `visit` may return `false` to keep the walk out of a node's children. That is
25
+ * how a rule declines a subtree that some other visitor already owns.
26
+ *
27
+ * @param {unknown} root - The node to start from. Visited itself, and never
28
+ * skipped for being a function.
29
+ * @param {(node: AstNode) => boolean | void} visit - Called once per node.
30
+ * Return `false` to skip that node's children.
31
+ * @returns {void}
32
+ */
33
+ function walkOwnSubtree(
34
+ root: unknown,
35
+ visit: (node: AstNode) => boolean | void,
36
+ ): void {
37
+ if (!isNode(root)) {
38
+ return;
39
+ }
40
+
41
+ const pending: AstNode[] = [root];
42
+ while (pending.length > 0) {
43
+ // `pop` on a non-empty array always yields a node; the length check above
44
+ // is the loop condition, but `noUncheckedIndexedAccess` cannot see that.
45
+ const current = pending.pop();
46
+ if (current === undefined) {
47
+ break;
48
+ }
49
+
50
+ if (visit(current) === false) {
51
+ continue;
52
+ }
53
+
54
+ for (const [key, value] of Object.entries(current)) {
55
+ if (key === "parent") {
56
+ continue;
57
+ }
58
+
59
+ const candidates = Array.isArray(value) ? value : [value];
60
+ for (const candidate of candidates) {
61
+ if (!isNode(candidate) || FUNCTION_TYPES.has(candidate.type)) {
62
+ continue;
63
+ }
64
+ pending.push(candidate);
65
+ }
66
+ }
67
+ }
68
+ }
69
+
70
+ export { walkOwnSubtree };