@emberbox/lint 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RainbowDashLabs and Contributor
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,78 @@
1
- # Temporary Holding Version
1
+ # @emberbox/lint
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared linters of the [Emberbox](https://emberbox.app) tools: an ESLint flat config with the
4
+ Emberbox rules, and `emberbox-lint`, which runs ESLint together with the linters ESLint does not
5
+ cover.
6
+
7
+ ```sh
8
+ npm install --save-dev @emberbox/lint eslint
9
+ ```
10
+
11
+ ## ESLint
12
+
13
+ ```js
14
+ // eslint.config.mjs
15
+ import {emberboxEslint} from '@emberbox/lint'
16
+
17
+ export default await emberboxEslint({
18
+ catalogue: 'src/i18n/de.ts',
19
+ layers: [{layer: 'model', above: ['views', 'components']}],
20
+ })
21
+ ```
22
+
23
+ The config brings Vue, TypeScript and accessibility as recommended and the Emberbox conventions:
24
+ script, template and style in that order, self-closing empty elements, no `v-html`, no leftover
25
+ `console.log`, named state types, functions of at most 79 lines, and for templates outside
26
+ `components/` no class pattern repeated across the views and no oversized template blocks. Undefined
27
+ names in TypeScript and Vue files are left to the type checker (`vue-tsc` or `tsc`), which knows
28
+ auto-imported names such as Nuxt UI's composables; run it alongside, since ESLint does not report
29
+ them there. JavaScript files are still checked by `no-undef`.
30
+
31
+ | Option | Default | Meaning |
32
+ |---|---|---|
33
+ | `src` | `src` | the source directory |
34
+ | `catalogue` | none | the German vue-i18n catalogue; with it every template text goes through the catalogue, and the catalogue is checked for missing, unused and plural messages (plural messages unless `plurals` is set) |
35
+ | `plurals` | `false` | allow vue-i18n plural messages such as `{n} Alarm \| {n} Alarme`; without it a bare `\|` in the catalogue is an error, since it usually wanted escaping |
36
+ | `layers` | `[]` | which source directories may not import from which |
37
+ | `maxFunctionLines` | `79` | the longest function allowed |
38
+ | `ignores`, `nodeFiles` | `[]` | further files to skip, or that run in Node |
39
+ | `cwd` | working directory | where ESLint runs |
40
+
41
+ The rules alone are available as the plugin `@emberbox/lint/plugin`, prefix `emberbox`.
42
+
43
+ ## emberbox-lint
44
+
45
+ `emberbox-lint` reads `emberbox-lint.config.mjs` in the working directory (the frontend, where
46
+ ESLint runs) and runs ESLint, jscpd, the browser storage check, the em dash check and the comment
47
+ check. It fails when any of them fails, after all have run. `emberbox-lint <name>` runs one of
48
+ them, `emberbox-lint --audit` runs all without failing.
49
+
50
+ ```js
51
+ // emberbox-lint.config.mjs
52
+ export default {
53
+ root: '..',
54
+ sources: [
55
+ {path: 'frontend/src', extensions: ['.ts', '.vue']},
56
+ {path: 'backend/src', extensions: ['.py']},
57
+ ],
58
+ text: [{path: 'README.md', extensions: null}],
59
+ browserStorage: {catalogue: 'frontend/browser-storage.json', sources: 'frontend/src'},
60
+ duplication: '.jscpd.json',
61
+ }
62
+ ```
63
+
64
+ - `root`: the repository root, relative to the working directory. Every path except `duplication`
65
+ is relative to it.
66
+ - `sources`: what the comment and the em dash check read. Only doc comments and one-line `TODO`s are
67
+ allowed, in TypeScript, Vue, JavaScript and Python.
68
+ - `text`: further files only the em dash check reads.
69
+ - `browserStorage`: a catalogue of every `localStorage` and `sessionStorage` key with its purpose;
70
+ every key the code uses must be declared, every declared key used. A key a dependency stores, such
71
+ as `@emberbox/ui`'s colour mode `vueuse-color-scheme`, is declared with `"source": "@emberbox/ui"`; it is
72
+ listed for completeness and not expected in the project's own code. Entries with a `source` are not
73
+ checked against the dependency, so remove one when the dependency stops storing its key.
74
+ - `duplication`: a jscpd config file, relative to the working directory.
75
+
76
+ ## License
77
+
78
+ MIT
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@emberbox/lint",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Shared linters of the Emberbox tools: an ESLint config with the Emberbox rules and the emberbox-lint runner.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ember-tools/emberbox.git",
10
+ "directory": "packages/lint"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "exports": {
16
+ ".": "./src/eslint.mjs",
17
+ "./plugin": "./src/plugin.mjs"
18
+ },
19
+ "bin": {
20
+ "emberbox-lint": "./src/cli/main.mjs"
21
+ },
22
+ "scripts": {
23
+ "test": "vitest run"
24
+ },
25
+ "dependencies": {
26
+ "@eslint/js": "^10.0.1",
27
+ "@intlify/eslint-plugin-vue-i18n": "^4.5.1",
28
+ "@intlify/message-compiler": "^11.4.23",
29
+ "@typescript-eslint/parser": "^8.73.0",
30
+ "eslint-plugin-import-x": "^4.18.1",
31
+ "eslint-plugin-vue": "^10.12.1",
32
+ "eslint-plugin-vuejs-accessibility": "^2.6.3",
33
+ "globals": "^17.14.0",
34
+ "jiti": "^2.7.0",
35
+ "jscpd": "^5.4.3",
36
+ "jsonc-eslint-parser": "^3.3.0",
37
+ "typescript-eslint": "^8.73.0",
38
+ "vue-eslint-parser": "^10.4.2"
39
+ },
40
+ "peerDependencies": {
41
+ "eslint": "^10.15.0"
42
+ },
43
+ "devDependencies": {
44
+ "eslint": "^10.15.0",
45
+ "vitest": "^5.1.1"
46
+ }
47
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The check of a browser storage catalogue against the code that reads and writes the browser's
3
+ * storage.
4
+ *
5
+ * The catalogue (`browser-storage.json` by convention) lists every value the application keeps in the browser, each with what it
6
+ * holds and why. A key added to the code without an entry would be stored without anybody having
7
+ * written down why, so every key the frontend reads or writes must be declared, and every declared
8
+ * key must still be used.
9
+ *
10
+ * Keys are collected from `localStorage` and `sessionStorage` calls to `getItem`, `setItem` and
11
+ * `removeItem`. A key held in a constant of the same file resolves to its literal; any other
12
+ * argument is reported as one that cannot be checked.
13
+ */
14
+
15
+ import {readFileSync} from 'node:fs'
16
+ import {join} from 'node:path'
17
+ import {createReporter, walk} from './lint-utils.mjs'
18
+
19
+ const STORAGE_CALL = /\b(?:localStorage|sessionStorage)\??\.(?:getItem|setItem|removeItem)\(\s*([^,)]+)/g
20
+
21
+ /**
22
+ * The `const NAME = 'value'` bindings of a file, so a key held in a constant resolves.
23
+ *
24
+ * @param content the file's source
25
+ * @returns the constants by name
26
+ */
27
+ function constantsIn(content) {
28
+ return new Map([...content.matchAll(/const\s+([A-Za-z_$][\w$]*)\s*=\s*'([^']*)'/g)].map(match => [match[1], match[2]]))
29
+ }
30
+
31
+ /**
32
+ * The storage keys a file uses, and the arguments that are not literals.
33
+ *
34
+ * @param content the file's source
35
+ * @returns the keys and the unresolved arguments
36
+ */
37
+ function keysIn(content) {
38
+ const constants = constantsIn(content)
39
+ const keys = new Set()
40
+ const dynamic = []
41
+ for (const match of content.matchAll(STORAGE_CALL)) {
42
+ const argument = match[1].trim()
43
+ const literal = argument.match(/^'([^']*)'$/)
44
+ if (literal) keys.add(literal[1])
45
+ else if (constants.has(argument)) keys.add(constants.get(argument))
46
+ else dynamic.push(argument)
47
+ }
48
+ return {keys, dynamic}
49
+ }
50
+
51
+ /**
52
+ * Compares the keys the code uses with the catalogue: every used key must be declared, every
53
+ * declared key used, and every key a literal or a constant of the same file. An entry with a
54
+ * `source`, the package that stores the key on the project's behalf (such as `@emberbox/ui` for the
55
+ * colour mode), is declared so the catalogue is complete, and is not expected in the project's code.
56
+ *
57
+ * @param root the absolute repository root
58
+ * @param options `catalogue`, the catalogue file, and `sources`, the source folder, both relative to the root
59
+ * @returns whether the catalogue and the code agree
60
+ */
61
+ export function checkBrowserStorage(root, {catalogue, sources}) {
62
+ const reporter = createReporter(root)
63
+ const catalog = JSON.parse(readFileSync(join(root, catalogue), 'utf-8'))
64
+ const entries = catalog.entries ?? []
65
+ const declared = new Set(entries.map(entry => entry.key))
66
+ const fromDependencies = new Set(entries.filter(entry => entry.source).map(entry => entry.key))
67
+ const used = new Map()
68
+ const folder = join(root, sources)
69
+ for (const file of [...walk(folder, '.ts'), ...walk(folder, '.vue')]) {
70
+ if (file.endsWith('.test.ts')) continue
71
+ const {keys, dynamic} = keysIn(readFileSync(file, 'utf-8'))
72
+ for (const key of keys) if (!used.has(key)) used.set(key, file)
73
+ for (const argument of dynamic) {
74
+ reporter.error(file, 0, `storage key is not a literal (${argument}), so it cannot be checked against ${catalogue}`, 'dynamic')
75
+ }
76
+ }
77
+ for (const [key, file] of used) {
78
+ if (!declared.has(key)) reporter.error(file, 0, `browser storage key '${key}' is not declared in ${catalogue}`, 'undeclared')
79
+ }
80
+ for (const key of fromDependencies) {
81
+ if (used.has(key)) reporter.error(catalogue, 0, `browser storage key '${key}' is used by this project's own code, so it must not name a source`, 'source')
82
+ }
83
+ for (const key of declared) {
84
+ if (!used.has(key) && !fromDependencies.has(key)) reporter.error(catalogue, 0, `declared browser storage key '${key}' is no longer used`, 'stale')
85
+ }
86
+ return reporter.finish(`Browser storage lint passed. ${used.size} keys used, ${declared.size} declared in ${catalogue}.`)
87
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Finds the comments of a source file that are neither doc comments nor TODO markers.
3
+ *
4
+ * <p>Python and the script languages are read in one pass over their characters, which is the only
5
+ * way to tell a comment from the same characters inside a string: an address in a string, a
6
+ * protocol in a template literal and a `#` inside a docstring all look like a comment otherwise.
7
+ */
8
+
9
+ const TODO = /^(\/\/|\/\*|#)\s*TODO\b/
10
+ const TEMPLATE_COMMENT = '<!--'
11
+
12
+ const LINE_MESSAGE = 'Only doc comments and TODO markers are allowed; put the reasoning in the doc comment of the'
13
+ + ' enclosing class or function.'
14
+
15
+ /**
16
+ * The comments of a Python file that are not a docstring, a shebang or a TODO.
17
+ *
18
+ * @param text the file's source
19
+ * @returns the findings, each with its line and message
20
+ */
21
+ export function pythonFindings(text) {
22
+ const found = []
23
+ let line = 1
24
+ let quote = null
25
+ for (let i = 0; i < text.length; i++) {
26
+ const c = text[i]
27
+ if (c === '\n') {
28
+ line++
29
+ if (quote?.length === 1) quote = null
30
+ continue
31
+ }
32
+ if (quote) {
33
+ if (c === '\\') {
34
+ if (text[i + 1] === '\n') line++
35
+ i++
36
+ } else if (text.startsWith(quote, i)) {
37
+ i += quote.length - 1
38
+ quote = null
39
+ }
40
+ continue
41
+ }
42
+ if (c === '"' || c === "'") {
43
+ const triple = c.repeat(3)
44
+ quote = text.startsWith(triple, i) ? triple : c
45
+ i += quote.length - 1
46
+ continue
47
+ }
48
+ if (c !== '#') continue
49
+ const end = endOfLine(text, i)
50
+ const comment = text.slice(i, end)
51
+ const shebang = line === 1 && i === 0 && comment.startsWith('#!')
52
+ if (!shebang && !TODO.test(comment)) {
53
+ found.push({line, message: `Comment at column ${i - text.lastIndexOf('\n', i - 1)}. ${LINE_MESSAGE}`})
54
+ }
55
+ i = end - 1
56
+ }
57
+ return found
58
+ }
59
+
60
+ /**
61
+ * The comments of a script or a single file component that are not doc comments or TODOs. In a
62
+ * component the template is markup, where every comment is reported, and the script is code.
63
+ *
64
+ * @param text the file's source
65
+ * @param markup whether the file is a single file component
66
+ * @returns the findings, each with its line and message
67
+ */
68
+ export function scriptFindings(text, markup) {
69
+ const found = []
70
+ let line = 1
71
+ let quote = null
72
+ let inCode = !markup
73
+ let operandExpected = true
74
+ for (let i = 0; i < text.length; i++) {
75
+ const c = text[i]
76
+ if (c === '\n') {
77
+ line++
78
+ if (quote && quote !== '`') quote = null
79
+ continue
80
+ }
81
+ if (markup && atLineStart(text, i)) {
82
+ const tag = text.slice(i).match(/^\s*<(\/?)(script|style)\b/)
83
+ if (tag) {
84
+ inCode = tag[1] === ''
85
+ i = endOfLine(text, i) - 1
86
+ continue
87
+ }
88
+ }
89
+ if (!inCode) {
90
+ if (text.startsWith(TEMPLATE_COMMENT, i)) {
91
+ found.push({line, message: 'Template comment. Name the block with a component or a class instead.'})
92
+ const end = text.indexOf('-->', i)
93
+ const stop = end === -1 ? text.length : end + 3
94
+ line += countLines(text, i, stop)
95
+ i = stop - 1
96
+ }
97
+ continue
98
+ }
99
+ if (quote) {
100
+ if (c === '\\') {
101
+ if (text[i + 1] === '\n') line++
102
+ i++
103
+ } else if (c === quote) quote = null
104
+ continue
105
+ }
106
+ if (c === '"' || c === "'" || c === '`') {
107
+ quote = c
108
+ operandExpected = false
109
+ continue
110
+ }
111
+ if (c === '/' && operandExpected && text[i + 1] !== '/' && text[i + 1] !== '*') {
112
+ i = endOfRegex(text, i) - 1
113
+ operandExpected = false
114
+ continue
115
+ }
116
+ if (c === '#' && i === 0 && text[1] === '!') {
117
+ i = endOfLine(text, i) - 1
118
+ continue
119
+ }
120
+ if (text.startsWith('/*', i)) {
121
+ const end = text.indexOf('*/', i + 2)
122
+ const stop = end === -1 ? text.length : end + 2
123
+ const block = text.slice(i, stop)
124
+ if (!block.startsWith('/**') && !TODO.test(block)) {
125
+ found.push({line, message: 'Block comment that is not a doc comment. Put the reasoning in the doc comment of'
126
+ + ' the class or function it belongs to, or rewrite the passage so it needs none.'})
127
+ }
128
+ line += countLines(text, i, stop)
129
+ i = stop - 1
130
+ continue
131
+ }
132
+ if (text.startsWith('//', i)) {
133
+ const end = endOfLine(text, i)
134
+ if (!TODO.test(text.slice(i, end))) {
135
+ found.push({line, message: `Line comment at column ${i - text.lastIndexOf('\n', i - 1)}. ${LINE_MESSAGE}`})
136
+ }
137
+ i = end - 1
138
+ continue
139
+ }
140
+ if (/\s/.test(c)) continue
141
+ operandExpected = OPERAND_BEFORE.has(c) || precedingKeyword(text, i)
142
+ }
143
+ return found
144
+ }
145
+
146
+ /** The characters after which a `/` starts a regular expression rather than dividing. */
147
+ const OPERAND_BEFORE = new Set(['(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '<', '>', '~', '^'])
148
+
149
+ /** The keywords after which a `/` starts a regular expression. */
150
+ const KEYWORDS_BEFORE_OPERAND = /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|void|throw|delete|new|yield|await)$/
151
+
152
+ /**
153
+ * Whether the word ending at a position is a keyword after which an operand follows.
154
+ *
155
+ * @param text the source
156
+ * @param at the position of the word's last character
157
+ * @returns true after such a keyword
158
+ */
159
+ function precedingKeyword(text, at) {
160
+ if (!/[\w$]/.test(text[at])) return false
161
+ return KEYWORDS_BEFORE_OPERAND.test(text.slice(Math.max(0, at - 10), at + 1)) && !/[\w$]/.test(text[at + 1] ?? '')
162
+ }
163
+
164
+ /**
165
+ * Where a regular expression literal starting at a position ends, its flags included; a literal
166
+ * left open ends with its line.
167
+ *
168
+ * @param text the source
169
+ * @param start the position of the opening slash
170
+ * @returns the index after the literal
171
+ */
172
+ function endOfRegex(text, start) {
173
+ let inClass = false
174
+ for (let i = start + 1; i < text.length; i++) {
175
+ const c = text[i]
176
+ if (c === '\n') return i
177
+ if (c === '\\') i++
178
+ else if (c === '[') inClass = true
179
+ else if (c === ']') inClass = false
180
+ else if (c === '/' && !inClass) {
181
+ let end = i + 1
182
+ while (end < text.length && /[a-z]/i.test(text[end])) end++
183
+ return end
184
+ }
185
+ }
186
+ return text.length
187
+ }
188
+
189
+ /**
190
+ * Where the line holding a position ends.
191
+ *
192
+ * @param text the source
193
+ * @param from the position
194
+ * @returns the index of the line break, or the length of the text
195
+ */
196
+ function endOfLine(text, from) {
197
+ const end = text.indexOf('\n', from)
198
+ return end === -1 ? text.length : end
199
+ }
200
+
201
+ /**
202
+ * Whether a position is the first character of its line.
203
+ *
204
+ * @param text the source
205
+ * @param at the position
206
+ * @returns true at the start of a line
207
+ */
208
+ function atLineStart(text, at) {
209
+ return at === 0 || text[at - 1] === '\n'
210
+ }
211
+
212
+ /**
213
+ * How many line breaks lie in a span.
214
+ *
215
+ * @param text the source
216
+ * @param from where the span starts
217
+ * @param to where it ends
218
+ * @returns the number of line breaks
219
+ */
220
+ function countLines(text, from, to) {
221
+ let count = 0
222
+ for (let i = from; i < to; i++) if (text[i] === '\n') count++
223
+ return count
224
+ }
@@ -0,0 +1,28 @@
1
+ import {readFileSync} from 'node:fs'
2
+ import {pythonFindings, scriptFindings} from './comment-scan.mjs'
3
+ import {createReporter, targetFiles} from './lint-utils.mjs'
4
+
5
+ /**
6
+ * Finds every comment that is neither a doc comment nor a TODO.
7
+ *
8
+ * <p>Code documents itself in the Emberbox projects. Clear names, small functions and honest
9
+ * structure carry the meaning, and a passage that needs a comment beside it to be understood wants
10
+ * rewriting rather than annotating. So only doc comments are allowed: the block that introduces a
11
+ * class, a method, a function or a constant and says what it is for, which is a docstring in
12
+ * Python. The one exception is a TODO marking a real gap. Shell scripts are not scanned, since
13
+ * their header and the doc lines above their functions are the shell's doc comments.
14
+ *
15
+ * @param root the absolute repository root
16
+ * @param sources the `{path, extensions}` targets to scan
17
+ * @returns whether nothing was found
18
+ */
19
+ export function checkComments(root, sources) {
20
+ const reporter = createReporter(root)
21
+ const files = targetFiles(root, sources)
22
+ for (const file of files) {
23
+ const text = readFileSync(file, 'utf-8')
24
+ const found = file.endsWith('.py') ? pythonFindings(text) : scriptFindings(text, file.endsWith('.vue'))
25
+ for (const one of found) reporter.error(file, one.line, one.message)
26
+ }
27
+ return reporter.finish(`Comment lint passed. ${files.length} files checked.`)
28
+ }
@@ -0,0 +1,33 @@
1
+ import {readFileSync} from 'node:fs'
2
+ import {createReporter, targetFiles} from './lint-utils.mjs'
3
+
4
+ /** Built from its code point so this file does not trip over itself. */
5
+ const EM_DASH = String.fromCharCode(0x2014)
6
+
7
+ /** The names markup gives the same character, assembled here for the same reason. */
8
+ const ENTITIES = ['mdash', '#8212', '#x2014', '#X2014'].map(name => `&${name};`)
9
+
10
+ const SPELLINGS = [EM_DASH, ...ENTITIES]
11
+
12
+ /**
13
+ * Finds the em dash, which the Emberbox projects keep out of their code and the text they ship, so
14
+ * the interface reads the same everywhere. The first one on each line is reported.
15
+ *
16
+ * @param root the absolute repository root
17
+ * @param targets the `{path, extensions}` targets to scan
18
+ * @returns whether none was found
19
+ */
20
+ export function checkEmDash(root, targets) {
21
+ const reporter = createReporter(root)
22
+ const files = targetFiles(root, targets)
23
+ for (const file of files) {
24
+ const lines = readFileSync(file, 'utf-8').split('\n')
25
+ lines.forEach((line, index) => {
26
+ const spelling = SPELLINGS.find(candidate => line.includes(candidate))
27
+ if (!spelling) return
28
+ reporter.error(file, index + 1,
29
+ `Em dash at column ${line.indexOf(spelling) + 1}. Use a comma, a colon, parentheses, a full stop or a spaced hyphen instead.`)
30
+ })
31
+ }
32
+ return reporter.finish(`Em dash lint passed. ${files.length} files carry none.`)
33
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Shared utilities for the script linters: a file walker and a reporter that groups and prints what
3
+ * the linters find. Every path a linter is given is relative to the repository root.
4
+ */
5
+
6
+ import {existsSync, readdirSync} from 'node:fs'
7
+ import {join, relative} from 'node:path'
8
+
9
+ const RED = '\x1b[31m'
10
+ const GREEN = '\x1b[32m'
11
+ const RESET = '\x1b[0m'
12
+ const BOLD = '\x1b[1m'
13
+
14
+ /** Folders no linter looks into: dependencies, builds and caches. */
15
+ const SKIPPED_DIRS = new Set(['node_modules', 'frontend_dist', 'dist', '__pycache__', '.venv', '.git'])
16
+
17
+ /**
18
+ * Every file below a folder whose name ends in the extension.
19
+ *
20
+ * @param dir the folder, which may be missing
21
+ * @param ext the extension, with its dot
22
+ * @returns the absolute paths
23
+ */
24
+ export function walk(dir, ext) {
25
+ if (!existsSync(dir)) return []
26
+ const results = []
27
+ for (const entry of readdirSync(dir, {withFileTypes: true})) {
28
+ const full = join(dir, entry.name)
29
+ if (entry.isDirectory()) {
30
+ if (!SKIPPED_DIRS.has(entry.name)) results.push(...walk(full, ext))
31
+ } else if (entry.name.endsWith(ext)) {
32
+ results.push(full)
33
+ }
34
+ }
35
+ return results
36
+ }
37
+
38
+ /**
39
+ * Every file of the given targets, each a folder or a file relative to the repository root.
40
+ *
41
+ * @param root the absolute repository root
42
+ * @param targets `{path, extensions}` entries; `extensions` is null for a single file
43
+ * @returns the absolute paths of the files that exist
44
+ */
45
+ export function targetFiles(root, targets) {
46
+ return targets.flatMap(target => {
47
+ const absolute = join(root, target.path)
48
+ if (!target.extensions) return existsSync(absolute) ? [absolute] : []
49
+ return target.extensions.flatMap(extension => walk(absolute, extension))
50
+ })
51
+ }
52
+
53
+ /**
54
+ * A collector for errors that prints them grouped by category.
55
+ *
56
+ * @param root the absolute repository root, which file names in messages are relative to
57
+ * @returns the reporter
58
+ */
59
+ export function createReporter(root) {
60
+ const errors = []
61
+ const entry = (file, line, msg, category) => ({file: typeof file === 'string' && file.startsWith('/') ? relative(root, file) : file, line, msg, category})
62
+
63
+ return {
64
+ error(file, line, msg, category = '') {
65
+ errors.push(entry(file, line, msg, category))
66
+ },
67
+ get errors() { return errors },
68
+
69
+ /**
70
+ * Prints the errors, or the message of a passed check when there are none.
71
+ *
72
+ * @param passed what a passed check says
73
+ * @returns whether the check passed
74
+ */
75
+ finish(passed) {
76
+ if (errors.length === 0) {
77
+ console.log(`${GREEN}${BOLD}${passed}${RESET}`)
78
+ return true
79
+ }
80
+ printGroup(errors, RED, 'Errors')
81
+ return false
82
+ },
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Prints one group of findings, split by category when there is more than one.
88
+ *
89
+ * @param items the findings
90
+ * @param color the colour of the label
91
+ * @param label the group's name
92
+ */
93
+ function printGroup(items, color, label) {
94
+ if (items.length === 0) return
95
+ console.log(`\n${color}${BOLD}${label} (${items.length}):${RESET}`)
96
+ const groups = Map.groupBy(items, item => item.category || 'Other')
97
+ for (const [category, entries] of groups) {
98
+ if (groups.size > 1) console.log(`\n ${BOLD}${category}${RESET}`)
99
+ for (const e of entries) {
100
+ const loc = e.line > 0 ? `:${e.line}` : ''
101
+ console.log(` ${color}${label.toLowerCase().slice(0, -1)}${RESET} ${e.file}${loc}: ${e.msg}`)
102
+ }
103
+ }
104
+ }