@intellectual-frontiers/lint 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/plugin.d.ts +31 -0
- package/dist/plugin.js +19 -0
- package/dist/rule.d.ts +207 -0
- package/dist/rule.js +125 -0
- package/dist/rules/import-boundary.d.ts +7 -0
- package/dist/rules/import-boundary.js +64 -0
- package/dist/rules/module-doc.d.ts +3 -0
- package/dist/rules/module-doc.js +39 -0
- package/dist/rules/no-registry-import.d.ts +5 -0
- package/dist/rules/no-registry-import.js +46 -0
- package/dist/rules/no-vendor-api.d.ts +5 -0
- package/dist/rules/no-vendor-api.js +46 -0
- package/dist/rules/switch-absurd.d.ts +5 -0
- package/dist/rules/switch-absurd.js +72 -0
- package/dist/rules/terminal-writers.d.ts +10 -0
- package/dist/rules/terminal-writers.js +53 -0
- package/dist/test-rule.d.ts +32 -0
- package/dist/test-rule.js +100 -0
- package/package.json +50 -4
- package/src/plugin.ts +49 -0
- package/src/rule.ts +281 -0
- package/src/rules/import-boundary.ts +64 -0
- package/src/rules/module-doc.ts +43 -0
- package/src/rules/no-registry-import.ts +48 -0
- package/src/rules/no-vendor-api.ts +50 -0
- package/src/rules/switch-absurd.ts +71 -0
- package/src/rules/terminal-writers.ts +57 -0
- package/src/test-rule.ts +130 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `import-boundary` (commons lint 0001-lint FR-005): a relative import that leaves its package is refused; another package is
|
|
3
|
+
* imported by its name. The packages are the option `roots`, folders relative to the linter's working folder, each a glob of whole
|
|
4
|
+
* segments (`kernel`, `packages/*`, `lib/ts/*`); a file's package is the longest root it is in, and a file in none is not checked.
|
|
5
|
+
*
|
|
6
|
+
* Options: `roots` (the package and member folders) and `allow` (`[{ files, reason }]`).
|
|
7
|
+
*
|
|
8
|
+
* Spec: 0001-lint FR-005
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { posix } from "node:path";
|
|
13
|
+
import { array, string } from "@intellectual-frontiers/core";
|
|
14
|
+
import { globToRegExp } from "@intellectual-frontiers/formats/glob";
|
|
15
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, type Node, type Rule, stringOf } from "../rule.ts";
|
|
16
|
+
|
|
17
|
+
/** The folder of `file` that is its package: the longest of `roots` whose segments match its leading folders; undefined where none does. */
|
|
18
|
+
export function packageOf(file: string, roots: readonly string[]): string | undefined {
|
|
19
|
+
const folders = file.split("/").slice(0, -1);
|
|
20
|
+
let best: string | undefined;
|
|
21
|
+
for (const root of roots) {
|
|
22
|
+
const n = root.split("/").filter((s) => s !== "" && s !== ".").length;
|
|
23
|
+
if (n === 0 || n > folders.length) continue;
|
|
24
|
+
const head = folders.slice(0, n).join("/");
|
|
25
|
+
const re = globToRegExp(root);
|
|
26
|
+
if (re.kind === "ok" && re.value.test(head) && (best === undefined || head.length > best.length)) best = head;
|
|
27
|
+
}
|
|
28
|
+
return best;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Where a relative specifier lands from `file`, as a `/` path relative to the same folder as `file` (`../` where it leaves it). */
|
|
32
|
+
export function landing(file: string, specifier: string): string {
|
|
33
|
+
return posix.normalize(posix.join(posix.dirname(file), specifier));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The rule. */
|
|
37
|
+
export const importBoundary: Rule = defineRule(
|
|
38
|
+
{
|
|
39
|
+
description: "a relative import stays in its package: import another package by its name",
|
|
40
|
+
options: { roots: array(string), allow: allowList },
|
|
41
|
+
},
|
|
42
|
+
(context, options) => {
|
|
43
|
+
const file = fileOf(context);
|
|
44
|
+
const own = packageOf(file, options.roots ?? []);
|
|
45
|
+
if (own === undefined || allowedFor(options.allow, file) !== undefined) return {};
|
|
46
|
+
const check = (node: Node, source: Node | null | undefined): void => {
|
|
47
|
+
const specifier = stringOf(source);
|
|
48
|
+
if (specifier === undefined || !(specifier.startsWith("./") || specifier.startsWith("../"))) return;
|
|
49
|
+
const target = landing(file, specifier);
|
|
50
|
+
if (target.startsWith(`${own}/`)) return;
|
|
51
|
+
context.report({ node, message: `"${specifier}" leaves the package ${own}/: import the other package by its name` });
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
ImportDeclaration: (node) => check(node, node.source),
|
|
55
|
+
ExportAllDeclaration: (node) => check(node, node.source),
|
|
56
|
+
ExportNamedDeclaration: (node) => check(node, node.source),
|
|
57
|
+
ImportExpression: (node) => check(node, node.source),
|
|
58
|
+
TSImportType: (node) => check(node, node.source ?? node.argument),
|
|
59
|
+
CallExpression: (node) => {
|
|
60
|
+
if (isIdentifier(node.callee, "require")) check(node, node.arguments[0]);
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `module-doc` (commons lint 0001-lint FR-006): a file begins with its module's documentation, a JSDoc block (`/** ... *\/`)
|
|
3
|
+
* that says `@module`, before any code and before any other comment (a shebang may come first).
|
|
4
|
+
*
|
|
5
|
+
* Options: `tag` (`@module` by default) and `allow` (`[{ files, reason }]`).
|
|
6
|
+
*
|
|
7
|
+
* Spec: 0001-lint FR-006
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
import { string } from "@intellectual-frontiers/core";
|
|
12
|
+
import { allowedFor, allowList, defineRule, fileOf, type Rule } from "../rule.ts";
|
|
13
|
+
|
|
14
|
+
/** The rule. */
|
|
15
|
+
export const moduleDoc: Rule = defineRule(
|
|
16
|
+
{
|
|
17
|
+
description: "a file begins with a JSDoc block that says @module",
|
|
18
|
+
type: "suggestion",
|
|
19
|
+
options: { tag: string, allow: allowList },
|
|
20
|
+
},
|
|
21
|
+
(context, options) => {
|
|
22
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined) return {};
|
|
23
|
+
const tag = options.tag ?? "@module";
|
|
24
|
+
return {
|
|
25
|
+
Program: (node) => {
|
|
26
|
+
const first = context.sourceCode.getAllComments().find((c) => c.type !== "Shebang");
|
|
27
|
+
const code = node.body[0]?.range?.[0] ?? Number.POSITIVE_INFINITY;
|
|
28
|
+
const documented =
|
|
29
|
+
first !== undefined &&
|
|
30
|
+
first.type === "Block" &&
|
|
31
|
+
first.value.startsWith("*") &&
|
|
32
|
+
first.value.includes(tag) &&
|
|
33
|
+
first.range[1] <= code;
|
|
34
|
+
if (!documented) {
|
|
35
|
+
context.report({
|
|
36
|
+
loc: { line: 1, column: 0 },
|
|
37
|
+
message: `begin the file with its module's documentation: a /** ... */ block that says ${tag}, before any code or other comment`,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
},
|
|
43
|
+
);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `no-registry-import` (commons lint 0001-lint FR-004): no module specifier that names a registry or a URL (`npm:`, `jsr:`,
|
|
3
|
+
* `http:`, `https:` by default), in an import, an export, a dynamic `import()`, a type's `import()`, `import x = require()` or
|
|
4
|
+
* `require()`; a package is installed and imported by its bare name.
|
|
5
|
+
*
|
|
6
|
+
* Options: `prefixes` (the refused beginnings of a specifier) and `allow` (`[{ files, reason }]`).
|
|
7
|
+
*
|
|
8
|
+
* Spec: 0001-lint FR-004
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { array, string } from "@intellectual-frontiers/core";
|
|
13
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, type Node, type Rule, stringOf } from "../rule.ts";
|
|
14
|
+
|
|
15
|
+
/** The beginnings of a specifier the rule refuses where none are given. */
|
|
16
|
+
export const REGISTRY_PREFIXES: readonly string[] = ["npm", "jsr", "http", "https"].map((scheme) => `${scheme}:`);
|
|
17
|
+
|
|
18
|
+
/** The rule. */
|
|
19
|
+
export const noRegistryImport: Rule = defineRule(
|
|
20
|
+
{
|
|
21
|
+
description: "no npm:, jsr: or URL module specifier: install the package and import it by its bare name",
|
|
22
|
+
options: { prefixes: array(string), allow: allowList },
|
|
23
|
+
},
|
|
24
|
+
(context, options) => {
|
|
25
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined) return {};
|
|
26
|
+
const prefixes = options.prefixes ?? REGISTRY_PREFIXES;
|
|
27
|
+
const check = (node: Node, source: Node | null | undefined): void => {
|
|
28
|
+
const specifier = stringOf(source);
|
|
29
|
+
const prefix = specifier === undefined ? undefined : prefixes.find((p) => specifier.toLowerCase().startsWith(p));
|
|
30
|
+
if (specifier === undefined || prefix === undefined) return;
|
|
31
|
+
context.report({
|
|
32
|
+
node,
|
|
33
|
+
message: `"${specifier}" names a registry or a URL (${prefix}): install the package and import it by its bare name`,
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
ImportDeclaration: (node) => check(node, node.source),
|
|
38
|
+
ExportAllDeclaration: (node) => check(node, node.source),
|
|
39
|
+
ExportNamedDeclaration: (node) => check(node, node.source),
|
|
40
|
+
ImportExpression: (node) => check(node, node.source),
|
|
41
|
+
TSImportType: (node) => check(node, node.source ?? node.argument),
|
|
42
|
+
TSExternalModuleReference: (node) => check(node, node.expression),
|
|
43
|
+
CallExpression: (node) => {
|
|
44
|
+
if (isIdentifier(node.callee, "require")) check(node, node.arguments[0]);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `no-vendor-api` (commons lint 0001-lint FR-003): no member of a vendor's global (`Deno.*`, `Bun.*` by default), in code or in
|
|
3
|
+
* a type, outside the files of the option `allow`, each with its reason; a harness keeps its own list.
|
|
4
|
+
*
|
|
5
|
+
* Options: `globals` (the vendor globals, `["Deno", "Bun"]` by default) and `allow` (`[{ files, reason }]`, globs relative to the
|
|
6
|
+
* linter's working folder).
|
|
7
|
+
*
|
|
8
|
+
* Spec: 0001-lint FR-003
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { array, string } from "@intellectual-frontiers/core";
|
|
13
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, isMember, nameOf, type Node, propertyOf, type Rule } from "../rule.ts";
|
|
14
|
+
|
|
15
|
+
/** The vendor globals the rule refuses where none are given. */
|
|
16
|
+
export const VENDOR_GLOBALS: readonly string[] = ["Deno", "Bun"];
|
|
17
|
+
|
|
18
|
+
/** The rule. */
|
|
19
|
+
export const noVendorApi: Rule = defineRule(
|
|
20
|
+
{
|
|
21
|
+
description: "no member of a vendor's global (Deno, Bun) outside the files listed with their reasons",
|
|
22
|
+
options: { globals: array(string), allow: allowList },
|
|
23
|
+
},
|
|
24
|
+
(context, options) => {
|
|
25
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined) return {};
|
|
26
|
+
const globals = options.globals ?? VENDOR_GLOBALS;
|
|
27
|
+
const refuse = (node: Node, what: string, vendor: string): void =>
|
|
28
|
+
context.report({
|
|
29
|
+
node,
|
|
30
|
+
message: `${what} is ${vendor}'s own API: use a node: builtin or the runtime, or list this file with its reason in allow`,
|
|
31
|
+
});
|
|
32
|
+
return {
|
|
33
|
+
MemberExpression: (node) => {
|
|
34
|
+
const name = nameOf(node);
|
|
35
|
+
if (name !== undefined && globals.includes(name[0])) {
|
|
36
|
+
refuse(node, `${name[0]}.${name[1]}`, name[0]);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
// `globalThis.Deno` itself, not as the object of a member (which the outer expression reports).
|
|
40
|
+
const vendor = isIdentifier(node.object, "globalThis") ? propertyOf(node) : undefined;
|
|
41
|
+
const outer = node.parent !== undefined && isMember(node.parent) && node.parent.object === node;
|
|
42
|
+
if (vendor !== undefined && globals.includes(vendor) && !outer) refuse(node, `globalThis.${vendor}`, vendor);
|
|
43
|
+
},
|
|
44
|
+
TSQualifiedName: (node) => {
|
|
45
|
+
if (isIdentifier(node.left) && globals.includes(node.left.name) && isIdentifier(node.right))
|
|
46
|
+
refuse(node, `${node.left.name}.${node.right.name}`, node.left.name);
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
},
|
|
50
|
+
);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `switch-absurd` (commons lint 0001-lint FR-007): a `switch` over a union, on its discriminant (`x.kind` by default), ends in
|
|
3
|
+
* a `default` that calls `absurd` (`default: return absurd(x)`), so that an alternative added to the union and left out does not
|
|
4
|
+
* compile. A JavaScript rule has no types, so a switch over a union is a switch on a member named as one of the option `discriminants`;
|
|
5
|
+
* with `every`, every switch is held to it.
|
|
6
|
+
*
|
|
7
|
+
* Options: `discriminants` (`["kind"]` by default), `functions` (the names of the exhaustive end, `["absurd"]` by default), `every` and
|
|
8
|
+
* `allow` (`[{ files, reason }]`).
|
|
9
|
+
*
|
|
10
|
+
* Spec: 0001-lint FR-007
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { array, boolean, string } from "@intellectual-frontiers/core";
|
|
15
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, isMember, isNode, type Node, propertyOf, type Rule } from "../rule.ts";
|
|
16
|
+
|
|
17
|
+
/** Whether a statement of a `default` calls one of the functions: `f(x);`, `return f(x);`, `throw f(x);`, or in a block. */
|
|
18
|
+
export function callsOneOf(node: Node | null | undefined, functions: readonly string[]): boolean {
|
|
19
|
+
if (node === null || node === undefined) return false;
|
|
20
|
+
const child = (key: string): unknown => (key in node ? Reflect.get(node, key) : undefined);
|
|
21
|
+
switch (node.type) {
|
|
22
|
+
case "ReturnStatement":
|
|
23
|
+
case "ThrowStatement": {
|
|
24
|
+
const argument = child("argument");
|
|
25
|
+
return isNode(argument) && callsOneOf(argument, functions);
|
|
26
|
+
}
|
|
27
|
+
case "ExpressionStatement": {
|
|
28
|
+
const expression = child("expression");
|
|
29
|
+
return isNode(expression) && callsOneOf(expression, functions);
|
|
30
|
+
}
|
|
31
|
+
case "BlockStatement": {
|
|
32
|
+
const body = child("body");
|
|
33
|
+
return Array.isArray(body) && body.some((s: unknown) => isNode(s) && callsOneOf(s, functions));
|
|
34
|
+
}
|
|
35
|
+
case "CallExpression": {
|
|
36
|
+
const callee = child("callee");
|
|
37
|
+
if (!isNode(callee)) return false;
|
|
38
|
+
if (isIdentifier(callee)) return functions.includes(callee.name);
|
|
39
|
+
const name = isMember(callee) ? propertyOf(callee) : undefined;
|
|
40
|
+
return name !== undefined && functions.includes(name);
|
|
41
|
+
}
|
|
42
|
+
default:
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The rule. */
|
|
48
|
+
export const switchAbsurd: Rule = defineRule(
|
|
49
|
+
{
|
|
50
|
+
description: "a switch over a union ends in a default that calls absurd",
|
|
51
|
+
options: { discriminants: array(string), functions: array(string), every: boolean, allow: allowList },
|
|
52
|
+
},
|
|
53
|
+
(context, options) => {
|
|
54
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined) return {};
|
|
55
|
+
const discriminants = options.discriminants ?? ["kind"];
|
|
56
|
+
const functions = options.functions ?? ["absurd"];
|
|
57
|
+
return {
|
|
58
|
+
SwitchStatement: (node) => {
|
|
59
|
+
const d = node.discriminant;
|
|
60
|
+
const property = isMember(d) ? propertyOf(d) : undefined;
|
|
61
|
+
if (options.every !== true && (property === undefined || !discriminants.includes(property))) return;
|
|
62
|
+
const last = node.cases.at(-1);
|
|
63
|
+
if (last !== undefined && last.test === null && last.consequent.some((s) => callsOneOf(s, functions))) return;
|
|
64
|
+
context.report({
|
|
65
|
+
node,
|
|
66
|
+
message: `end this switch in \`default: return ${functions[0] ?? "absurd"}(value)\`, so that an alternative left out does not compile`,
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `terminal-writers` (commons lint 0001-lint FR-008): nothing writes to the terminal (`process.stdout`, `process.stderr`,
|
|
3
|
+
* `console.*`, and the vendors' own streams) outside the files of the option `allow`, each with its reason; everything else emits a
|
|
4
|
+
* signal, or writes through the one module a harness lists. A named import of `stdout` or `stderr` from `node:process` is refused too.
|
|
5
|
+
*
|
|
6
|
+
* Options: `writers` (`[{ object, property }]`, `property` `*` for any member; the list above by default) and `allow` (`[{ files,
|
|
7
|
+
* reason }]`).
|
|
8
|
+
*
|
|
9
|
+
* Spec: 0001-lint FR-008
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { array, object, string } from "@intellectual-frontiers/core";
|
|
14
|
+
import { allowedFor, allowList, defineRule, fileOf, isIdentifier, isNode, nameOf, type Rule, stringOf } from "../rule.ts";
|
|
15
|
+
|
|
16
|
+
/** A writer: a global's member (`process.stdout`), or any of its members (`console.*`). */
|
|
17
|
+
export type Writer = { readonly object: string; readonly property: string };
|
|
18
|
+
|
|
19
|
+
/** The writers the rule refuses where none are given. */
|
|
20
|
+
export const TERMINAL_WRITERS: readonly Writer[] = [
|
|
21
|
+
{ object: "process", property: "stdout" },
|
|
22
|
+
{ object: "process", property: "stderr" },
|
|
23
|
+
{ object: "console", property: "*" },
|
|
24
|
+
{ object: "Bun", property: "stdout" },
|
|
25
|
+
{ object: "Bun", property: "stderr" },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** The rule. */
|
|
29
|
+
export const terminalWriters: Rule = defineRule(
|
|
30
|
+
{
|
|
31
|
+
description: "no write to the terminal outside the files listed with their reasons",
|
|
32
|
+
options: { writers: array(object({ object: string, property: string })), allow: allowList },
|
|
33
|
+
},
|
|
34
|
+
(context, options) => {
|
|
35
|
+
if (allowedFor(options.allow, fileOf(context)) !== undefined) return {};
|
|
36
|
+
const writers = options.writers ?? TERMINAL_WRITERS;
|
|
37
|
+
const writes = (o: string, p: string): boolean => writers.some((w) => w.object === o && (w.property === "*" || w.property === p));
|
|
38
|
+
const message = (what: string): string =>
|
|
39
|
+
`${what} writes to the terminal: emit a signal or write through the module listed for it, or list this file with its reason in allow`;
|
|
40
|
+
return {
|
|
41
|
+
MemberExpression: (node) => {
|
|
42
|
+
const name = nameOf(node);
|
|
43
|
+
if (name !== undefined && writes(name[0], name[1])) context.report({ node, message: message(`${name[0]}.${name[1]}`) });
|
|
44
|
+
},
|
|
45
|
+
ImportDeclaration: (node) => {
|
|
46
|
+
const source = stringOf(node.source);
|
|
47
|
+
if (source !== "node:process" && source !== "process") return;
|
|
48
|
+
for (const s of node.specifiers) {
|
|
49
|
+
if (s.type !== "ImportSpecifier" || !("imported" in s)) continue;
|
|
50
|
+
const imported: unknown = s.imported;
|
|
51
|
+
const text = isNode(imported) ? (isIdentifier(imported) ? imported.name : stringOf(imported)) : undefined;
|
|
52
|
+
if (text !== undefined && writes("process", text)) context.report({ node: s, message: message(`process.${text}`) });
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
);
|
package/src/test-rule.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A rule of a lint plugin run against code, in a test (commons lint 0001-lint FR-009): the files are written to a new folder
|
|
3
|
+
* and the real linter, `bun lint` of the pinned Bun, is run over them with the plugin loaded by `--plugin` and only the rule turned on
|
|
4
|
+
* by `--rule`, so that a test proves the rule and the way `bun lint` loads it. Its problems come back from its JSON report, decoded.
|
|
5
|
+
*
|
|
6
|
+
* The linter is the Bun named by `IFC_LINT_BUN` (a path to a Bun whose `lint` runs plugins), else the pinned canary through `bun x
|
|
7
|
+
* --no-install bun@<LINT_BUN_VERSION>`, which is never fetched here: where it is not installed, `linter()` says so and the tests that
|
|
8
|
+
* need it are skipped with that reason (`bun x bun@<LINT_BUN_VERSION> --version` installs it).
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { lintFiles } from "./test-rule.ts";
|
|
13
|
+
* const problems = await lintFiles({ rule: "no-registry-import", files: { "a.ts": 'import x from "npm:x";\nexport { x };\n' } });
|
|
14
|
+
* // { kind: "ok", value: [{ file: "a.ts", rule: "no-registry-import", line: 1, column: 1, message: "..." }] }
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Spec: 0001-lint FR-009
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync } from "node:fs";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { array, integer, json, nullable, object, string, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
24
|
+
import { makeTempDir, mkdir, readTextFile, realPath, remove, writeTextFile } from "@intellectual-frontiers/system/fs";
|
|
25
|
+
import { dirname, join, relative } from "@intellectual-frontiers/system/path";
|
|
26
|
+
import { env, run } from "@intellectual-frontiers/system/proc";
|
|
27
|
+
|
|
28
|
+
/** The Bun whose `lint` runs ESLint plugins, until a release has it (FR-028). */
|
|
29
|
+
export const LINT_BUN_VERSION = "1.4.4-canary.20261115.1";
|
|
30
|
+
|
|
31
|
+
/** The plugin of this folder. */
|
|
32
|
+
export const PLUGIN_PATH: string = fileURLToPath(
|
|
33
|
+
new URL(existsSync(new URL("./plugin.ts", import.meta.url)) ? "./plugin.ts" : "./plugin.js", import.meta.url),
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
/** A problem the linter reported: the file (as given), the rule without its prefix, the line and column from 1, and the message. */
|
|
37
|
+
export type Problem = {
|
|
38
|
+
readonly file: string;
|
|
39
|
+
readonly rule: string;
|
|
40
|
+
readonly line: number;
|
|
41
|
+
readonly column: number;
|
|
42
|
+
readonly message: string;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A rule to run: its name, its options object, the files (relative paths and their text), and the plugin (this folder's by default). */
|
|
46
|
+
export type LintRun = {
|
|
47
|
+
readonly rule: string;
|
|
48
|
+
readonly options?: unknown;
|
|
49
|
+
readonly files: Readonly<Record<string, string>>;
|
|
50
|
+
readonly plugin?: string;
|
|
51
|
+
/** The plugin's name, the prefix of its rules (`ifc` by default). */
|
|
52
|
+
readonly prefix?: string;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** The command that runs `bun lint`, without `lint`: `IFC_LINT_BUN`, or the pinned canary through `bun x --no-install`. */
|
|
56
|
+
export function lintCommand(): readonly string[] {
|
|
57
|
+
const given = env.get("IFC_LINT_BUN")?.trim();
|
|
58
|
+
return given !== undefined && given !== "" ? [given] : ["bun", "x", "--no-install", `bun@${LINT_BUN_VERSION}`];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The linter's command where it runs and can load a plugin, or why not. */
|
|
62
|
+
export async function linter(): Promise<Result<readonly string[], string>> {
|
|
63
|
+
const command = lintCommand();
|
|
64
|
+
try {
|
|
65
|
+
const r = await run([...command, "lint", "--help", "--all"]);
|
|
66
|
+
if (r.success && r.stdout.includes("--plugin")) return ok(command);
|
|
67
|
+
return err(`${command.join(" ")} lint does not load plugins here (exit ${r.code}); run bun x bun@${LINT_BUN_VERSION} --version once`);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
return err(`${command.join(" ")} does not run here: ${e instanceof Error ? e.message : String(e)}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const report = array(
|
|
74
|
+
object(
|
|
75
|
+
{ filePath: string },
|
|
76
|
+
{ messages: array(object({ message: string }, { ruleId: nullable(string), line: integer, column: integer })) },
|
|
77
|
+
),
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The problems one rule of a plugin finds in the files given (0001-lint FR-009), by running `bun lint` over them in a new folder (its working
|
|
82
|
+
* folder, with a `bunfig.toml` of an empty `[lint]`), the rule set to `error` with its options. Problems of other rules (Bun's own
|
|
83
|
+
* defaults) are left out. An error where the linter fails (exit 2: a rule threw, or the plugin did not load).
|
|
84
|
+
*/
|
|
85
|
+
export async function lintFiles(r: LintRun): Promise<Result<readonly Problem[], string>> {
|
|
86
|
+
const prefix = r.prefix ?? "ifc";
|
|
87
|
+
const dir = await makeTempDir({ prefix: "ifc-lint-" });
|
|
88
|
+
try {
|
|
89
|
+
await writeTextFile(join(dir, "bunfig.toml"), "[lint]\n");
|
|
90
|
+
const names = Object.keys(r.files);
|
|
91
|
+
for (const [name, text] of Object.entries(r.files)) {
|
|
92
|
+
const path = join(dir, name);
|
|
93
|
+
await mkdir(dirname(path), { recursive: true });
|
|
94
|
+
await writeTextFile(path, text);
|
|
95
|
+
}
|
|
96
|
+
const out = join(dir, "report.json");
|
|
97
|
+
const setting = r.options === undefined ? ["error"] : ["error", r.options];
|
|
98
|
+
const result = await run(
|
|
99
|
+
[
|
|
100
|
+
...lintCommand(),
|
|
101
|
+
"lint",
|
|
102
|
+
"--format",
|
|
103
|
+
"json",
|
|
104
|
+
"--output-file",
|
|
105
|
+
out,
|
|
106
|
+
`--plugin=${r.plugin ?? PLUGIN_PATH}`,
|
|
107
|
+
"--rule",
|
|
108
|
+
JSON.stringify({ [`${prefix}/${r.rule}`]: setting }),
|
|
109
|
+
...names,
|
|
110
|
+
],
|
|
111
|
+
{ cwd: dir },
|
|
112
|
+
);
|
|
113
|
+
if (result.code !== 0 && result.code !== 1) return err(`bun lint exited with ${result.code}: ${result.stderr}${result.stdout}`);
|
|
114
|
+
const decoded = json(await readTextFile(out), report);
|
|
115
|
+
if (decoded.kind === "err")
|
|
116
|
+
return err(`bun lint's report is not what it should be: ${decoded.error.expected} at ${decoded.error.path}`);
|
|
117
|
+
const problems: Problem[] = [];
|
|
118
|
+
const real = await realPath(dir);
|
|
119
|
+
for (const f of decoded.value) {
|
|
120
|
+
const file = relative(real, await realPath(f.filePath)).replaceAll("\\", "/");
|
|
121
|
+
for (const m of f.messages ?? []) {
|
|
122
|
+
if (m.ruleId === undefined || m.ruleId === null || !m.ruleId.startsWith(`${prefix}/`)) continue;
|
|
123
|
+
problems.push({ file, rule: m.ruleId.slice(prefix.length + 1), line: m.line ?? 0, column: m.column ?? 0, message: m.message });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return ok(problems.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || a.column - b.column)));
|
|
127
|
+
} finally {
|
|
128
|
+
await remove(dir, { recursive: true });
|
|
129
|
+
}
|
|
130
|
+
}
|