@murky-web/typebuddy 1.1.0 → 1.2.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.
@@ -19,16 +19,21 @@ type RuleContext = {
19
19
  }): void;
20
20
  };
21
21
 
22
+ type RuleFixer = {
23
+ replaceText(node: unknown, text: string): unknown;
24
+ insertTextBeforeRange(range: [number, number], text: string): unknown;
25
+ };
26
+
22
27
  function isNode(value: unknown): value is AstNode {
23
28
  return typeof value === "object" && value !== null && "type" in value;
24
29
  }
25
30
 
26
31
  function isAsyncFunction(node: AstNode): boolean {
27
- return node.async === true;
32
+ return node["async"] === true;
28
33
  }
29
34
 
30
35
  function hasTypeParameters(value: unknown): value is { params: unknown[] } {
31
- return isNode(value) && Array.isArray(value.params);
36
+ return isNode(value) && Array.isArray(value["params"]);
32
37
  }
33
38
 
34
39
  function isCallArgumentCallback(node: AstNode): boolean {
@@ -41,18 +46,55 @@ function isCallArgumentCallback(node: AstNode): boolean {
41
46
  return false;
42
47
  }
43
48
 
44
- return Array.isArray(parent.arguments) && parent.arguments.includes(node);
49
+ return Array.isArray(parent["arguments"]) && parent["arguments"].includes(node);
45
50
  }
46
51
 
47
52
  function isIdentifierNamed(node: unknown, name: string): boolean {
48
- return isNode(node) && node.type === "Identifier" && node.name === name;
53
+ return isNode(node) && node.type === "Identifier" && node["name"] === name;
54
+ }
55
+
56
+ function getProgram(node: AstNode): AstNode | null {
57
+ let current: AstNode | undefined = node;
58
+
59
+ while (current?.parent) {
60
+ current = current.parent;
61
+ }
62
+
63
+ return current?.type === "Program" ? current : null;
64
+ }
65
+
66
+ function isImportDeclaration(node: unknown): node is AstNode {
67
+ return isNode(node) && node.type === "ImportDeclaration";
68
+ }
69
+
70
+ function getStringLiteralValue(node: unknown): string | null {
71
+ if (!isNode(node)) {
72
+ return null;
73
+ }
74
+
75
+ if (
76
+ (node.type === "Literal" || node.type === "StringLiteral") &&
77
+ typeof node["value"] === "string"
78
+ ) {
79
+ return node["value"];
80
+ }
81
+
82
+ return null;
83
+ }
84
+
85
+ function getProgramBody(node: AstNode): AstNode[] {
86
+ if (!Array.isArray(node["body"])) {
87
+ return [];
88
+ }
89
+
90
+ return node["body"].filter(isNode);
49
91
  }
50
92
 
51
93
  function isResultHelperCall(node: unknown, name: "ok" | "err"): boolean {
52
94
  return (
53
95
  isNode(node) &&
54
96
  node.type === "CallExpression" &&
55
- isIdentifierNamed(node.callee, name)
97
+ isIdentifierNamed(node["callee"], name)
56
98
  );
57
99
  }
58
100
 
@@ -60,40 +102,123 @@ function hasIsErrorFlag(node: unknown, expected: boolean): boolean {
60
102
  if (
61
103
  !isNode(node) ||
62
104
  node.type !== "ObjectExpression" ||
63
- !Array.isArray(node.properties)
105
+ !Array.isArray(node["properties"])
64
106
  ) {
65
107
  return false;
66
108
  }
67
109
 
68
- return node.properties.some((property) => {
110
+ return node["properties"].some((property) => {
69
111
  return (
70
112
  isNode(property) &&
71
113
  property.type === "Property" &&
72
- isIdentifierNamed(property.key, "isError") &&
73
- isNode(property.value) &&
74
- property.value.type === "Literal" &&
75
- property.value.value === expected
114
+ isIdentifierNamed(property["key"], "isError") &&
115
+ isNode(property["value"]) &&
116
+ property["value"].type === "Literal" &&
117
+ property["value"]["value"] === expected
76
118
  );
77
119
  });
78
120
  }
79
121
 
122
+ function getObjectPropertyValue(
123
+ node: unknown,
124
+ propertyName: string,
125
+ ): AstNode | null {
126
+ if (
127
+ !isNode(node) ||
128
+ node.type !== "ObjectExpression" ||
129
+ !Array.isArray(node["properties"])
130
+ ) {
131
+ return null;
132
+ }
133
+
134
+ for (const property of node["properties"]) {
135
+ if (
136
+ isNode(property) &&
137
+ property.type === "Property" &&
138
+ isIdentifierNamed(property["key"], propertyName) &&
139
+ isNode(property["value"])
140
+ ) {
141
+ return property["value"];
142
+ }
143
+ }
144
+
145
+ return null;
146
+ }
147
+
148
+ function isBooleanLiteral(node: unknown, expected: boolean): boolean {
149
+ return isNode(node) && node.type === "Literal" && node["value"] === expected;
150
+ }
151
+
152
+ function isNullLiteral(node: unknown): boolean {
153
+ return isNode(node) && node.type === "Literal" && node["value"] === null;
154
+ }
155
+
156
+ function hasTypeBuddyHelperImport(program: AstNode, helperName: "ok" | "err") {
157
+ return getProgramBody(program).some((statement) => {
158
+ if (!isImportDeclaration(statement)) {
159
+ return false;
160
+ }
161
+
162
+ if (
163
+ getStringLiteralValue(statement["source"]) !== "@murky-web/typebuddy"
164
+ ) {
165
+ return false;
166
+ }
167
+
168
+ if (statement["importKind"] === "type") {
169
+ return false;
170
+ }
171
+
172
+ const specifiers = Array.isArray(statement["specifiers"])
173
+ ? statement["specifiers"]
174
+ : [];
175
+
176
+ return specifiers.some((specifier) => {
177
+ return (
178
+ isNode(specifier) &&
179
+ specifier.type === "ImportSpecifier" &&
180
+ isIdentifierNamed(specifier["local"], helperName)
181
+ );
182
+ });
183
+ });
184
+ }
185
+
186
+ function getTypeBuddyImportInsertRange(
187
+ program: AstNode,
188
+ ): [number, number] | null {
189
+ const body = getProgramBody(program);
190
+ const imports = body.filter(isImportDeclaration);
191
+ const anchor = imports.at(-1) ?? body[0] ?? program;
192
+
193
+ if (!Array.isArray(anchor["range"]) || anchor["range"].length < 2) {
194
+ return null;
195
+ }
196
+
197
+ if (imports.length > 0) {
198
+ return [anchor["range"][1], anchor["range"][1]];
199
+ }
200
+
201
+ return [anchor["range"][0], anchor["range"][0]];
202
+ }
203
+
80
204
  const rule = {
81
205
  create(context: RuleContext) {
82
206
  const sourceCode = context.getSourceCode();
207
+ const scheduledHelperImports = new Set<"ok" | "err">();
83
208
 
84
209
  function isTypeReference(node: unknown): node is AstNode {
85
210
  return isNode(node) && node.type === "TSTypeReference";
86
211
  }
87
212
 
88
213
  function getTypeName(node: AstNode): string | null {
89
- const typeName = node.typeName;
214
+ const typeName = node["typeName"];
90
215
  if (!isNode(typeName) || typeName.type !== "Identifier")
91
216
  return null;
92
- return typeof typeName.name === "string" ? typeName.name : null;
217
+ return typeof typeName["name"] === "string" ? typeName["name"] : null;
93
218
  }
94
219
 
95
220
  function getTypeArgument(node: AstNode): AstNode | null {
96
- const typeArguments = node.typeArguments;
221
+ const typeArguments = node["typeArguments"];
97
222
  if (!hasTypeParameters(typeArguments)) return null;
98
223
  const [firstParam] = typeArguments.params;
99
224
  if (!isNode(firstParam)) return null;
@@ -105,16 +230,45 @@ const rule = {
105
230
  return getTypeArgument(node);
106
231
  }
107
232
 
233
+ function ensureResultHelperImportFixes(
234
+ node: AstNode,
235
+ fixer: RuleFixer,
236
+ helperName: "ok" | "err",
237
+ ): unknown[] {
238
+ if (scheduledHelperImports.has(helperName)) {
239
+ return [];
240
+ }
241
+
242
+ const program = getProgram(node);
243
+ if (!program || hasTypeBuddyHelperImport(program, helperName)) {
244
+ return [];
245
+ }
246
+
247
+ const insertRange = getTypeBuddyImportInsertRange(program);
248
+ if (!insertRange) {
249
+ return [];
250
+ }
251
+
252
+ scheduledHelperImports.add(helperName);
253
+
254
+ const hasImports = insertRange[0] !== 0;
255
+ const importText = hasImports
256
+ ? `\nimport { ${helperName} } from "@murky-web/typebuddy";`
257
+ : `import { ${helperName} } from "@murky-web/typebuddy";\n`;
258
+
259
+ return [fixer.insertTextBeforeRange(insertRange, importText)];
260
+ }
261
+
108
262
  function checkReturnType(node: AstNode) {
109
263
  if (!isAsyncFunction(node)) return;
110
264
  if (isCallArgumentCallback(node)) return;
111
- if (!isNode(node.returnType)) return;
265
+ if (!isNode(node["returnType"])) return;
112
266
 
113
- const typeAnnotation = node.returnType.typeAnnotation;
267
+ const typeAnnotation = node["returnType"]["typeAnnotation"];
114
268
  if (!isTypeReference(typeAnnotation)) return;
115
269
  if (getTypeName(typeAnnotation) !== "Promise") return;
116
270
 
117
- const typeName = typeAnnotation.typeName;
271
+ const typeName = typeAnnotation["typeName"];
118
272
  context.report({
119
273
  node: typeName,
120
274
  messageId: "replaceWithMaybePromise",
@@ -131,17 +285,21 @@ const rule = {
131
285
  ) {
132
286
  if (!isAsync) return;
133
287
 
134
- const argument = node.argument;
288
+ const argument = node["argument"];
135
289
  if (!isNode(argument)) {
136
290
  if (returnType?.type === "TSVoidKeyword") {
137
291
  context.report({
138
292
  node,
139
293
  messageId: "returnVoidPromise",
140
294
  fix(fixer) {
141
- return fixer.replaceText(
142
- node,
143
- "return { isError: false, value: undefined }",
144
- );
295
+ return [
296
+ ...ensureResultHelperImportFixes(
297
+ node,
298
+ fixer,
299
+ "ok",
300
+ ),
301
+ fixer.replaceText(node, "return ok()"),
302
+ ];
145
303
  },
146
304
  });
147
305
  }
@@ -150,8 +308,8 @@ const rule = {
150
308
 
151
309
  if (
152
310
  argument.type === "Identifier" &&
153
- (argument.name === "VOID_PROMISE" ||
154
- argument.name === "FAILED_PROMISE")
311
+ (argument["name"] === "VOID_PROMISE" ||
312
+ argument["name"] === "FAILED_PROMISE")
155
313
  ) {
156
314
  return;
157
315
  }
@@ -163,6 +321,45 @@ const rule = {
163
321
  return;
164
322
  }
165
323
 
324
+ const isErrorValue = getObjectPropertyValue(argument, "isError");
325
+ const objectValue = getObjectPropertyValue(argument, "value");
326
+
327
+ if (isBooleanLiteral(isErrorValue, false) && objectValue) {
328
+ context.report({
329
+ node: argument,
330
+ messageId: "preferOkResult",
331
+ fix(fixer) {
332
+ const valueText = sourceCode.getText(objectValue);
333
+ return [
334
+ ...ensureResultHelperImportFixes(node, fixer, "ok"),
335
+ fixer.replaceText(argument, `ok(${valueText})`),
336
+ ];
337
+ },
338
+ });
339
+ return;
340
+ }
341
+
342
+ if (
343
+ isBooleanLiteral(isErrorValue, true) &&
344
+ isNullLiteral(objectValue)
345
+ ) {
346
+ context.report({
347
+ node: argument,
348
+ messageId: "preferErrResult",
349
+ fix(fixer) {
350
+ return [
351
+ ...ensureResultHelperImportFixes(
352
+ node,
353
+ fixer,
354
+ "err",
355
+ ),
356
+ fixer.replaceText(argument, "err()"),
357
+ ];
358
+ },
359
+ });
360
+ return;
361
+ }
362
+
166
363
  if (
167
364
  !hasIsErrorFlag(argument, true) &&
168
365
  !hasIsErrorFlag(argument, false)
@@ -172,10 +369,10 @@ const rule = {
172
369
  messageId: "wrapReturn",
173
370
  fix(fixer) {
174
371
  const argumentText = sourceCode.getText(argument);
175
- return fixer.replaceText(
176
- argument,
177
- `{ value: ${argumentText}, isError: false }`,
178
- );
372
+ return [
373
+ ...ensureResultHelperImportFixes(node, fixer, "ok"),
374
+ fixer.replaceText(argument, `ok(${argumentText})`),
375
+ ];
179
376
  },
180
377
  });
181
378
  }
@@ -192,7 +389,7 @@ const rule = {
192
389
  parent.type === "FunctionExpression" ||
193
390
  parent.type === "ArrowFunctionExpression"
194
391
  ) {
195
- isAsync = parent.async === true;
392
+ isAsync = parent["async"] === true;
196
393
  parentFunction = parent;
197
394
  break;
198
395
  }
@@ -203,16 +400,16 @@ const rule = {
203
400
  if (isCallArgumentCallback(parentFunction)) return;
204
401
 
205
402
  let returnType: AstNode | null = null;
206
- if (isNode(parentFunction.returnType)) {
207
- const typeAnnotation = parentFunction.returnType.typeAnnotation;
403
+ if (isNode(parentFunction["returnType"])) {
404
+ const typeAnnotation = parentFunction["returnType"]["typeAnnotation"];
208
405
  if (isTypeReference(typeAnnotation)) {
209
406
  returnType = getPromiseTypeArgument(typeAnnotation);
210
407
  }
211
408
  }
212
409
 
213
410
  const blockBody =
214
- isNode(node.block) && Array.isArray(node.block.body)
215
- ? node.block.body
411
+ isNode(node["block"]) && Array.isArray(node["block"]["body"])
412
+ ? node["block"]["body"]
216
413
  : [];
217
414
  for (const statement of blockBody) {
218
415
  if (isNode(statement) && statement.type === "ReturnStatement") {
@@ -220,55 +417,81 @@ const rule = {
220
417
  }
221
418
  }
222
419
 
223
- if (!isNode(node.handler) || !isNode(node.handler.body)) return;
224
- const catchBody = Array.isArray(node.handler.body.body)
225
- ? node.handler.body.body.filter(isNode)
420
+ if (!isNode(node["handler"]) || !isNode(node["handler"]["body"])) return;
421
+ const catchBody = Array.isArray(node["handler"]["body"]["body"])
422
+ ? node["handler"]["body"]["body"].filter(isNode)
226
423
  : [];
227
424
 
425
+ for (const statement of catchBody) {
426
+ if (
427
+ statement.type === "ReturnStatement" &&
428
+ isNode(statement["argument"])
429
+ ) {
430
+ wrapReturnValue(statement, isAsync, returnType);
431
+ }
432
+ }
433
+
228
434
  const hasCorrectReturn = catchBody.some(
229
435
  (statement) =>
230
436
  statement.type === "ReturnStatement" &&
231
- isNode(statement.argument) &&
232
- ((statement.argument.type === "Identifier" &&
233
- statement.argument.name === "FAILED_PROMISE") ||
234
- isResultHelperCall(statement.argument, "err") ||
235
- hasIsErrorFlag(statement.argument, true)),
437
+ isNode(statement["argument"]) &&
438
+ ((statement["argument"].type === "Identifier" &&
439
+ statement["argument"]["name"] === "FAILED_PROMISE") ||
440
+ isResultHelperCall(statement["argument"], "err") ||
441
+ hasIsErrorFlag(statement["argument"], true)),
236
442
  );
237
443
 
238
444
  if (!hasCorrectReturn) {
239
445
  context.report({
240
- node: node.handler,
446
+ node: node["handler"],
241
447
  messageId: "returnFailedPromise",
242
448
  fix(fixer) {
243
449
  const lastStatement = catchBody.at(-1);
244
450
  if (
245
451
  lastStatement?.type === "ReturnStatement" &&
246
- isNode(lastStatement.argument) &&
247
- lastStatement.argument.type === "ObjectExpression"
452
+ isNode(lastStatement["argument"]) &&
453
+ lastStatement["argument"].type === "ObjectExpression"
248
454
  ) {
249
- return fixer.replaceText(
250
- lastStatement,
251
- "return { isError: true, value: null }",
252
- );
455
+ return [
456
+ ...ensureResultHelperImportFixes(
457
+ node,
458
+ fixer,
459
+ "err",
460
+ ),
461
+ fixer.replaceText(
462
+ lastStatement,
463
+ "return err()",
464
+ ),
465
+ ];
253
466
  }
254
467
 
255
- const handler = node.handler;
468
+ const handler = node["handler"];
256
469
  if (!isNode(handler)) {
257
470
  return null;
258
471
  }
259
472
 
260
- const bodyRange = handler.body;
473
+ const bodyRange = handler["body"];
261
474
  if (
262
475
  !isNode(bodyRange) ||
263
- !Array.isArray(bodyRange.range)
476
+ !Array.isArray(bodyRange["range"])
264
477
  ) {
265
478
  return null;
266
479
  }
267
480
 
268
- return fixer.insertTextBeforeRange(
269
- [bodyRange.range[1] - 1, bodyRange.range[1] - 1],
270
- "return { isError: true, value: null }; ",
271
- );
481
+ return [
482
+ ...ensureResultHelperImportFixes(
483
+ node,
484
+ fixer,
485
+ "err",
486
+ ),
487
+ fixer.insertTextBeforeRange(
488
+ [
489
+ bodyRange["range"][1] - 1,
490
+ bodyRange["range"][1] - 1,
491
+ ],
492
+ "return err(); ",
493
+ ),
494
+ ];
272
495
  },
273
496
  });
274
497
  }
@@ -296,12 +519,15 @@ const rule = {
296
519
  messages: {
297
520
  replaceWithMaybePromise:
298
521
  "Use 'MaybePromise' instead of 'Promise' as the return type in async functions.",
299
- wrapReturn:
300
- "Wrap return value with { value: value, isError: false }.",
522
+ wrapReturn: "Wrap return value with ok(value).",
523
+ preferOkResult:
524
+ "Use ok(value) instead of an inline success result object.",
525
+ preferErrResult:
526
+ "Use err() instead of an inline error result object.",
301
527
  returnVoidPromise:
302
- "Return a success result object for async functions with Promise<void> return type.",
528
+ "Return ok() for async functions with Promise<void> return type.",
303
529
  returnFailedPromise:
304
- "Return an error result object in the catch block of async functions.",
530
+ "Return err() in the catch block of async functions.",
305
531
  },
306
532
  },
307
533
  };
package/src/index.ts CHANGED
@@ -1,3 +1,12 @@
1
+ // Side-effect type import: pulls the `declare global` block into any
2
+ // program that imports this package, so the global helpers need no
3
+ // tsconfig entry of their own. The empty brace form is the only way to say
4
+ // "load this module for its ambient declarations" without importing a value,
5
+ // and `globals.ts` sits at the package root because it is a published entry
6
+ // point (`@murky-web/typebuddy/globals`).
7
+ // oxlint-disable-next-line no-empty-named-blocks, no-relative-parent-imports, require-module-specifiers
8
+ import type {} from "../globals.js";
9
+
1
10
  export * from "./type_helper.js";
2
11
 
3
12
  export type {