@murky-web/typebuddy 2.1.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 +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 +3 -2
  21. package/oxlint/index.ts +7 -5
  22. package/package.json +92 -91
  23. package/rules/async_rule.ts +80 -64
  24. package/rules/deliberate_throw.ts +11 -11
  25. package/rules/maybe_promise_rule.ts +218 -91
  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 +2 -1
  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 +5 -4
  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,59 +1,87 @@
1
- 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;
16
- if (types.length !== 3) return;
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
+ };
17
7
 
8
+ const rule = {
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
+ }) {
18
21
  const sourceCode = context.getSourceCode();
19
- const nullType = types.find((typeNode) => typeNode.type === "TSNullKeyword");
20
- const undefinedType = types.find(
21
- (typeNode) => typeNode.type === "TSUndefinedKeyword",
22
- );
23
- const otherType = types.find(
24
- (typeNode) =>
25
- typeNode.type !== "TSNullKeyword" &&
26
- typeNode.type !== "TSUndefinedKeyword",
27
- );
22
+ const imports = createImportPlanner(sourceCode);
23
+
24
+ return {
25
+ TSUnionType(node: { types: Array<{ type: string }> }) {
26
+ const types = node.types;
27
+ if (types.length !== 3) return;
28
+
29
+ const nullType = types.find(
30
+ (typeNode) => typeNode.type === "TSNullKeyword",
31
+ );
32
+ const undefinedType = types.find(
33
+ (typeNode) => typeNode.type === "TSUndefinedKeyword",
34
+ );
35
+ const otherType = types.find(
36
+ (typeNode) =>
37
+ typeNode.type !== "TSNullKeyword" &&
38
+ typeNode.type !== "TSUndefinedKeyword",
39
+ );
40
+
41
+ if (nullType && undefinedType && otherType) {
42
+ const typeText = sourceCode.getText(otherType);
43
+ context.report({
44
+ node,
45
+ messageId: "useNullable",
46
+ data: { type: typeText },
47
+ fix(fixer) {
48
+ // See `prefer-maybe`: the fix only uses the
49
+ // package's own `Nullable`, imported where it is
50
+ // not already.
51
+ const importFixes = imports.fixes(
52
+ node,
53
+ fixer,
54
+ "Nullable",
55
+ "type",
56
+ );
57
+ if (importFixes === null) return null;
28
58
 
29
- if (nullType && undefinedType && otherType) {
30
- const typeText = sourceCode.getText(otherType);
31
- context.report({
32
- node,
33
- messageId: "useNullable",
34
- data: { type: typeText },
35
- fix(fixer) {
36
- return fixer.replaceText(node, `Nullable<${typeText}>`);
59
+ return [
60
+ ...importFixes,
61
+ fixer.replaceText(
62
+ node,
63
+ `Nullable<${typeText}>`,
64
+ ),
65
+ ];
66
+ },
67
+ });
68
+ }
37
69
  },
38
- });
39
- }
40
- },
41
- };
42
- },
43
- defaultOptions: [],
44
- meta: {
45
- type: "suggestion",
46
- hasSuggestions: true,
47
- docs: {
48
- description: "Use Nullable<T> instead of T | null | undefined",
70
+ };
49
71
  },
50
- fixable: "code",
51
- schema: [],
52
- messages: {
53
- useNullable:
54
- "Use Nullable<{{type}}> instead of {{type}} | null | undefined",
72
+ defaultOptions: [],
73
+ meta: {
74
+ type: "suggestion",
75
+ docs: {
76
+ description: "Use Nullable<T> instead of T | null | undefined",
77
+ },
78
+ fixable: "code",
79
+ schema: [],
80
+ messages: {
81
+ useNullable:
82
+ "Use Nullable<{{type}}> instead of {{type}} | null | undefined",
83
+ },
55
84
  },
56
- },
57
85
  };
58
86
 
59
87
  export { rule as nullableRule };
@@ -1,58 +1,87 @@
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
- if (node.types.length !== 2) return;
16
-
17
- const undefinedType = node.types.find(
18
- (typeNode) => typeNode.type === "TSUndefinedKeyword",
19
- );
20
- // `null | undefined` has no non-nullish member to name, and rewriting
21
- // it to `Optional<null>` only restated it with more syntax.
22
- const otherType = node.types.find(
23
- (typeNode) =>
24
- typeNode.type !== "TSUndefinedKeyword" &&
25
- typeNode.type !== "TSNullKeyword",
26
- );
27
-
28
- if (undefinedType && otherType) {
29
- const sourceCode = context.getSourceCode();
30
- const typeText = sourceCode.getText(otherType);
31
-
32
- context.report({
33
- node,
34
- messageId: "preferOptional",
35
- data: { type: typeText },
36
- fix(fixer) {
37
- return fixer.replaceText(node, `Optional<${typeText}>`);
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
+ }) {
21
+ const sourceCode = context.getSourceCode();
22
+ const imports = createImportPlanner(sourceCode);
23
+
24
+ return {
25
+ TSUnionType(node: { types: Array<{ type: string }> }) {
26
+ if (node.types.length !== 2) return;
27
+
28
+ const undefinedType = node.types.find(
29
+ (typeNode) => typeNode.type === "TSUndefinedKeyword",
30
+ );
31
+ // `null | undefined` has no non-nullish member to name, and
32
+ // rewriting it to `Optional<null>` only restated it with more
33
+ // syntax.
34
+ const otherType = node.types.find(
35
+ (typeNode) =>
36
+ typeNode.type !== "TSUndefinedKeyword" &&
37
+ typeNode.type !== "TSNullKeyword",
38
+ );
39
+
40
+ if (undefinedType && otherType) {
41
+ const typeText = sourceCode.getText(otherType);
42
+
43
+ context.report({
44
+ node,
45
+ messageId: "preferOptional",
46
+ data: { type: typeText },
47
+ fix(fixer) {
48
+ // See `prefer-maybe`: the fix only uses the
49
+ // package's own `Optional`, imported where it is
50
+ // not already.
51
+ const importFixes = imports.fixes(
52
+ node,
53
+ fixer,
54
+ "Optional",
55
+ "type",
56
+ );
57
+ if (importFixes === null) return null;
58
+
59
+ return [
60
+ ...importFixes,
61
+ fixer.replaceText(
62
+ node,
63
+ `Optional<${typeText}>`,
64
+ ),
65
+ ];
66
+ },
67
+ });
68
+ }
38
69
  },
39
- });
40
- }
41
- },
42
- };
43
- },
44
- defaultOptions: [],
45
- meta: {
46
- type: "suggestion",
47
- docs: {
48
- description: "Enforce using Optional<T> instead of T | undefined",
70
+ };
49
71
  },
50
- fixable: "code",
51
- schema: [],
52
- messages: {
53
- preferOptional: "Use Optional<{{type}}> instead of {{type}} | undefined",
72
+ defaultOptions: [],
73
+ meta: {
74
+ type: "suggestion",
75
+ docs: {
76
+ description: "Enforce using Optional<T> instead of T | undefined",
77
+ },
78
+ fixable: "code",
79
+ schema: [],
80
+ messages: {
81
+ preferOptional:
82
+ "Use Optional<{{type}}> instead of {{type}} | undefined",
83
+ },
54
84
  },
55
- },
56
85
  };
57
86
 
58
87
  export { rule as optionalRule };
@@ -1,16 +1,16 @@
1
1
  type AstNode = {
2
- type: string;
3
- [key: string]: unknown;
2
+ type: string;
3
+ [key: string]: unknown;
4
4
  };
5
5
 
6
6
  const FUNCTION_TYPES = new Set([
7
- "ArrowFunctionExpression",
8
- "FunctionDeclaration",
9
- "FunctionExpression",
7
+ "ArrowFunctionExpression",
8
+ "FunctionDeclaration",
9
+ "FunctionExpression",
10
10
  ]);
11
11
 
12
12
  function isNode(value: unknown): value is AstNode {
13
- return typeof value === "object" && value !== null && "type" in value;
13
+ return typeof value === "object" && value !== null && "type" in value;
14
14
  }
15
15
 
16
16
  /**
@@ -31,40 +31,40 @@ function isNode(value: unknown): value is AstNode {
31
31
  * @returns {void}
32
32
  */
33
33
  function walkOwnSubtree(
34
- root: unknown,
35
- visit: (node: AstNode) => boolean | void,
34
+ root: unknown,
35
+ visit: (node: AstNode) => boolean | void,
36
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;
37
+ if (!isNode(root)) {
38
+ return;
48
39
  }
49
40
 
50
- if (visit(current) === false) {
51
- continue;
52
- }
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
53
 
54
- for (const [key, value] of Object.entries(current)) {
55
- if (key === "parent") {
56
- continue;
57
- }
54
+ for (const [key, value] of Object.entries(current)) {
55
+ if (key === "parent") {
56
+ continue;
57
+ }
58
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;
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
+ }
63
66
  }
64
- pending.push(candidate);
65
- }
66
67
  }
67
- }
68
68
  }
69
69
 
70
70
  export { walkOwnSubtree };
@@ -0,0 +1,114 @@
1
+ // Directory names whose contents are test code, matched as whole path
2
+ // segments: `src/__tests__/x.ts` and `tests/helper.ts` count, `src/latest/x.ts`
3
+ // and `src/testing/x.ts` do not.
4
+ const TEST_DIRECTORIES = new Set(["__mocks__", "__tests__", "test", "tests"]);
5
+
6
+ // `x.test.ts`, `x.spec.tsx`, `x.bench.ts`: the marker has to be its own dot
7
+ // segment, so `latest.ts` and `contest.ts` stay source files.
8
+ const TEST_FILE_NAME = /\.(?:bench|spec|test)\.[^.]+/;
9
+
10
+ // Test setup files by name: `vitest.setup.*`, `vitest-setup.*` and the
11
+ // Jest-style `setupTests.*`.
12
+ const SETUP_FILE_NAME = /^(?:setupTests|vitest-setup|vitest\.setup)\.[^.]+$/;
13
+
14
+ const ABSOLUTE_PATH = /^(?:\/|[A-Za-z]:\/)/;
15
+
16
+ function toSlashes(path: string): string {
17
+ return path.replaceAll("\\", "/");
18
+ }
19
+
20
+ /**
21
+ * The directory segments of `filename` that count for the directory match: the
22
+ * ones below the project's working directory `cwd`. A relative filename is
23
+ * relative to the project already. An absolute one needs `cwd` to tell the
24
+ * project's own directories from the ones above it (`/tmp/test/app/src/x.ts` is
25
+ * not under a test directory); without `cwd`, or outside it, no directory
26
+ * counts, so the mistake is a test helper that gets linted, never a whole
27
+ * project that goes silent.
28
+ */
29
+ function projectDirectories(path: string, cwd: string | undefined): string[] {
30
+ const segments = path.split("/");
31
+ segments.pop();
32
+
33
+ if (!ABSOLUTE_PATH.test(path)) {
34
+ return segments;
35
+ }
36
+ if (cwd === undefined) {
37
+ return [];
38
+ }
39
+
40
+ const root = toSlashes(cwd).replace(/\/+$/, "");
41
+ if (root === "" || !path.startsWith(`${root}/`)) {
42
+ return [];
43
+ }
44
+
45
+ return path
46
+ .slice(root.length + 1)
47
+ .split("/")
48
+ .slice(0, -1);
49
+ }
50
+
51
+ /**
52
+ * Whether `filename` is test code: test, spec and bench files, files under a
53
+ * `__tests__`, `tests`, `test` or `__mocks__` directory of the project rooted
54
+ * at `cwd`, and test setup files. Both `/` and `\` separate path segments.
55
+ */
56
+ function isTestFile(filename: string, cwd?: string): boolean {
57
+ const path = toSlashes(filename);
58
+ const baseName = path.slice(path.lastIndexOf("/") + 1);
59
+
60
+ return (
61
+ TEST_FILE_NAME.test(baseName) ||
62
+ SETUP_FILE_NAME.test(baseName) ||
63
+ projectDirectories(path, cwd).some((segment) =>
64
+ TEST_DIRECTORIES.has(segment),
65
+ )
66
+ );
67
+ }
68
+
69
+ // The rules type their context by what they use (`getSourceCode`, `report`),
70
+ // which leaves out what oxlint's JS plugin API puts on every context: the
71
+ // absolute `filename` and the `cwd` oxlint runs in.
72
+ function getFilename(context: object): string {
73
+ if ("filename" in context && typeof context.filename === "string") {
74
+ return context.filename;
75
+ }
76
+
77
+ return "";
78
+ }
79
+
80
+ function getCwd(context: object): string | undefined {
81
+ if ("cwd" in context && typeof context.cwd === "string") {
82
+ return context.cwd;
83
+ }
84
+
85
+ return undefined;
86
+ }
87
+
88
+ /**
89
+ * Make a rule a no-op for test files: its `create` returns no visitors, so test
90
+ * helpers, fixtures and mocks are not asked to follow the typebuddy conventions
91
+ * (`MaybePromise` results, `Maybe`/`Nullable`/`Optional` types).
92
+ */
93
+ function withoutTestFiles<
94
+ Context extends object,
95
+ Visitors extends object,
96
+ Rest,
97
+ >(
98
+ rule: Rest & { create(context: Context): Visitors },
99
+ ): Omit<Rest, "create"> & {
100
+ create(context: Context): Visitors | Record<string, never>;
101
+ } {
102
+ return {
103
+ ...rule,
104
+ create(context: Context): Visitors | Record<string, never> {
105
+ if (isTestFile(getFilename(context), getCwd(context))) {
106
+ return {};
107
+ }
108
+
109
+ return rule.create(context);
110
+ },
111
+ };
112
+ }
113
+
114
+ export { isTestFile, withoutTestFiles };