@murky-web/typebuddy 2.0.0 → 3.0.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.
Files changed (45) 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 +9 -8
  9. package/dist/rules/async_rule.js +45 -28
  10. package/dist/rules/deliberate_throw.js +5 -6
  11. package/dist/rules/maybe_promise_rule.js +109 -47
  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 +63 -0
  19. package/globals.d.ts +49 -44
  20. package/jsr.json +3 -2
  21. package/oxlint/index.ts +7 -5
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +87 -67
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +229 -98
  26. package/rules/maybe_rule.ts +74 -47
  27. package/rules/nullable_rule.ts +78 -50
  28. package/rules/optional_rule.ts +80 -51
  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 +117 -0
  33. package/src/empty.ts +57 -19
  34. package/src/guards.ts +96 -30
  35. package/src/ids.ts +10 -4
  36. package/src/index.ts +1 -18
  37. package/src/parse.ts +104 -25
  38. package/src/public_api.ts +22 -0
  39. package/src/result.ts +11 -9
  40. package/src/types/globals.ts +11 -11
  41. package/src/types/index.ts +21 -21
  42. package/src/types/json.ts +48 -11
  43. package/src/types/maybe_promise.ts +17 -12
  44. package/src/types/nullable.ts +2 -2
  45. package/src/types/optional.ts +6 -6
@@ -1,6 +1,7 @@
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
+ import { createUseServerGuard } from "./use_server.js";
4
5
 
5
6
  type AstNode = {
6
7
  type: string;
@@ -8,26 +9,29 @@ type AstNode = {
8
9
  [key: string]: unknown;
9
10
  };
10
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
+
11
22
  type RuleContext = {
12
- getSourceCode(): { getText(node: unknown): string };
23
+ getSourceCode(): {
24
+ getText(node: unknown): string;
25
+ getScope(node: unknown): unknown;
26
+ };
13
27
  report(descriptor: {
14
28
  node: unknown;
15
29
  messageId: string;
16
- fix?(fixer: {
17
- replaceText(node: unknown, text: string): unknown;
18
- insertTextBeforeRange(
19
- range: [number, number],
20
- text: string,
21
- ): unknown;
22
- }): unknown;
30
+ fix?(fixer: RuleFixer): unknown;
31
+ suggest?: RuleSuggestion[];
23
32
  }): void;
24
33
  };
25
34
 
26
- type RuleFixer = {
27
- replaceText(node: unknown, text: string): unknown;
28
- insertTextBeforeRange(range: [number, number], text: string): unknown;
29
- };
30
-
31
35
  function isNode(value: unknown): value is AstNode {
32
36
  return typeof value === "object" && value !== null && "type" in value;
33
37
  }
@@ -135,6 +139,30 @@ function getObjectPropertyValue(
135
139
  return null;
136
140
  }
137
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
+
138
166
  function isBooleanLiteral(node: unknown, expected: boolean): boolean {
139
167
  return (
140
168
  isNode(node) && node.type === "Literal" && node["value"] === expected
@@ -148,7 +176,7 @@ function isNullLiteral(node: unknown): boolean {
148
176
  const rule = {
149
177
  create(context: RuleContext) {
150
178
  const sourceCode = context.getSourceCode();
151
- const scheduledHelperImports = new Set<"ok" | "err">();
179
+ const imports = createImportPlanner(sourceCode);
152
180
 
153
181
  function isTypeReference(node: unknown): node is AstNode {
154
182
  return isNode(node) && node.type === "TSTypeReference";
@@ -174,9 +202,9 @@ const rule = {
174
202
  /**
175
203
  * The awaited type behind an async function's return annotation.
176
204
  *
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
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
180
208
  * `MaybePromise<void>` function never became `return ok();`, while the
181
209
  * identical `Promise<void>` function was fixed. It only ever worked
182
210
  * because the rename and this lookup happen in the same pass, off the
@@ -191,28 +219,59 @@ const rule = {
191
219
  return getTypeArgument(node);
192
220
  }
193
221
 
194
- function ensureResultHelperImportFixes(
195
- 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,
196
230
  fixer: RuleFixer,
197
231
  helperName: "ok" | "err",
198
- ): unknown[] {
199
- if (scheduledHelperImports.has(helperName)) {
200
- return [];
201
- }
202
-
203
- const insertion = getTypeBuddyImportInsertion(node, helperName);
204
- if (!insertion) {
205
- return [];
206
- }
232
+ rewrite: unknown,
233
+ ): unknown[] | null {
234
+ const importFixes = imports.fixes(at, fixer, helperName, "value");
235
+ if (importFixes === null) return null;
207
236
 
208
- scheduledHelperImports.add(helperName);
237
+ return [...importFixes, rewrite];
238
+ }
209
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[] {
210
250
  return [
211
- 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
+ },
212
262
  ];
213
263
  }
214
264
 
215
- 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) {
216
275
  if (!isNode(node["returnType"])) return;
217
276
 
218
277
  const typeAnnotation = node["returnType"]["typeAnnotation"];
@@ -220,23 +279,60 @@ const rule = {
220
279
  if (getTypeName(typeAnnotation) !== "Promise") return;
221
280
 
222
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
+
223
313
  context.report({
224
314
  node: typeName,
225
315
  messageId: "replaceWithMaybePromise",
226
- fix(fixer) {
227
- return fixer.replaceText(typeName, "MaybePromise");
228
- },
316
+ suggest: [
317
+ {
318
+ messageId: "suggestMaybePromise",
319
+ fix(fixer) {
320
+ return rewrite(fixer);
321
+ },
322
+ },
323
+ ],
229
324
  });
230
325
  }
231
326
 
232
327
  function checkReturnType(node: AstNode) {
233
328
  if (!isAsyncFunction(node)) return;
329
+ if (node["generator"] === true) return;
234
330
  if (isCallArgumentCallback(node)) return;
235
331
  // Same exemption as `require-try-catch`: a deliberate throw is not a
236
332
  // result waiting to be wrapped.
237
333
  if (throwsDeliberately(node["body"])) return;
238
334
 
239
- reportPromiseReturnType(node);
335
+ reportPromiseReturnType(node, true);
240
336
  }
241
337
 
242
338
  /**
@@ -249,11 +345,15 @@ const rule = {
249
345
  * Ambient declarations are the exception: `declare` describes code the
250
346
  * project does not own, and rewriting a third-party framework's
251
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.
252
352
  */
253
353
  function checkSignatureReturnType(node: AstNode) {
254
354
  if (isAmbient(node)) return;
255
355
 
256
- reportPromiseReturnType(node);
356
+ reportPromiseReturnType(node, false);
257
357
  }
258
358
 
259
359
  function wrapReturnValue(
@@ -270,14 +370,12 @@ const rule = {
270
370
  node,
271
371
  messageId: "returnVoidPromise",
272
372
  fix(fixer) {
273
- return [
274
- ...ensureResultHelperImportFixes(
275
- node,
276
- fixer,
277
- "ok",
278
- ),
279
- fixer.replaceText(node, "return ok()"),
280
- ];
373
+ return withHelperFixes(
374
+ node,
375
+ fixer,
376
+ "ok",
377
+ fixer.replaceText(node, "return ok();"),
378
+ );
281
379
  },
282
380
  });
283
381
  }
@@ -302,16 +400,25 @@ const rule = {
302
400
  const isErrorValue = getObjectPropertyValue(argument, "isError");
303
401
  const objectValue = getObjectPropertyValue(argument, "value");
304
402
 
305
- 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
+ ) {
306
411
  context.report({
307
412
  node: argument,
308
413
  messageId: "preferOkResult",
309
414
  fix(fixer) {
310
415
  const valueText = sourceCode.getText(objectValue);
311
- return [
312
- ...ensureResultHelperImportFixes(node, fixer, "ok"),
416
+ return withHelperFixes(
417
+ node,
418
+ fixer,
419
+ "ok",
313
420
  fixer.replaceText(argument, `ok(${valueText})`),
314
- ];
421
+ );
315
422
  },
316
423
  });
317
424
  return;
@@ -319,25 +426,29 @@ const rule = {
319
426
 
320
427
  if (
321
428
  isBooleanLiteral(isErrorValue, true) &&
322
- isNullLiteral(objectValue)
429
+ isNullLiteral(objectValue) &&
430
+ hasOnlyResultProperties(argument)
323
431
  ) {
324
432
  context.report({
325
433
  node: argument,
326
434
  messageId: "preferErrResult",
327
435
  fix(fixer) {
328
- return [
329
- ...ensureResultHelperImportFixes(
330
- node,
331
- fixer,
332
- "err",
333
- ),
436
+ return withHelperFixes(
437
+ node,
438
+ fixer,
439
+ "err",
334
440
  fixer.replaceText(argument, "err()"),
335
- ];
441
+ );
336
442
  },
337
443
  });
338
444
  return;
339
445
  }
340
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.
341
452
  if (
342
453
  !hasIsErrorFlag(argument, true) &&
343
454
  !hasIsErrorFlag(argument, false)
@@ -345,13 +456,18 @@ const rule = {
345
456
  context.report({
346
457
  node: argument,
347
458
  messageId: "wrapReturn",
348
- fix(fixer) {
349
- const argumentText = sourceCode.getText(argument);
350
- return [
351
- ...ensureResultHelperImportFixes(node, fixer, "ok"),
352
- fixer.replaceText(argument, `ok(${argumentText})`),
353
- ];
354
- },
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
+ ),
355
471
  });
356
472
  }
357
473
  }
@@ -386,32 +502,32 @@ const rule = {
386
502
  /**
387
503
  * Push a single `return` inside a catch block towards `err()`.
388
504
  *
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.
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.
395
511
  */
396
- function reportCatchReturn(tryNode: AstNode, statement: AstNode) {
512
+ function reportCatchReturn(statement: AstNode) {
397
513
  const argument = statement["argument"];
398
514
 
399
515
  if (isSettledFailure(argument)) return;
400
516
 
401
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.
402
520
  if (!isNode(argument)) {
403
521
  context.report({
404
522
  node: statement,
405
523
  messageId: "returnFailedPromise",
406
524
  fix(fixer) {
407
- return [
408
- ...ensureResultHelperImportFixes(
409
- tryNode,
410
- fixer,
411
- "err",
412
- ),
413
- fixer.replaceText(statement, "return err()"),
414
- ];
525
+ return withHelperFixes(
526
+ statement,
527
+ fixer,
528
+ "err",
529
+ fixer.replaceText(statement, "return err();"),
530
+ );
415
531
  },
416
532
  });
417
533
  return;
@@ -420,19 +536,20 @@ const rule = {
420
536
  if (hasIsErrorFlag(argument, true)) {
421
537
  // `{ isError: true, value: null }` says the right thing the
422
538
  // long way round; `err()` is the same value.
423
- if (isNullLiteral(getObjectPropertyValue(argument, "value"))) {
539
+ if (
540
+ isNullLiteral(getObjectPropertyValue(argument, "value")) &&
541
+ hasOnlyResultProperties(argument)
542
+ ) {
424
543
  context.report({
425
544
  node: argument,
426
545
  messageId: "preferErrResult",
427
546
  fix(fixer) {
428
- return [
429
- ...ensureResultHelperImportFixes(
430
- tryNode,
431
- fixer,
432
- "err",
433
- ),
547
+ return withHelperFixes(
548
+ statement,
549
+ fixer,
550
+ "err",
434
551
  fixer.replaceText(argument, "err()"),
435
- ];
552
+ );
436
553
  },
437
554
  });
438
555
  }
@@ -464,6 +581,9 @@ const rule = {
464
581
  }
465
582
 
466
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;
467
587
  if (isCallArgumentCallback(parentFunction)) return;
468
588
  if (throwsDeliberately(parentFunction["body"])) return;
469
589
 
@@ -500,7 +620,7 @@ const rule = {
500
620
  const catchReturns = collectOwnReturns(handler["body"]);
501
621
 
502
622
  for (const statement of catchReturns) {
503
- reportCatchReturn(node, statement);
623
+ reportCatchReturn(statement);
504
624
  }
505
625
 
506
626
  // A nested try/catch inside this catch settles the branch on its
@@ -528,8 +648,13 @@ const rule = {
528
648
  return null;
529
649
  }
530
650
 
531
- return [
532
- ...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",
533
658
  fixer.insertTextBeforeRange(
534
659
  [
535
660
  handlerBody["range"][1] - 1,
@@ -540,19 +665,22 @@ const rule = {
540
665
  // which does not parse.
541
666
  "\nreturn err();\n",
542
667
  ),
543
- ];
668
+ );
544
669
  },
545
670
  });
546
671
  }
547
672
 
673
+ const { Program, guard } = createUseServerGuard();
674
+
548
675
  return {
549
- FunctionDeclaration: checkReturnType,
550
- FunctionExpression: checkReturnType,
551
- ArrowFunctionExpression: checkReturnType,
552
- TSDeclareFunction: checkSignatureReturnType,
553
- TSFunctionType: checkSignatureReturnType,
554
- TSMethodSignature: checkSignatureReturnType,
555
- TryStatement: processTryCatch,
676
+ Program,
677
+ FunctionDeclaration: guard(checkReturnType),
678
+ FunctionExpression: guard(checkReturnType),
679
+ ArrowFunctionExpression: guard(checkReturnType),
680
+ TSDeclareFunction: guard(checkSignatureReturnType),
681
+ TSFunctionType: guard(checkSignatureReturnType),
682
+ TSMethodSignature: guard(checkSignatureReturnType),
683
+ TryStatement: guard(processTryCatch),
556
684
  };
557
685
  },
558
686
  defaultOptions: [],
@@ -563,11 +691,14 @@ const rule = {
563
691
  "Ensure async functions' return values follow the MaybePromise pattern.",
564
692
  },
565
693
  fixable: "code",
694
+ hasSuggestions: true,
566
695
  schema: [],
567
696
  messages: {
568
697
  replaceWithMaybePromise:
569
698
  "Use 'MaybePromise' instead of 'Promise' as the return type in async functions.",
699
+ suggestMaybePromise: "Replace 'Promise' with 'MaybePromise'.",
570
700
  wrapReturn: "Wrap return value with ok(value).",
701
+ suggestWrapReturn: "Wrap the return value in ok(...).",
571
702
  preferOkResult:
572
703
  "Use ok(value) instead of an inline success result object.",
573
704
  preferErrResult:
@@ -1,57 +1,84 @@
1
+ import { createImportPlanner } from "./typebuddy_import.js";
2
+
3
+ type RuleFixer = {
4
+ replaceText(node: unknown, text: string): unknown;
5
+ insertTextBeforeRange(range: [number, number], text: string): unknown;
6
+ };
7
+
1
8
  const rule = {
2
- create(context: {
3
- getSourceCode(): { getText(node: unknown): string };
4
- report(descriptor: {
5
- node: unknown;
6
- messageId: string;
7
- data: { type: string };
8
- fix(fixer: { replaceText(node: unknown, text: string): unknown }): unknown;
9
- }): void;
10
- }) {
11
- return {
12
- TSUnionType(node: {
13
- types: Array<{ type: string }>;
14
- }) {
15
- const types = node.types;
9
+ create(context: {
10
+ getSourceCode(): {
11
+ getText(node: unknown): string;
12
+ getScope(node: unknown): unknown;
13
+ };
14
+ report(descriptor: {
15
+ node: unknown;
16
+ messageId: string;
17
+ data: { type: string };
18
+ fix(fixer: RuleFixer): unknown;
19
+ }): void;
20
+ }) {
16
21
  const sourceCode = context.getSourceCode();
22
+ const imports = createImportPlanner(sourceCode);
23
+
24
+ return {
25
+ TSUnionType(node: { types: Array<{ type: string }> }) {
26
+ const types = node.types;
27
+
28
+ const nullType = types.find(
29
+ (typeNode) => typeNode.type === "TSNullKeyword",
30
+ );
31
+ const undefinedType = types.find(
32
+ (typeNode) => typeNode.type === "TSUndefinedKeyword",
33
+ );
34
+ const otherTypes = types.filter(
35
+ (typeNode) =>
36
+ typeNode.type !== "TSNullKeyword" &&
37
+ typeNode.type !== "TSUndefinedKeyword",
38
+ );
17
39
 
18
- const nullType = types.find((typeNode) => typeNode.type === "TSNullKeyword");
19
- const undefinedType = types.find(
20
- (typeNode) => typeNode.type === "TSUndefinedKeyword",
21
- );
22
- const otherTypes = types.filter(
23
- (typeNode) =>
24
- typeNode.type !== "TSNullKeyword" &&
25
- typeNode.type !== "TSUndefinedKeyword",
26
- );
40
+ if (nullType && !undefinedType && otherTypes.length === 1) {
41
+ const typeText = sourceCode.getText(otherTypes[0]);
42
+ context.report({
43
+ node,
44
+ messageId: "useMaybe",
45
+ data: { type: typeText },
46
+ fix(fixer) {
47
+ // `Maybe` has to be the package's type where the
48
+ // fix puts it: imported, or already imported.
49
+ // Another library's `Maybe` (or a local one) would
50
+ // change what the type means, so then there is no
51
+ // fix.
52
+ const importFixes = imports.fixes(
53
+ node,
54
+ fixer,
55
+ "Maybe",
56
+ "type",
57
+ );
58
+ if (importFixes === null) return null;
27
59
 
28
- if (nullType && !undefinedType && otherTypes.length === 1) {
29
- const typeText = sourceCode.getText(otherTypes[0]);
30
- context.report({
31
- node,
32
- messageId: "useMaybe",
33
- data: { type: typeText },
34
- fix(fixer) {
35
- return fixer.replaceText(node, `Maybe<${typeText}>`);
60
+ return [
61
+ ...importFixes,
62
+ fixer.replaceText(node, `Maybe<${typeText}>`),
63
+ ];
64
+ },
65
+ });
66
+ }
36
67
  },
37
- });
38
- }
39
- },
40
- };
41
- },
42
- defaultOptions: [],
43
- meta: {
44
- type: "suggestion",
45
- hasSuggestions: true,
46
- docs: {
47
- description: "Use Maybe<T> for T | null",
68
+ };
48
69
  },
49
- fixable: "code",
50
- schema: [],
51
- messages: {
52
- useMaybe: "Use Maybe<{{type}}> instead of {{type}} | null",
70
+ defaultOptions: [],
71
+ meta: {
72
+ type: "suggestion",
73
+ docs: {
74
+ description: "Use Maybe<T> for T | null",
75
+ },
76
+ fixable: "code",
77
+ schema: [],
78
+ messages: {
79
+ useMaybe: "Use Maybe<{{type}}> instead of {{type}} | null",
80
+ },
53
81
  },
54
- },
55
82
  };
56
83
 
57
84
  export { rule as maybeRule };