@barqjs/cli 0.0.0-stage → 0.2.0-next.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 +128 -2
- package/dist/index.d.ts +104 -0
- package/dist/index.js +392 -0
- package/package.json +66 -4
- package/src/check.ts +382 -0
- package/src/index.ts +212 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Salama Ashoush
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,129 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @barqjs/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `barq` command. It runs a project through the compiler's diagnostics with
|
|
4
|
+
no build and no dev server, prints what it finds as text or JSON, and applies
|
|
5
|
+
the fixes the findings carry.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install --save-dev @barqjs/cli
|
|
9
|
+
npx barq check
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## `barq check [paths...]`
|
|
13
|
+
|
|
14
|
+
Checks every `.tsx` and `.jsx` file under the paths, and every script that
|
|
15
|
+
imports a `@barqjs/` package. With no path it checks the project root.
|
|
16
|
+
`node_modules`, `dist`, `build`, `coverage` and directories starting with a dot
|
|
17
|
+
are skipped.
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
src/view.tsx:7:32 warning BARQ001 `count` is an accessor, and here the function itself is used as the value. In a string it prints its own source text and in arithmetic it gives `NaN`. Call it: `count()`.
|
|
21
|
+
docs: https://github.com/salamaashoush/barq/blob/main/packages/compiler/docs/BARQ001.md
|
|
22
|
+
fix: `barq check --fix` repairs this
|
|
23
|
+
|
|
24
|
+
0 errors, 1 warning, 0 notes in 1 file, 1 more fixable with `--fix`
|
|
25
|
+
repair guide: node_modules/@barqjs/compiler/skills/compiler-diagnostics/SKILL.md
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Options:
|
|
29
|
+
|
|
30
|
+
- `--json`: one JSON document on stdout.
|
|
31
|
+
- `--fix`: apply the fixes, then report what is left.
|
|
32
|
+
- `--root <dir>`: the project root. Paths in the output are relative to it.
|
|
33
|
+
- `--routes <dir>`: the directory of file routes. Defaults to `src/routes`.
|
|
34
|
+
- `--level <CODE=level>`: set a code to `suppress`, `note`, `warning` or
|
|
35
|
+
`error`. Repeatable.
|
|
36
|
+
- `--max-warnings <n>`: exit 1 when there are more warnings than `n`.
|
|
37
|
+
|
|
38
|
+
Exit status: `0` when nothing is at error level, `1` when something is or the
|
|
39
|
+
warnings pass `--max-warnings`, `2` for a command line it does not understand.
|
|
40
|
+
|
|
41
|
+
### File routes
|
|
42
|
+
|
|
43
|
+
When the routes directory exists, the check reads it the way the build does and
|
|
44
|
+
writes nothing. Every `<Link to>` is then checked against the routes it gives
|
|
45
|
+
(`BARQ013`), and a route file whose `createFileRoute` id disagrees with its
|
|
46
|
+
filename is an error, as it is in a build.
|
|
47
|
+
|
|
48
|
+
### Settings in `package.json`
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"barq": {
|
|
53
|
+
"check": {
|
|
54
|
+
"paths": ["src"],
|
|
55
|
+
"routes": "src/routes",
|
|
56
|
+
"extraRoutes": ["/demo/dashboard", "/demo/dashboard/users/$id"],
|
|
57
|
+
"levels": { "BARQ004": "error", "BARQ011": "suppress" }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`extraRoutes` names patterns a link may use beside the file routes, such as
|
|
64
|
+
those of a second router the application builds by hand. A flag on the command
|
|
65
|
+
line replaces the setting of the same name, and a `--level` is added after the
|
|
66
|
+
ones here.
|
|
67
|
+
|
|
68
|
+
### The JSON form
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
{
|
|
72
|
+
"version": 1,
|
|
73
|
+
"root": "/work/app",
|
|
74
|
+
"files": 12,
|
|
75
|
+
"summary": { "errors": 0, "warnings": 1, "notes": 0, "fixable": 1, "fixed": 0 },
|
|
76
|
+
"findings": [
|
|
77
|
+
{
|
|
78
|
+
"code": "BARQ001",
|
|
79
|
+
"severity": "warning",
|
|
80
|
+
"message": "`count` is an accessor, and here the function itself is used as the value. ...",
|
|
81
|
+
"file": "src/view.tsx",
|
|
82
|
+
"line": 7,
|
|
83
|
+
"column": 32,
|
|
84
|
+
"endLine": 7,
|
|
85
|
+
"endColumn": 37,
|
|
86
|
+
"docs": "https://github.com/salamaashoush/barq/blob/main/packages/compiler/docs/BARQ001.md",
|
|
87
|
+
"skill": "node_modules/@barqjs/compiler/skills/compiler-diagnostics/SKILL.md#barq001",
|
|
88
|
+
"fix": [{ "pos": 221, "end": 221, "text": "()" }]
|
|
89
|
+
}
|
|
90
|
+
]
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`line` and `column` are 1-based. `skill` is the section of the installed repair
|
|
95
|
+
guide for the code. `fix` is present when the repair is one spelling: each edit
|
|
96
|
+
replaces the UTF-16 range `pos` to `end` of the file with `text`, and the two
|
|
97
|
+
are equal for an insertion.
|
|
98
|
+
|
|
99
|
+
### What `--fix` repairs
|
|
100
|
+
|
|
101
|
+
- `BARQ001`, `BARQ002`, `BARQ003`: an accessor used without being called gains
|
|
102
|
+
its call.
|
|
103
|
+
- `BARQ022`: `<Theme.Provider>` becomes `<Theme>`, in both tags.
|
|
104
|
+
- `BARQ023`: `classList` becomes `class`.
|
|
105
|
+
- `BARQ024`: `on:click` becomes `onClick`, and `attr:title` and `bool:disabled`
|
|
106
|
+
lose their prefix. An event name that is not one lowercase word, and the
|
|
107
|
+
`style:`, `class:` and `use:` namespaces, have no single spelling and are
|
|
108
|
+
left to you.
|
|
109
|
+
|
|
110
|
+
A fix can uncover another finding, so the file is compiled again after each
|
|
111
|
+
round, up to five rounds.
|
|
112
|
+
|
|
113
|
+
## `barq codes`
|
|
114
|
+
|
|
115
|
+
Lists every code the installed compiler can raise, with its default level and
|
|
116
|
+
one line on what it means. `--json` prints the list with each code's page and
|
|
117
|
+
guide section.
|
|
118
|
+
|
|
119
|
+
## From a program
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { check } from "@barqjs/cli";
|
|
123
|
+
|
|
124
|
+
const result = check({ root: process.cwd(), paths: ["src"] });
|
|
125
|
+
if (result.summary.errors > 0) process.exitCode = 1;
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`check`, `codes`, `applyFixes`, `formatText` and `projectOptions` are exported, with the types of
|
|
129
|
+
what they take and return.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
type Severity = "error" | "warning" | "note";
|
|
2
|
+
interface Edit {
|
|
3
|
+
/** UTF-16 offsets into the file as it was read. Equal for an insertion. */
|
|
4
|
+
pos: number;
|
|
5
|
+
end: number;
|
|
6
|
+
text: string;
|
|
7
|
+
}
|
|
8
|
+
interface Finding {
|
|
9
|
+
/** `BARQ001`, or absent for a syntax error, which is the parser's. */
|
|
10
|
+
code?: string;
|
|
11
|
+
severity: Severity;
|
|
12
|
+
message: string;
|
|
13
|
+
/** Relative to the root, with `/` separators. */
|
|
14
|
+
file: string;
|
|
15
|
+
line: number;
|
|
16
|
+
column: number;
|
|
17
|
+
endLine: number;
|
|
18
|
+
endColumn: number;
|
|
19
|
+
/** The page for the code. */
|
|
20
|
+
docs?: string;
|
|
21
|
+
/** The section of the installed repair guide for the code. */
|
|
22
|
+
skill?: string;
|
|
23
|
+
/** Present when `--fix` would repair it. */
|
|
24
|
+
fix?: Edit[];
|
|
25
|
+
}
|
|
26
|
+
interface CheckResult {
|
|
27
|
+
version: 1;
|
|
28
|
+
root: string;
|
|
29
|
+
files: number;
|
|
30
|
+
summary: {
|
|
31
|
+
errors: number;
|
|
32
|
+
warnings: number;
|
|
33
|
+
notes: number;
|
|
34
|
+
fixable: number;
|
|
35
|
+
fixed: number;
|
|
36
|
+
};
|
|
37
|
+
findings: Finding[];
|
|
38
|
+
}
|
|
39
|
+
interface CheckOptions {
|
|
40
|
+
/** The project root: paths in the result are relative to it. */
|
|
41
|
+
root: string;
|
|
42
|
+
/** Files and directories to check, relative to the root. Defaults to the root. */
|
|
43
|
+
paths?: readonly string[];
|
|
44
|
+
/** Apply the fixes the findings carry, and report what is left. */
|
|
45
|
+
fix?: boolean;
|
|
46
|
+
/** Per-code level, as `[code, "suppress" | "note" | "warning" | "error"]`. */
|
|
47
|
+
levels?: readonly (readonly [string, string])[];
|
|
48
|
+
/**
|
|
49
|
+
* The directory of file routes, relative to the root. When it exists, every
|
|
50
|
+
* `<Link to>` is checked against the routes in it and a route file whose id
|
|
51
|
+
* disagrees with its filename is reported.
|
|
52
|
+
* @default "src/routes"
|
|
53
|
+
*/
|
|
54
|
+
routes?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Route patterns a link may name beside the file routes, such as those of a
|
|
57
|
+
* second router the application builds by hand.
|
|
58
|
+
*/
|
|
59
|
+
extraRoutes?: readonly string[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* What a project sets for every run, under `barq.check` in its `package.json`.
|
|
63
|
+
* A flag on the command line replaces the field of the same name.
|
|
64
|
+
*/
|
|
65
|
+
export declare function projectOptions(root: string): Partial<CheckOptions>;
|
|
66
|
+
/**
|
|
67
|
+
* `source` with every fix applied that does not touch another's span, and how
|
|
68
|
+
* many findings that repaired. Last edit first, so an offset stays valid.
|
|
69
|
+
*/
|
|
70
|
+
export declare function applyFixes(source: string, findings: readonly Finding[]): [string, number];
|
|
71
|
+
export declare function check(options: CheckOptions): CheckResult;
|
|
72
|
+
interface CodeEntry {
|
|
73
|
+
code: string;
|
|
74
|
+
level: string;
|
|
75
|
+
summary: string;
|
|
76
|
+
docs: string;
|
|
77
|
+
skill: string;
|
|
78
|
+
}
|
|
79
|
+
/** Every code the installed compiler can raise, with its default level. */
|
|
80
|
+
export declare function codes(): CodeEntry[];
|
|
81
|
+
interface Paint {
|
|
82
|
+
error(text: string): string;
|
|
83
|
+
warning(text: string): string;
|
|
84
|
+
note(text: string): string;
|
|
85
|
+
dim(text: string): string;
|
|
86
|
+
bold(text: string): string;
|
|
87
|
+
}
|
|
88
|
+
/** The result for a person: one finding per block, then the count. */
|
|
89
|
+
export declare function formatText(result: CheckResult, paint: Paint): string;
|
|
90
|
+
interface Parsed {
|
|
91
|
+
command: string | undefined;
|
|
92
|
+
paths: string[];
|
|
93
|
+
json: boolean;
|
|
94
|
+
fix: boolean;
|
|
95
|
+
root: string;
|
|
96
|
+
routes: string | undefined;
|
|
97
|
+
levels: [string, string][];
|
|
98
|
+
maxWarnings: number | undefined;
|
|
99
|
+
help: boolean;
|
|
100
|
+
}
|
|
101
|
+
export declare function parse(argv: readonly string[]): Parsed;
|
|
102
|
+
/** Run one command line and answer with the exit status. */
|
|
103
|
+
export declare function main(argv: readonly string[], write: (text: string) => void): number;
|
|
104
|
+
export type { CheckOptions, CheckResult, CodeEntry, Edit, Finding, Paint, Severity };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { stdout } from "node:process";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { join, relative, resolve, sep } from "node:path";
|
|
7
|
+
// src/check.ts
|
|
8
|
+
/**
|
|
9
|
+
* `barq check`: every file of a project through the compiler's diagnostics,
|
|
10
|
+
* with no build and no dev server.
|
|
11
|
+
*
|
|
12
|
+
* The findings are the ones the Vite plugin reports, because they come from the
|
|
13
|
+
* same `transform`. What this adds is one answer for a whole project, a JSON
|
|
14
|
+
* form a program can read, and the fixes applied for the findings that carry
|
|
15
|
+
* one.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* What a project sets for every run, under `barq.check` in its `package.json`.
|
|
19
|
+
* A flag on the command line replaces the field of the same name.
|
|
20
|
+
*/
|
|
21
|
+
function projectOptions(root) {
|
|
22
|
+
let manifest;
|
|
23
|
+
try {
|
|
24
|
+
manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
25
|
+
} catch {
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
28
|
+
const set = manifest.barq?.check;
|
|
29
|
+
if (typeof set !== "object" || set === null) return {};
|
|
30
|
+
const { paths, routes, extraRoutes, levels } = set;
|
|
31
|
+
const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
|
|
32
|
+
const out = {};
|
|
33
|
+
const listed = strings(paths);
|
|
34
|
+
if (listed !== void 0) out.paths = listed;
|
|
35
|
+
if (typeof routes === "string") out.routes = routes;
|
|
36
|
+
const extra = strings(extraRoutes);
|
|
37
|
+
if (extra !== void 0) out.extraRoutes = extra;
|
|
38
|
+
if (typeof levels === "object" && levels !== null) out.levels = Object.entries(levels).filter((entry) => typeof entry[1] === "string");
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
let native;
|
|
42
|
+
function compiler() {
|
|
43
|
+
native ??= createRequire(import.meta.url)("@barqjs/compiler");
|
|
44
|
+
return native;
|
|
45
|
+
}
|
|
46
|
+
const SKILL = "node_modules/@barqjs/compiler/skills/compiler-diagnostics/SKILL.md";
|
|
47
|
+
const JSX = /\.[jt]sx$/;
|
|
48
|
+
const SCRIPT = /\.[cm]?[jt]s$/;
|
|
49
|
+
const SKIPPED = /* @__PURE__ */ new Set([
|
|
50
|
+
"node_modules",
|
|
51
|
+
"dist",
|
|
52
|
+
"build",
|
|
53
|
+
"coverage",
|
|
54
|
+
".git",
|
|
55
|
+
".vite",
|
|
56
|
+
".output"
|
|
57
|
+
]);
|
|
58
|
+
/** A fix can uncover the next one, such as a call inside a call. */
|
|
59
|
+
const MAX_PASSES = 5;
|
|
60
|
+
/** A script with no JSX is compiled only when it names barq, as the build does. */
|
|
61
|
+
function wanted(path, text) {
|
|
62
|
+
if (path.endsWith(".d.ts")) return false;
|
|
63
|
+
if (JSX.test(path)) return true;
|
|
64
|
+
return SCRIPT.test(path) && text().includes("@barqjs/");
|
|
65
|
+
}
|
|
66
|
+
function collect(path, out) {
|
|
67
|
+
if (statSync(path).isDirectory()) {
|
|
68
|
+
for (const entry of readdirSync(path).toSorted()) {
|
|
69
|
+
if (SKIPPED.has(entry) || entry.startsWith(".")) continue;
|
|
70
|
+
collect(join(path, entry), out);
|
|
71
|
+
}
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (JSX.test(path) || SCRIPT.test(path)) out.push(path);
|
|
75
|
+
}
|
|
76
|
+
function severityOf(level) {
|
|
77
|
+
return level === "error" ? "error" : level === "note" ? "note" : "warning";
|
|
78
|
+
}
|
|
79
|
+
/** A finding about the project and no one position in a file. */
|
|
80
|
+
function about(file, severity, message) {
|
|
81
|
+
return {
|
|
82
|
+
severity,
|
|
83
|
+
message,
|
|
84
|
+
file,
|
|
85
|
+
line: 1,
|
|
86
|
+
column: 1,
|
|
87
|
+
endLine: 1,
|
|
88
|
+
endColumn: 1
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The file routes, read the way the build reads them and written nowhere: the
|
|
93
|
+
* patterns a link may name, and what the scan itself found wrong.
|
|
94
|
+
*/
|
|
95
|
+
function routesOf(root, dir) {
|
|
96
|
+
if (!existsSync(join(root, dir))) return { findings: [] };
|
|
97
|
+
const tree = compiler().routeTree(root, dir);
|
|
98
|
+
return {
|
|
99
|
+
patterns: tree.patterns,
|
|
100
|
+
findings: [...tree.warnings.map((warning) => about(dir, "warning", warning)), ...tree.mismatches.map((mismatch) => about(mismatch.file, "error", `\`createFileRoute("${mismatch.declared}")\` names an id that differs from the one this file's name gives, \`${mismatch.expected}\`, and a build refuses it. Write \`createFileRoute("${mismatch.expected}")\`.`))]
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function findingsOf(file, root, source, project) {
|
|
104
|
+
const { options } = project;
|
|
105
|
+
const name = relative(root, file).split(sep).join("/");
|
|
106
|
+
let diagnostics;
|
|
107
|
+
try {
|
|
108
|
+
diagnostics = compiler().transform(source, {
|
|
109
|
+
filename: file,
|
|
110
|
+
root,
|
|
111
|
+
dev: true,
|
|
112
|
+
diagnostics: true,
|
|
113
|
+
sourceNames: false,
|
|
114
|
+
checks: options.levels?.map(([code, level]) => [code, level]),
|
|
115
|
+
routes: project.patterns
|
|
116
|
+
}).diagnostics ?? [];
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return [about(name, "error", error instanceof Error ? error.message : String(error))];
|
|
119
|
+
}
|
|
120
|
+
return diagnostics.map((found) => {
|
|
121
|
+
const finding = {
|
|
122
|
+
severity: severityOf(found.severity),
|
|
123
|
+
message: found.message,
|
|
124
|
+
file: name,
|
|
125
|
+
line: found.line,
|
|
126
|
+
column: found.column,
|
|
127
|
+
endLine: found.endLine,
|
|
128
|
+
endColumn: found.endColumn
|
|
129
|
+
};
|
|
130
|
+
if (found.code !== void 0) {
|
|
131
|
+
finding.code = found.code;
|
|
132
|
+
finding.skill = `${SKILL}#${found.code.toLowerCase()}`;
|
|
133
|
+
}
|
|
134
|
+
if (found.docs !== void 0) finding.docs = found.docs;
|
|
135
|
+
if (found.fix !== void 0 && found.fix.length > 0) finding.fix = found.fix;
|
|
136
|
+
return finding;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* `source` with every fix applied that does not touch another's span, and how
|
|
141
|
+
* many findings that repaired. Last edit first, so an offset stays valid.
|
|
142
|
+
*/
|
|
143
|
+
function applyFixes(source, findings) {
|
|
144
|
+
const chosen = [];
|
|
145
|
+
let repaired = 0;
|
|
146
|
+
for (const finding of findings) {
|
|
147
|
+
const edits = finding.fix;
|
|
148
|
+
if (edits === void 0) continue;
|
|
149
|
+
const clash = edits.some((edit) => chosen.some((taken) => edit.pos < taken.end && taken.pos < edit.end));
|
|
150
|
+
const repeated = edits.every((edit) => chosen.some((taken) => taken.pos === edit.pos && taken.end === edit.end && taken.text === edit.text));
|
|
151
|
+
if (clash || repeated) continue;
|
|
152
|
+
chosen.push(...edits);
|
|
153
|
+
repaired++;
|
|
154
|
+
}
|
|
155
|
+
let text = source;
|
|
156
|
+
for (const edit of chosen.toSorted((a, b) => b.pos - a.pos)) text = text.slice(0, edit.pos) + edit.text + text.slice(edit.end);
|
|
157
|
+
return [text, repaired];
|
|
158
|
+
}
|
|
159
|
+
function check(options) {
|
|
160
|
+
const root = resolve(options.root);
|
|
161
|
+
const files = [];
|
|
162
|
+
for (const path of options.paths === void 0 || options.paths.length === 0 ? ["."] : options.paths) collect(resolve(root, path), files);
|
|
163
|
+
const routes = routesOf(root, options.routes ?? "src/routes");
|
|
164
|
+
const project = {
|
|
165
|
+
options,
|
|
166
|
+
patterns: routes.patterns === void 0 ? void 0 : [...routes.patterns, ...options.extraRoutes ?? []]
|
|
167
|
+
};
|
|
168
|
+
const findings = [...routes.findings];
|
|
169
|
+
let checked = 0;
|
|
170
|
+
let fixed = 0;
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
let source;
|
|
173
|
+
const text = () => source ??= readFileSync(file, "utf8");
|
|
174
|
+
if (!wanted(file, text)) continue;
|
|
175
|
+
checked++;
|
|
176
|
+
let found = findingsOf(file, root, text(), project);
|
|
177
|
+
if (options.fix === true) {
|
|
178
|
+
let current = text();
|
|
179
|
+
for (let pass = 0; pass < MAX_PASSES; pass++) {
|
|
180
|
+
const [next, repaired] = applyFixes(current, found);
|
|
181
|
+
if (repaired === 0) break;
|
|
182
|
+
current = next;
|
|
183
|
+
fixed += repaired;
|
|
184
|
+
found = findingsOf(file, root, current, project);
|
|
185
|
+
}
|
|
186
|
+
if (current !== text()) writeFileSync(file, current);
|
|
187
|
+
}
|
|
188
|
+
findings.push(...found);
|
|
189
|
+
}
|
|
190
|
+
const count = (severity) => findings.filter((finding) => finding.severity === severity).length;
|
|
191
|
+
return {
|
|
192
|
+
version: 1,
|
|
193
|
+
root,
|
|
194
|
+
files: checked,
|
|
195
|
+
summary: {
|
|
196
|
+
errors: count("error"),
|
|
197
|
+
warnings: count("warning"),
|
|
198
|
+
notes: count("note"),
|
|
199
|
+
fixable: findings.filter((finding) => finding.fix !== void 0).length,
|
|
200
|
+
fixed
|
|
201
|
+
},
|
|
202
|
+
findings
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
/** Every code the installed compiler can raise, with its default level. */
|
|
206
|
+
function codes() {
|
|
207
|
+
return compiler().diagnosticCodes().map((entry) => ({
|
|
208
|
+
...entry,
|
|
209
|
+
skill: `${SKILL}#${entry.code.toLowerCase()}`
|
|
210
|
+
}));
|
|
211
|
+
}
|
|
212
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
213
|
+
/** The result for a person: one finding per block, then the count. */
|
|
214
|
+
function formatText(result, paint) {
|
|
215
|
+
const lines = [];
|
|
216
|
+
for (const finding of result.findings) {
|
|
217
|
+
const at = `${finding.file}:${finding.line}:${finding.column}`;
|
|
218
|
+
const label = paint[finding.severity](finding.severity);
|
|
219
|
+
const code = finding.code === void 0 ? "" : ` ${paint.bold(finding.code)}`;
|
|
220
|
+
lines.push(`${at} ${label}${code} ${finding.message}`);
|
|
221
|
+
if (finding.docs !== void 0) lines.push(paint.dim(` docs: ${finding.docs}`));
|
|
222
|
+
if (finding.fix !== void 0) lines.push(paint.dim(" fix: `barq check --fix` repairs this"));
|
|
223
|
+
lines.push("");
|
|
224
|
+
}
|
|
225
|
+
const { errors, warnings, notes, fixable, fixed } = result.summary;
|
|
226
|
+
let summary = `${[
|
|
227
|
+
plural(errors, "error"),
|
|
228
|
+
plural(warnings, "warning"),
|
|
229
|
+
plural(notes, "note")
|
|
230
|
+
].join(", ")} in ${plural(result.files, "file")}`;
|
|
231
|
+
if (fixed > 0) summary += `, ${fixed} fixed`;
|
|
232
|
+
if (fixable > 0) summary += `, ${fixable} more fixable with \`--fix\``;
|
|
233
|
+
lines.push(summary);
|
|
234
|
+
if (result.findings.some((finding) => finding.code !== void 0)) lines.push(paint.dim(`repair guide: ${SKILL}`));
|
|
235
|
+
return lines.join("\n");
|
|
236
|
+
}
|
|
237
|
+
// src/index.ts
|
|
238
|
+
/**
|
|
239
|
+
* `barq`: the command line of the framework.
|
|
240
|
+
*
|
|
241
|
+
* No dependencies beyond the compiler it drives. The argument parsing is
|
|
242
|
+
* smaller than a library that would do it.
|
|
243
|
+
*/
|
|
244
|
+
const HELP = `\
|
|
245
|
+
barq check [paths...] Report the compiler's findings for a project
|
|
246
|
+
barq codes List every code the compiler can raise
|
|
247
|
+
|
|
248
|
+
check options:
|
|
249
|
+
--json One JSON document on stdout, for a program to read
|
|
250
|
+
--fix Apply the fixes the findings carry, then report what is left
|
|
251
|
+
--root <dir> The project root (default: the current directory)
|
|
252
|
+
--routes <dir> The file routes, for checking links (default: src/routes)
|
|
253
|
+
--level <CODE=level> Set a code to suppress, note, warning or error; repeatable
|
|
254
|
+
--max-warnings <n> Exit 1 when there are more warnings than this
|
|
255
|
+
|
|
256
|
+
codes options:
|
|
257
|
+
--json The list as JSON
|
|
258
|
+
|
|
259
|
+
A project sets its own defaults under "barq": { "check": { ... } } in
|
|
260
|
+
package.json: paths, routes, extraRoutes (patterns beside the file routes) and
|
|
261
|
+
levels ({ "BARQ004": "error" }).
|
|
262
|
+
|
|
263
|
+
Exit status: 0 clean, 1 findings at error level or past --max-warnings, 2 a
|
|
264
|
+
command line this does not understand.
|
|
265
|
+
`;
|
|
266
|
+
const LEVELS = /* @__PURE__ */ new Set([
|
|
267
|
+
"suppress",
|
|
268
|
+
"note",
|
|
269
|
+
"warning",
|
|
270
|
+
"error"
|
|
271
|
+
]);
|
|
272
|
+
var UsageError = class extends Error {};
|
|
273
|
+
function parse(argv) {
|
|
274
|
+
const parsed = {
|
|
275
|
+
command: void 0,
|
|
276
|
+
paths: [],
|
|
277
|
+
json: false,
|
|
278
|
+
fix: false,
|
|
279
|
+
root: process.cwd(),
|
|
280
|
+
routes: void 0,
|
|
281
|
+
levels: [],
|
|
282
|
+
maxWarnings: void 0,
|
|
283
|
+
help: false
|
|
284
|
+
};
|
|
285
|
+
const value = (flag, index) => {
|
|
286
|
+
const next = argv[index];
|
|
287
|
+
if (next === void 0 || next.startsWith("--")) throw new UsageError(`\`${flag}\` takes a value, and none follows it.`);
|
|
288
|
+
return next;
|
|
289
|
+
};
|
|
290
|
+
for (let index = 0; index < argv.length; index++) {
|
|
291
|
+
const arg = argv[index];
|
|
292
|
+
switch (arg) {
|
|
293
|
+
case "--help":
|
|
294
|
+
case "-h":
|
|
295
|
+
parsed.help = true;
|
|
296
|
+
break;
|
|
297
|
+
case "--json":
|
|
298
|
+
parsed.json = true;
|
|
299
|
+
break;
|
|
300
|
+
case "--fix":
|
|
301
|
+
parsed.fix = true;
|
|
302
|
+
break;
|
|
303
|
+
case "--root":
|
|
304
|
+
parsed.root = value(arg, ++index);
|
|
305
|
+
break;
|
|
306
|
+
case "--routes":
|
|
307
|
+
parsed.routes = value(arg, ++index);
|
|
308
|
+
break;
|
|
309
|
+
case "--level": {
|
|
310
|
+
const pair = value(arg, ++index);
|
|
311
|
+
const [code, level] = pair.split("=");
|
|
312
|
+
if (code === void 0 || level === void 0 || !LEVELS.has(level)) throw new UsageError(`\`--level ${pair}\` is not \`CODE=level\`, where level is one of suppress, note, warning, error. Write it as \`--level BARQ004=error\`.`);
|
|
313
|
+
parsed.levels.push([code.toUpperCase(), level]);
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
case "--max-warnings": {
|
|
317
|
+
const text = value(arg, ++index);
|
|
318
|
+
const count = Number(text);
|
|
319
|
+
if (!Number.isInteger(count) || count < 0) throw new UsageError(`\`--max-warnings ${text}\` is not a whole number. Write it as \`--max-warnings 0\`.`);
|
|
320
|
+
parsed.maxWarnings = count;
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
default:
|
|
324
|
+
if (arg.startsWith("-")) throw new UsageError(`\`${arg}\` is not an option of barq. Run \`barq --help\`.`);
|
|
325
|
+
if (parsed.command === void 0) parsed.command = arg;
|
|
326
|
+
else parsed.paths.push(arg);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return parsed;
|
|
330
|
+
}
|
|
331
|
+
function painter() {
|
|
332
|
+
const styled = stdout.isTTY && process.env["NO_COLOR"] === void 0;
|
|
333
|
+
const code = (open) => (text) => styled ? `\u001B[${open}m${text}\u001B[0m` : text;
|
|
334
|
+
return {
|
|
335
|
+
error: code("31"),
|
|
336
|
+
warning: code("33"),
|
|
337
|
+
note: code("36"),
|
|
338
|
+
dim: code("2"),
|
|
339
|
+
bold: code("1")
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/** Run one command line and answer with the exit status. */
|
|
343
|
+
function main(argv, write) {
|
|
344
|
+
let parsed;
|
|
345
|
+
try {
|
|
346
|
+
parsed = parse(argv);
|
|
347
|
+
} catch (error) {
|
|
348
|
+
if (!(error instanceof UsageError)) throw error;
|
|
349
|
+
write(`${error.message}\n`);
|
|
350
|
+
return 2;
|
|
351
|
+
}
|
|
352
|
+
if (parsed.help || parsed.command === void 0) {
|
|
353
|
+
write(HELP);
|
|
354
|
+
return parsed.help ? 0 : 2;
|
|
355
|
+
}
|
|
356
|
+
switch (parsed.command) {
|
|
357
|
+
case "check": {
|
|
358
|
+
const set = projectOptions(parsed.root);
|
|
359
|
+
const result = check({
|
|
360
|
+
...set,
|
|
361
|
+
root: parsed.root,
|
|
362
|
+
fix: parsed.fix,
|
|
363
|
+
levels: [...set.levels ?? [], ...parsed.levels],
|
|
364
|
+
...parsed.paths.length > 0 ? { paths: parsed.paths } : {},
|
|
365
|
+
...parsed.routes !== void 0 ? { routes: parsed.routes } : {}
|
|
366
|
+
});
|
|
367
|
+
write(parsed.json ? `${JSON.stringify(result, null, 2)}\n` : `${formatText(result, painter())}\n`);
|
|
368
|
+
const { errors, warnings } = result.summary;
|
|
369
|
+
const over = parsed.maxWarnings !== void 0 && warnings > parsed.maxWarnings;
|
|
370
|
+
return errors > 0 || over ? 1 : 0;
|
|
371
|
+
}
|
|
372
|
+
case "codes": {
|
|
373
|
+
const list = codes();
|
|
374
|
+
write(parsed.json ? `${JSON.stringify(list, null, 2)}\n` : `${list.map((entry) => `${entry.code} ${entry.level.padEnd(7)} ${entry.summary}`).join("\n")}\n`);
|
|
375
|
+
return 0;
|
|
376
|
+
}
|
|
377
|
+
default:
|
|
378
|
+
write(`\`${parsed.command}\` is not a command of barq. Run \`barq --help\`.\n`);
|
|
379
|
+
return 2;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The guard compares the script node was asked to run with this module rather
|
|
384
|
+
* than reading `import.meta.main`, which node defines only from 24.2. `argv[1]`
|
|
385
|
+
* is the `.bin` symlink under a package manager, hence the realpath.
|
|
386
|
+
*/
|
|
387
|
+
function invokedDirectly() {
|
|
388
|
+
const script = process.argv[1];
|
|
389
|
+
return script !== void 0 && realpathSync(script) === fileURLToPath(import.meta.url);
|
|
390
|
+
}
|
|
391
|
+
if (invokedDirectly()) process.exitCode = main(process.argv.slice(2), (text) => stdout.write(text));
|
|
392
|
+
export { applyFixes, check, codes, formatText, main, parse, projectOptions };
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@barqjs/cli",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0-next.0",
|
|
4
|
+
"description": "The barq command: check a project against the compiler's diagnostics, as text or JSON, and apply the fixes it offers",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"agents",
|
|
7
|
+
"barq",
|
|
8
|
+
"check",
|
|
9
|
+
"cli",
|
|
10
|
+
"diagnostics",
|
|
11
|
+
"lint"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/salamaashoush/barq#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/salamaashoush/barq/issues"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/salamaashoush/barq.git",
|
|
21
|
+
"directory": "packages/cli"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"src",
|
|
26
|
+
"!src/**/*.test.ts",
|
|
27
|
+
"!src/**/*.test.tsx",
|
|
28
|
+
"!src/**/test-*.ts",
|
|
29
|
+
"!src/**/*-harness.ts",
|
|
30
|
+
"!src/**/*-probe.ts",
|
|
31
|
+
"!src/**/fixtures",
|
|
32
|
+
"!src/**/fixtures.ts",
|
|
33
|
+
"!src/**/ssr-fixtures.ts"
|
|
34
|
+
],
|
|
35
|
+
"type": "module",
|
|
36
|
+
"sideEffects": false,
|
|
37
|
+
"bin": {
|
|
38
|
+
"barq": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"types": "./dist/index.d.ts",
|
|
43
|
+
"bun": "./src/index.ts",
|
|
44
|
+
"import": "./dist/index.js"
|
|
45
|
+
},
|
|
46
|
+
"./package.json": "./package.json"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"dev": "tsdown --watch",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"test": "bun test --timeout 60000"
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"@barqjs/compiler": "0.2.0-next.0"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@types/bun": "^1.4.4",
|
|
59
|
+
"typescript": "^7.0.2"
|
|
60
|
+
},
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=20.19.0"
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public",
|
|
66
|
+
"provenance": true
|
|
67
|
+
}
|
|
68
|
+
}
|
package/src/check.ts
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `barq check`: every file of a project through the compiler's diagnostics,
|
|
3
|
+
* with no build and no dev server.
|
|
4
|
+
*
|
|
5
|
+
* The findings are the ones the Vite plugin reports, because they come from the
|
|
6
|
+
* same `transform`. What this adds is one answer for a whole project, a JSON
|
|
7
|
+
* form a program can read, and the fixes applied for the findings that carry
|
|
8
|
+
* one.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
import { join, relative, resolve, sep } from "node:path";
|
|
14
|
+
|
|
15
|
+
export type Severity = "error" | "warning" | "note";
|
|
16
|
+
|
|
17
|
+
export interface Edit {
|
|
18
|
+
/** UTF-16 offsets into the file as it was read. Equal for an insertion. */
|
|
19
|
+
pos: number;
|
|
20
|
+
end: number;
|
|
21
|
+
text: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface Finding {
|
|
25
|
+
/** `BARQ001`, or absent for a syntax error, which is the parser's. */
|
|
26
|
+
code?: string;
|
|
27
|
+
severity: Severity;
|
|
28
|
+
message: string;
|
|
29
|
+
/** Relative to the root, with `/` separators. */
|
|
30
|
+
file: string;
|
|
31
|
+
line: number;
|
|
32
|
+
column: number;
|
|
33
|
+
endLine: number;
|
|
34
|
+
endColumn: number;
|
|
35
|
+
/** The page for the code. */
|
|
36
|
+
docs?: string;
|
|
37
|
+
/** The section of the installed repair guide for the code. */
|
|
38
|
+
skill?: string;
|
|
39
|
+
/** Present when `--fix` would repair it. */
|
|
40
|
+
fix?: Edit[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CheckResult {
|
|
44
|
+
version: 1;
|
|
45
|
+
root: string;
|
|
46
|
+
files: number;
|
|
47
|
+
summary: { errors: number; warnings: number; notes: number; fixable: number; fixed: number };
|
|
48
|
+
findings: Finding[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface CheckOptions {
|
|
52
|
+
/** The project root: paths in the result are relative to it. */
|
|
53
|
+
root: string;
|
|
54
|
+
/** Files and directories to check, relative to the root. Defaults to the root. */
|
|
55
|
+
paths?: readonly string[];
|
|
56
|
+
/** Apply the fixes the findings carry, and report what is left. */
|
|
57
|
+
fix?: boolean;
|
|
58
|
+
/** Per-code level, as `[code, "suppress" | "note" | "warning" | "error"]`. */
|
|
59
|
+
levels?: readonly (readonly [string, string])[];
|
|
60
|
+
/**
|
|
61
|
+
* The directory of file routes, relative to the root. When it exists, every
|
|
62
|
+
* `<Link to>` is checked against the routes in it and a route file whose id
|
|
63
|
+
* disagrees with its filename is reported.
|
|
64
|
+
* @default "src/routes"
|
|
65
|
+
*/
|
|
66
|
+
routes?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Route patterns a link may name beside the file routes, such as those of a
|
|
69
|
+
* second router the application builds by hand.
|
|
70
|
+
*/
|
|
71
|
+
extraRoutes?: readonly string[];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* What a project sets for every run, under `barq.check` in its `package.json`.
|
|
76
|
+
* A flag on the command line replaces the field of the same name.
|
|
77
|
+
*/
|
|
78
|
+
export function projectOptions(root: string): Partial<CheckOptions> {
|
|
79
|
+
let manifest: unknown;
|
|
80
|
+
try {
|
|
81
|
+
manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
82
|
+
} catch {
|
|
83
|
+
return {};
|
|
84
|
+
}
|
|
85
|
+
const set = (manifest as { barq?: { check?: unknown } }).barq?.check;
|
|
86
|
+
if (typeof set !== "object" || set === null) return {};
|
|
87
|
+
const { paths, routes, extraRoutes, levels } = set as Record<string, unknown>;
|
|
88
|
+
const strings = (value: unknown): string[] | undefined =>
|
|
89
|
+
Array.isArray(value) && value.every((item) => typeof item === "string") ? value : undefined;
|
|
90
|
+
const out: Partial<CheckOptions> = {};
|
|
91
|
+
const listed = strings(paths);
|
|
92
|
+
if (listed !== undefined) out.paths = listed;
|
|
93
|
+
if (typeof routes === "string") out.routes = routes;
|
|
94
|
+
const extra = strings(extraRoutes);
|
|
95
|
+
if (extra !== undefined) out.extraRoutes = extra;
|
|
96
|
+
if (typeof levels === "object" && levels !== null) {
|
|
97
|
+
out.levels = Object.entries(levels).filter(
|
|
98
|
+
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface NativeDiagnostic {
|
|
105
|
+
code?: string;
|
|
106
|
+
severity: string;
|
|
107
|
+
message: string;
|
|
108
|
+
line: number;
|
|
109
|
+
column: number;
|
|
110
|
+
endLine: number;
|
|
111
|
+
endColumn: number;
|
|
112
|
+
docs?: string;
|
|
113
|
+
fix?: Edit[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface Native {
|
|
117
|
+
transform(
|
|
118
|
+
code: string,
|
|
119
|
+
options: {
|
|
120
|
+
filename: string;
|
|
121
|
+
root: string;
|
|
122
|
+
dev: boolean;
|
|
123
|
+
diagnostics: boolean;
|
|
124
|
+
sourceNames: boolean;
|
|
125
|
+
checks?: string[][];
|
|
126
|
+
routes?: string[];
|
|
127
|
+
},
|
|
128
|
+
): { diagnostics?: NativeDiagnostic[] };
|
|
129
|
+
diagnosticCodes(): { code: string; level: string; summary: string; docs: string }[];
|
|
130
|
+
routeTree(
|
|
131
|
+
root: string,
|
|
132
|
+
dir: string,
|
|
133
|
+
): {
|
|
134
|
+
patterns: string[];
|
|
135
|
+
warnings: string[];
|
|
136
|
+
mismatches: { file: string; declared: string; expected: string }[];
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let native: Native | undefined;
|
|
141
|
+
|
|
142
|
+
function compiler(): Native {
|
|
143
|
+
native ??= createRequire(import.meta.url)("@barqjs/compiler") as Native;
|
|
144
|
+
return native;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const SKILL = "node_modules/@barqjs/compiler/skills/compiler-diagnostics/SKILL.md";
|
|
148
|
+
const JSX = /\.[jt]sx$/;
|
|
149
|
+
const SCRIPT = /\.[cm]?[jt]s$/;
|
|
150
|
+
const SKIPPED = new Set(["node_modules", "dist", "build", "coverage", ".git", ".vite", ".output"]);
|
|
151
|
+
/** A fix can uncover the next one, such as a call inside a call. */
|
|
152
|
+
const MAX_PASSES = 5;
|
|
153
|
+
|
|
154
|
+
/** A script with no JSX is compiled only when it names barq, as the build does. */
|
|
155
|
+
function wanted(path: string, text: () => string): boolean {
|
|
156
|
+
if (path.endsWith(".d.ts")) return false;
|
|
157
|
+
if (JSX.test(path)) return true;
|
|
158
|
+
return SCRIPT.test(path) && text().includes("@barqjs/");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function collect(path: string, out: string[]): void {
|
|
162
|
+
if (statSync(path).isDirectory()) {
|
|
163
|
+
for (const entry of readdirSync(path).toSorted()) {
|
|
164
|
+
if (SKIPPED.has(entry) || entry.startsWith(".")) continue;
|
|
165
|
+
collect(join(path, entry), out);
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (JSX.test(path) || SCRIPT.test(path)) out.push(path);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function severityOf(level: string): Severity {
|
|
173
|
+
return level === "error" ? "error" : level === "note" ? "note" : "warning";
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
interface Project {
|
|
177
|
+
options: CheckOptions;
|
|
178
|
+
/** The route patterns, when the project has file routes. */
|
|
179
|
+
patterns: string[] | undefined;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A finding about the project and no one position in a file. */
|
|
183
|
+
function about(file: string, severity: Severity, message: string): Finding {
|
|
184
|
+
return { severity, message, file, line: 1, column: 1, endLine: 1, endColumn: 1 };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The file routes, read the way the build reads them and written nowhere: the
|
|
189
|
+
* patterns a link may name, and what the scan itself found wrong.
|
|
190
|
+
*/
|
|
191
|
+
function routesOf(root: string, dir: string): { patterns?: string[]; findings: Finding[] } {
|
|
192
|
+
if (!existsSync(join(root, dir))) return { findings: [] };
|
|
193
|
+
const tree = compiler().routeTree(root, dir);
|
|
194
|
+
return {
|
|
195
|
+
patterns: tree.patterns,
|
|
196
|
+
findings: [
|
|
197
|
+
...tree.warnings.map((warning) => about(dir, "warning", warning)),
|
|
198
|
+
...tree.mismatches.map((mismatch) =>
|
|
199
|
+
about(
|
|
200
|
+
mismatch.file,
|
|
201
|
+
"error",
|
|
202
|
+
`\`createFileRoute("${mismatch.declared}")\` names an id that differs from the one this file's name gives, \`${mismatch.expected}\`, and a build refuses it. Write \`createFileRoute("${mismatch.expected}")\`.`,
|
|
203
|
+
),
|
|
204
|
+
),
|
|
205
|
+
],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function findingsOf(file: string, root: string, source: string, project: Project): Finding[] {
|
|
210
|
+
const { options } = project;
|
|
211
|
+
const name = relative(root, file).split(sep).join("/");
|
|
212
|
+
let diagnostics: NativeDiagnostic[];
|
|
213
|
+
try {
|
|
214
|
+
diagnostics =
|
|
215
|
+
compiler().transform(source, {
|
|
216
|
+
filename: file,
|
|
217
|
+
root,
|
|
218
|
+
dev: true,
|
|
219
|
+
diagnostics: true,
|
|
220
|
+
sourceNames: false,
|
|
221
|
+
checks: options.levels?.map(([code, level]) => [code, level]),
|
|
222
|
+
routes: project.patterns,
|
|
223
|
+
}).diagnostics ?? [];
|
|
224
|
+
} catch (error) {
|
|
225
|
+
// The compiler refuses a file it cannot parse by throwing, and the message
|
|
226
|
+
// already carries the position.
|
|
227
|
+
return [about(name, "error", error instanceof Error ? error.message : String(error))];
|
|
228
|
+
}
|
|
229
|
+
return diagnostics.map((found) => {
|
|
230
|
+
const finding: Finding = {
|
|
231
|
+
severity: severityOf(found.severity),
|
|
232
|
+
message: found.message,
|
|
233
|
+
file: name,
|
|
234
|
+
line: found.line,
|
|
235
|
+
column: found.column,
|
|
236
|
+
endLine: found.endLine,
|
|
237
|
+
endColumn: found.endColumn,
|
|
238
|
+
};
|
|
239
|
+
if (found.code !== undefined) {
|
|
240
|
+
finding.code = found.code;
|
|
241
|
+
finding.skill = `${SKILL}#${found.code.toLowerCase()}`;
|
|
242
|
+
}
|
|
243
|
+
if (found.docs !== undefined) finding.docs = found.docs;
|
|
244
|
+
if (found.fix !== undefined && found.fix.length > 0) finding.fix = found.fix;
|
|
245
|
+
return finding;
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* `source` with every fix applied that does not touch another's span, and how
|
|
251
|
+
* many findings that repaired. Last edit first, so an offset stays valid.
|
|
252
|
+
*/
|
|
253
|
+
export function applyFixes(source: string, findings: readonly Finding[]): [string, number] {
|
|
254
|
+
const chosen: Edit[] = [];
|
|
255
|
+
let repaired = 0;
|
|
256
|
+
for (const finding of findings) {
|
|
257
|
+
const edits = finding.fix;
|
|
258
|
+
if (edits === undefined) continue;
|
|
259
|
+
const clash = edits.some((edit) =>
|
|
260
|
+
chosen.some((taken) => edit.pos < taken.end && taken.pos < edit.end),
|
|
261
|
+
);
|
|
262
|
+
const repeated = edits.every((edit) =>
|
|
263
|
+
chosen.some(
|
|
264
|
+
(taken) => taken.pos === edit.pos && taken.end === edit.end && taken.text === edit.text,
|
|
265
|
+
),
|
|
266
|
+
);
|
|
267
|
+
if (clash || repeated) continue;
|
|
268
|
+
chosen.push(...edits);
|
|
269
|
+
repaired++;
|
|
270
|
+
}
|
|
271
|
+
let text = source;
|
|
272
|
+
for (const edit of chosen.toSorted((a, b) => b.pos - a.pos)) {
|
|
273
|
+
text = text.slice(0, edit.pos) + edit.text + text.slice(edit.end);
|
|
274
|
+
}
|
|
275
|
+
return [text, repaired];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function check(options: CheckOptions): CheckResult {
|
|
279
|
+
const root = resolve(options.root);
|
|
280
|
+
const files: string[] = [];
|
|
281
|
+
for (const path of options.paths === undefined || options.paths.length === 0
|
|
282
|
+
? ["."]
|
|
283
|
+
: options.paths) {
|
|
284
|
+
collect(resolve(root, path), files);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const routes = routesOf(root, options.routes ?? "src/routes");
|
|
288
|
+
const project: Project = {
|
|
289
|
+
options,
|
|
290
|
+
patterns:
|
|
291
|
+
routes.patterns === undefined
|
|
292
|
+
? undefined
|
|
293
|
+
: [...routes.patterns, ...(options.extraRoutes ?? [])],
|
|
294
|
+
};
|
|
295
|
+
const findings: Finding[] = [...routes.findings];
|
|
296
|
+
let checked = 0;
|
|
297
|
+
let fixed = 0;
|
|
298
|
+
for (const file of files) {
|
|
299
|
+
let source: string | undefined;
|
|
300
|
+
const text = (): string => (source ??= readFileSync(file, "utf8"));
|
|
301
|
+
if (!wanted(file, text)) continue;
|
|
302
|
+
checked++;
|
|
303
|
+
let found = findingsOf(file, root, text(), project);
|
|
304
|
+
if (options.fix === true) {
|
|
305
|
+
let current = text();
|
|
306
|
+
for (let pass = 0; pass < MAX_PASSES; pass++) {
|
|
307
|
+
const [next, repaired] = applyFixes(current, found);
|
|
308
|
+
if (repaired === 0) break;
|
|
309
|
+
current = next;
|
|
310
|
+
fixed += repaired;
|
|
311
|
+
found = findingsOf(file, root, current, project);
|
|
312
|
+
}
|
|
313
|
+
if (current !== text()) writeFileSync(file, current);
|
|
314
|
+
}
|
|
315
|
+
findings.push(...found);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const count = (severity: Severity): number =>
|
|
319
|
+
findings.filter((finding) => finding.severity === severity).length;
|
|
320
|
+
return {
|
|
321
|
+
version: 1,
|
|
322
|
+
root,
|
|
323
|
+
files: checked,
|
|
324
|
+
summary: {
|
|
325
|
+
errors: count("error"),
|
|
326
|
+
warnings: count("warning"),
|
|
327
|
+
notes: count("note"),
|
|
328
|
+
fixable: findings.filter((finding) => finding.fix !== undefined).length,
|
|
329
|
+
fixed,
|
|
330
|
+
},
|
|
331
|
+
findings,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export interface CodeEntry {
|
|
336
|
+
code: string;
|
|
337
|
+
level: string;
|
|
338
|
+
summary: string;
|
|
339
|
+
docs: string;
|
|
340
|
+
skill: string;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Every code the installed compiler can raise, with its default level. */
|
|
344
|
+
export function codes(): CodeEntry[] {
|
|
345
|
+
return compiler()
|
|
346
|
+
.diagnosticCodes()
|
|
347
|
+
.map((entry) => ({ ...entry, skill: `${SKILL}#${entry.code.toLowerCase()}` }));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export interface Paint {
|
|
351
|
+
error(text: string): string;
|
|
352
|
+
warning(text: string): string;
|
|
353
|
+
note(text: string): string;
|
|
354
|
+
dim(text: string): string;
|
|
355
|
+
bold(text: string): string;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
359
|
+
|
|
360
|
+
/** The result for a person: one finding per block, then the count. */
|
|
361
|
+
export function formatText(result: CheckResult, paint: Paint): string {
|
|
362
|
+
const lines: string[] = [];
|
|
363
|
+
for (const finding of result.findings) {
|
|
364
|
+
const at = `${finding.file}:${finding.line}:${finding.column}`;
|
|
365
|
+
const label = paint[finding.severity](finding.severity);
|
|
366
|
+
const code = finding.code === undefined ? "" : ` ${paint.bold(finding.code)}`;
|
|
367
|
+
lines.push(`${at} ${label}${code} ${finding.message}`);
|
|
368
|
+
if (finding.docs !== undefined) lines.push(paint.dim(` docs: ${finding.docs}`));
|
|
369
|
+
if (finding.fix !== undefined) lines.push(paint.dim(" fix: `barq check --fix` repairs this"));
|
|
370
|
+
lines.push("");
|
|
371
|
+
}
|
|
372
|
+
const { errors, warnings, notes, fixable, fixed } = result.summary;
|
|
373
|
+
const parts = [plural(errors, "error"), plural(warnings, "warning"), plural(notes, "note")];
|
|
374
|
+
let summary = `${parts.join(", ")} in ${plural(result.files, "file")}`;
|
|
375
|
+
if (fixed > 0) summary += `, ${fixed} fixed`;
|
|
376
|
+
if (fixable > 0) summary += `, ${fixable} more fixable with \`--fix\``;
|
|
377
|
+
lines.push(summary);
|
|
378
|
+
if (result.findings.some((finding) => finding.code !== undefined)) {
|
|
379
|
+
lines.push(paint.dim(`repair guide: ${SKILL}`));
|
|
380
|
+
}
|
|
381
|
+
return lines.join("\n");
|
|
382
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `barq`: the command line of the framework.
|
|
4
|
+
*
|
|
5
|
+
* No dependencies beyond the compiler it drives. The argument parsing is
|
|
6
|
+
* smaller than a library that would do it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { realpathSync } from "node:fs";
|
|
10
|
+
import { stdout } from "node:process";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
import { check, codes, formatText, projectOptions, type Paint } from "./check.ts";
|
|
14
|
+
|
|
15
|
+
export { applyFixes, check, codes, formatText, projectOptions } from "./check.ts";
|
|
16
|
+
export type {
|
|
17
|
+
CheckOptions,
|
|
18
|
+
CheckResult,
|
|
19
|
+
CodeEntry,
|
|
20
|
+
Edit,
|
|
21
|
+
Finding,
|
|
22
|
+
Paint,
|
|
23
|
+
Severity,
|
|
24
|
+
} from "./check.ts";
|
|
25
|
+
|
|
26
|
+
const HELP = `\
|
|
27
|
+
barq check [paths...] Report the compiler's findings for a project
|
|
28
|
+
barq codes List every code the compiler can raise
|
|
29
|
+
|
|
30
|
+
check options:
|
|
31
|
+
--json One JSON document on stdout, for a program to read
|
|
32
|
+
--fix Apply the fixes the findings carry, then report what is left
|
|
33
|
+
--root <dir> The project root (default: the current directory)
|
|
34
|
+
--routes <dir> The file routes, for checking links (default: src/routes)
|
|
35
|
+
--level <CODE=level> Set a code to suppress, note, warning or error; repeatable
|
|
36
|
+
--max-warnings <n> Exit 1 when there are more warnings than this
|
|
37
|
+
|
|
38
|
+
codes options:
|
|
39
|
+
--json The list as JSON
|
|
40
|
+
|
|
41
|
+
A project sets its own defaults under "barq": { "check": { ... } } in
|
|
42
|
+
package.json: paths, routes, extraRoutes (patterns beside the file routes) and
|
|
43
|
+
levels ({ "BARQ004": "error" }).
|
|
44
|
+
|
|
45
|
+
Exit status: 0 clean, 1 findings at error level or past --max-warnings, 2 a
|
|
46
|
+
command line this does not understand.
|
|
47
|
+
`;
|
|
48
|
+
|
|
49
|
+
const LEVELS = new Set(["suppress", "note", "warning", "error"]);
|
|
50
|
+
|
|
51
|
+
class UsageError extends Error {}
|
|
52
|
+
|
|
53
|
+
interface Parsed {
|
|
54
|
+
command: string | undefined;
|
|
55
|
+
paths: string[];
|
|
56
|
+
json: boolean;
|
|
57
|
+
fix: boolean;
|
|
58
|
+
root: string;
|
|
59
|
+
routes: string | undefined;
|
|
60
|
+
levels: [string, string][];
|
|
61
|
+
maxWarnings: number | undefined;
|
|
62
|
+
help: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function parse(argv: readonly string[]): Parsed {
|
|
66
|
+
const parsed: Parsed = {
|
|
67
|
+
command: undefined,
|
|
68
|
+
paths: [],
|
|
69
|
+
json: false,
|
|
70
|
+
fix: false,
|
|
71
|
+
root: process.cwd(),
|
|
72
|
+
routes: undefined,
|
|
73
|
+
levels: [],
|
|
74
|
+
maxWarnings: undefined,
|
|
75
|
+
help: false,
|
|
76
|
+
};
|
|
77
|
+
const value = (flag: string, index: number): string => {
|
|
78
|
+
const next = argv[index];
|
|
79
|
+
if (next === undefined || next.startsWith("--")) {
|
|
80
|
+
throw new UsageError(`\`${flag}\` takes a value, and none follows it.`);
|
|
81
|
+
}
|
|
82
|
+
return next;
|
|
83
|
+
};
|
|
84
|
+
for (let index = 0; index < argv.length; index++) {
|
|
85
|
+
const arg = argv[index] as string;
|
|
86
|
+
switch (arg) {
|
|
87
|
+
case "--help":
|
|
88
|
+
case "-h":
|
|
89
|
+
parsed.help = true;
|
|
90
|
+
break;
|
|
91
|
+
case "--json":
|
|
92
|
+
parsed.json = true;
|
|
93
|
+
break;
|
|
94
|
+
case "--fix":
|
|
95
|
+
parsed.fix = true;
|
|
96
|
+
break;
|
|
97
|
+
case "--root":
|
|
98
|
+
parsed.root = value(arg, ++index);
|
|
99
|
+
break;
|
|
100
|
+
case "--routes":
|
|
101
|
+
parsed.routes = value(arg, ++index);
|
|
102
|
+
break;
|
|
103
|
+
case "--level": {
|
|
104
|
+
const pair = value(arg, ++index);
|
|
105
|
+
const [code, level] = pair.split("=");
|
|
106
|
+
if (code === undefined || level === undefined || !LEVELS.has(level)) {
|
|
107
|
+
throw new UsageError(
|
|
108
|
+
`\`--level ${pair}\` is not \`CODE=level\`, where level is one of suppress, note, warning, error. Write it as \`--level BARQ004=error\`.`,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
parsed.levels.push([code.toUpperCase(), level]);
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
case "--max-warnings": {
|
|
115
|
+
const text = value(arg, ++index);
|
|
116
|
+
const count = Number(text);
|
|
117
|
+
if (!Number.isInteger(count) || count < 0) {
|
|
118
|
+
throw new UsageError(
|
|
119
|
+
`\`--max-warnings ${text}\` is not a whole number. Write it as \`--max-warnings 0\`.`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
parsed.maxWarnings = count;
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
default:
|
|
126
|
+
if (arg.startsWith("-")) {
|
|
127
|
+
throw new UsageError(`\`${arg}\` is not an option of barq. Run \`barq --help\`.`);
|
|
128
|
+
}
|
|
129
|
+
if (parsed.command === undefined) parsed.command = arg;
|
|
130
|
+
else parsed.paths.push(arg);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return parsed;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function painter(): Paint {
|
|
137
|
+
const styled = stdout.isTTY && process.env["NO_COLOR"] === undefined;
|
|
138
|
+
const code =
|
|
139
|
+
(open: string) =>
|
|
140
|
+
(text: string): string =>
|
|
141
|
+
styled ? `\u001B[${open}m${text}\u001B[0m` : text;
|
|
142
|
+
return {
|
|
143
|
+
error: code("31"),
|
|
144
|
+
warning: code("33"),
|
|
145
|
+
note: code("36"),
|
|
146
|
+
dim: code("2"),
|
|
147
|
+
bold: code("1"),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Run one command line and answer with the exit status. */
|
|
152
|
+
export function main(argv: readonly string[], write: (text: string) => void): number {
|
|
153
|
+
let parsed: Parsed;
|
|
154
|
+
try {
|
|
155
|
+
parsed = parse(argv);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (!(error instanceof UsageError)) throw error;
|
|
158
|
+
write(`${error.message}\n`);
|
|
159
|
+
return 2;
|
|
160
|
+
}
|
|
161
|
+
if (parsed.help || parsed.command === undefined) {
|
|
162
|
+
write(HELP);
|
|
163
|
+
return parsed.help ? 0 : 2;
|
|
164
|
+
}
|
|
165
|
+
switch (parsed.command) {
|
|
166
|
+
case "check": {
|
|
167
|
+
const set = projectOptions(parsed.root);
|
|
168
|
+
const result = check({
|
|
169
|
+
...set,
|
|
170
|
+
root: parsed.root,
|
|
171
|
+
fix: parsed.fix,
|
|
172
|
+
// A level on the command line is added after the project's, and the
|
|
173
|
+
// compiler takes the last one named for a code.
|
|
174
|
+
levels: [...(set.levels ?? []), ...parsed.levels],
|
|
175
|
+
...(parsed.paths.length > 0 ? { paths: parsed.paths } : {}),
|
|
176
|
+
...(parsed.routes !== undefined ? { routes: parsed.routes } : {}),
|
|
177
|
+
});
|
|
178
|
+
write(
|
|
179
|
+
parsed.json ? `${JSON.stringify(result, null, 2)}\n` : `${formatText(result, painter())}\n`,
|
|
180
|
+
);
|
|
181
|
+
const { errors, warnings } = result.summary;
|
|
182
|
+
const over = parsed.maxWarnings !== undefined && warnings > parsed.maxWarnings;
|
|
183
|
+
return errors > 0 || over ? 1 : 0;
|
|
184
|
+
}
|
|
185
|
+
case "codes": {
|
|
186
|
+
const list = codes();
|
|
187
|
+
write(
|
|
188
|
+
parsed.json
|
|
189
|
+
? `${JSON.stringify(list, null, 2)}\n`
|
|
190
|
+
: `${list.map((entry) => `${entry.code} ${entry.level.padEnd(7)} ${entry.summary}`).join("\n")}\n`,
|
|
191
|
+
);
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
default:
|
|
195
|
+
write(`\`${parsed.command}\` is not a command of barq. Run \`barq --help\`.\n`);
|
|
196
|
+
return 2;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The guard compares the script node was asked to run with this module rather
|
|
202
|
+
* than reading `import.meta.main`, which node defines only from 24.2. `argv[1]`
|
|
203
|
+
* is the `.bin` symlink under a package manager, hence the realpath.
|
|
204
|
+
*/
|
|
205
|
+
function invokedDirectly(): boolean {
|
|
206
|
+
const script = process.argv[1];
|
|
207
|
+
return script !== undefined && realpathSync(script) === fileURLToPath(import.meta.url);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (invokedDirectly()) {
|
|
211
|
+
process.exitCode = main(process.argv.slice(2), (text) => stdout.write(text));
|
|
212
|
+
}
|