@nera-static/stan 1.0.1 → 1.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +147 -15
  3. package/canonical/editorconfig +12 -0
  4. package/canonical/github/FUNDING.yml +13 -0
  5. package/canonical/github/dependabot.yml +20 -0
  6. package/canonical/github/workflows/publish.yml +64 -0
  7. package/canonical/github/workflows/test.yml +37 -0
  8. package/canonical/husky/pre-push +1 -0
  9. package/canonical/variants/chokidar-major/github/dependabot.yml +25 -0
  10. package/canonical/variants/desktop-release/github/workflows/publish.yml +104 -0
  11. package/canonical/variants/dist-check/github/workflows/test.yml +43 -0
  12. package/canonical/variants/image-cache/github/workflows/publish.yml +73 -0
  13. package/canonical/variants/image-cache/github/workflows/test.yml +46 -0
  14. package/canonical/variants/validate-templates/github/workflows/publish.yml +64 -0
  15. package/canonical/variants/validate-templates/github/workflows/test.yml +40 -0
  16. package/canonical/variants/windows-smoke/github/workflows/test.yml +57 -0
  17. package/canonical/vitest.config.js +3 -0
  18. package/package.json +24 -12
  19. package/src/bem.js +35 -0
  20. package/src/checks/canonical.js +368 -0
  21. package/src/checks/css.js +131 -0
  22. package/src/checks/docs.js +405 -0
  23. package/src/checks/package.js +352 -0
  24. package/src/checks/pug.js +369 -0
  25. package/src/checks/tree.js +544 -0
  26. package/src/cli.js +49 -39
  27. package/src/eslint/check.js +64 -0
  28. package/src/eslint/config.js +45 -28
  29. package/src/eslint/files.js +37 -0
  30. package/src/markdown.js +60 -0
  31. package/src/repo-files.js +62 -1
  32. package/src/settings.js +136 -0
  33. package/src/stylelint/config.js +122 -0
  34. package/src/stylelint/index.js +15 -0
@@ -0,0 +1,544 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ import { isPluginPackage } from '@nera-static/plugin-utils/packages'
6
+ import { isPlainObject, isText } from '@nera-static/plugin-utils/values'
7
+ import * as espree from 'espree'
8
+
9
+ import { kindOf } from '../kind.js'
10
+ import { headings } from '../markdown.js'
11
+ import { entryFile, isDirectory, isPublished, normalize, publishedPatterns } from '../repo-files.js'
12
+ import { HOOKS } from '../rules/hook-shape.js'
13
+ import { STRUCTURE_PREFIX, keyLines } from './package.js'
14
+
15
+ /** The rule ids the tree check reports, one per repo kind. */
16
+ export const TREE_RULES = Object.freeze({
17
+ plugin: `${STRUCTURE_PREFIX}plugin-tree`,
18
+ theme: `${STRUCTURE_PREFIX}theme-tree`,
19
+ starter: `${STRUCTURE_PREFIX}starter-tree`,
20
+ })
21
+
22
+ /** The one bin a plugin with `views/` ships (2-plugin-anatomy §4.1). */
23
+ export const PUBLISH_TEMPLATE = 'bin/publish-template.js'
24
+
25
+ /** The layout every theme ships (4-tooling-themes §2.1). */
26
+ export const THEME_LAYOUT = 'views/layouts/layout.pug'
27
+
28
+ /**
29
+ * The seams every contract theme ships under `views/partials/`: the ones blog, business,
30
+ * stack, ansitz and umwege all have (4-tooling-themes §2.1). The blog seams (`post-media`,
31
+ * `tag-cloud`, …) and business's (`hero-media`, `contact-form`) belong to one contract each.
32
+ */
33
+ export const THEME_SEAMS = Object.freeze(['head-extra', 'scripts-extra', 'footer-extra', 'nav-main'])
34
+
35
+ /**
36
+ * What `nera new --starter` copies from a starter (`STARTER_ENTRIES` in nera-cli's
37
+ * `src/starter.js`); with `CHANGELOG.md` the only entries a starter's `files` may hold.
38
+ */
39
+ export const STARTER_ENTRIES = Object.freeze(['pages', 'config', 'theme', 'assets', 'plugins', '.neraignore'])
40
+
41
+ /** The H2 that closes a starter's README: the CLI prints the section after `nera new`. */
42
+ export const FIRST_STEPS = '## First steps'
43
+
44
+ const PLUGIN_PREFIX = '@nera-static/plugin-'
45
+ const SCOPE = /^@[^/]+\//
46
+ const THEME_PREFIX = /^theme-/
47
+ const CHANGELOG = 'CHANGELOG.md'
48
+ const README = 'README.md'
49
+ const FONT_FACE = /@font-face\s*\{([^}]*)\}/g
50
+ const CSS_URL = /url\(\s*(['"]?)([^'")]+)\1\s*\)/g
51
+ const CSS_COMMENT = /\/\*[\s\S]*?\*\//g
52
+ const REMOTE_URL = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
53
+ const LICENCE_FILE = /^(?:OFL|LICEN[CS]E|COPYING)/i
54
+ const SKIPPED_DIRS = new Set(['node_modules', '.git'])
55
+
56
+ /**
57
+ * The tree check: what a plugin, theme or starter repo must hold beyond its `package.json`
58
+ * keys. Other repo kinds get no finding. Nothing is fixed: each finding needs a file written
59
+ * or moved by hand. The copied-plugin-file part of the starter rule reads the checked repo's
60
+ * `node_modules`; without an install it finds nothing to compare against.
61
+ */
62
+ export const treeCheck = Object.freeze({
63
+ name: 'tree',
64
+
65
+ /**
66
+ * Every rule id this check can report.
67
+ *
68
+ * @returns {string[]}
69
+ */
70
+ rules() {
71
+ return Object.values(TREE_RULES)
72
+ },
73
+
74
+ /**
75
+ * Check the repo's tree for its kind.
76
+ *
77
+ * @param {{ root: string, pkg: object }} context
78
+ * @returns {{ findings: { file: string, line: number, rule: string, message: string,
79
+ * fixable: boolean }[] }}
80
+ */
81
+ run({ root, pkg }) {
82
+ const check = TREES[kindOf(pkg)]
83
+ const findings = check ? check(root, pkg, packageLines(root)) : []
84
+ return { findings: findings.map((finding) => ({ ...finding, fixable: false })) }
85
+ },
86
+ })
87
+
88
+ const TREES = Object.freeze({ plugin: pluginTree, theme: themeTree, starter: starterTree })
89
+
90
+ /**
91
+ * `structure/plugin-tree`: the entry exports hooks only, `src/` exists, `config/<name>.yaml`
92
+ * exists and is published, `bin/publish-template.js` exists iff `views/` does and is the
93
+ * only bin, named `nera-<name>`.
94
+ */
95
+ function pluginTree(root, pkg, lineOf) {
96
+ const rule = TREE_RULES.plugin
97
+ const name = pkg.name.slice(PLUGIN_PREFIX.length)
98
+ const findings = [...entryExports(root, entryFile(pkg), rule)]
99
+
100
+ if (!isDirectory(root, 'src')) {
101
+ findings.push({
102
+ file: 'src',
103
+ line: 1,
104
+ rule,
105
+ message: 'the folder "src/" is missing: move every function but the hooks out of the entry into ' +
106
+ 'one module per concern under src/ (e.g. src/config.js)',
107
+ })
108
+ }
109
+
110
+ const config = `config/${name}.yaml`
111
+ if (!existsSync(path.join(root, config))) {
112
+ findings.push({
113
+ file: config,
114
+ line: 1,
115
+ rule,
116
+ message: `"${config}" is missing: ship every config key with its default (or commented) there, ` +
117
+ 'since nera add copies it into the site',
118
+ })
119
+ } else if (!isPublished(publishedPatterns(pkg), config)) {
120
+ findings.push({
121
+ file: 'package.json',
122
+ line: lineOf('files'),
123
+ rule,
124
+ message: `"files" does not ship "${config}": add "config" to "files"`,
125
+ })
126
+ }
127
+
128
+ findings.push(...pluginBins(root, pkg, name, lineOf))
129
+ return findings
130
+ }
131
+
132
+ function entryExports(root, entry, rule) {
133
+ const file = path.join(root, entry)
134
+ if (!existsSync(file)) {
135
+ return [{
136
+ file: entry,
137
+ line: 1,
138
+ rule,
139
+ message: `the entry "${entry}" is missing: create it with the plugin's hooks (${HOOKS.join(', ')})`,
140
+ }]
141
+ }
142
+
143
+ let ast
144
+ try {
145
+ ast = espree.parse(readFileSync(file, 'utf8'), { ecmaVersion: 'latest', sourceType: 'module', loc: true })
146
+ } catch {
147
+ // The code check reports the parse error.
148
+ return []
149
+ }
150
+ return ast.body.flatMap(exportedNames)
151
+ .filter(({ name }) => !HOOKS.includes(name))
152
+ .map(({ name, line }) => ({
153
+ file: entry,
154
+ line,
155
+ rule,
156
+ message: `the entry exports "${name}", but a plugin entry exports only its hooks ` +
157
+ `(${HOOKS.join(', ')}): move "${name}" into a module under src/ and import it from there`,
158
+ }))
159
+ }
160
+
161
+ /** The names one top-level statement exports, each with its line. */
162
+ function exportedNames(node) {
163
+ const line = node.loc.start.line
164
+ if (node.type === 'ExportDefaultDeclaration') {
165
+ return [{ name: 'default', line }]
166
+ }
167
+ if (node.type === 'ExportAllDeclaration') {
168
+ return [{ name: node.exported ? moduleName(node.exported) : `* from '${node.source.value}'`, line }]
169
+ }
170
+ if (node.type !== 'ExportNamedDeclaration') {
171
+ return []
172
+ }
173
+ if (node.declaration?.type === 'VariableDeclaration') {
174
+ return node.declaration.declarations.flatMap((declarator) => boundNames(declarator.id))
175
+ .map((name) => ({ name, line }))
176
+ }
177
+ if (node.declaration) {
178
+ return [{ name: node.declaration.id.name, line }]
179
+ }
180
+ return node.specifiers.map((specifier) => ({
181
+ name: moduleName(specifier.exported),
182
+ line: specifier.loc.start.line,
183
+ }))
184
+ }
185
+
186
+ function moduleName(node) {
187
+ return node.type === 'Literal' ? String(node.value) : node.name
188
+ }
189
+
190
+ /** The identifiers a binding pattern declares. */
191
+ function boundNames(pattern) {
192
+ switch (pattern.type) {
193
+ case 'Identifier':
194
+ return [pattern.name]
195
+ case 'ObjectPattern':
196
+ return pattern.properties.flatMap((property) => boundNames(property.value ?? property.argument))
197
+ case 'ArrayPattern':
198
+ return pattern.elements.filter(Boolean).flatMap(boundNames)
199
+ case 'RestElement':
200
+ return boundNames(pattern.argument)
201
+ case 'AssignmentPattern':
202
+ return boundNames(pattern.left)
203
+ default:
204
+ return []
205
+ }
206
+ }
207
+
208
+ function pluginBins(root, pkg, name, lineOf) {
209
+ const rule = TREE_RULES.plugin
210
+ const binName = `nera-${name}`
211
+ const hasViews = isDirectory(root, 'views')
212
+ const hasScript = existsSync(path.join(root, PUBLISH_TEMPLATE))
213
+ const findings = []
214
+
215
+ if (hasViews && !hasScript) {
216
+ findings.push({
217
+ file: PUBLISH_TEMPLATE,
218
+ line: 1,
219
+ rule,
220
+ message: `"${PUBLISH_TEMPLATE}" is missing although the plugin ships views/: add it ` +
221
+ '(publishAllTemplates from @nera-static/plugin-utils), since nera add runs it',
222
+ })
223
+ }
224
+ if (!hasViews && hasScript) {
225
+ findings.push({
226
+ file: PUBLISH_TEMPLATE,
227
+ line: 1,
228
+ rule,
229
+ message: `"${PUBLISH_TEMPLATE}" exists, but the plugin ships no views/: delete it and its "bin" entry`,
230
+ })
231
+ }
232
+
233
+ const bins = binEntries(pkg)
234
+ for (const { key, target } of bins) {
235
+ if (hasViews && key === binName && target === PUBLISH_TEMPLATE) {
236
+ continue
237
+ }
238
+ const allowed = hasViews
239
+ ? `the only bin is { "${binName}": "${PUBLISH_TEMPLATE}" }`
240
+ : 'a plugin without views/ has no bin'
241
+ const why = target === PUBLISH_TEMPLATE
242
+ ? ''
243
+ : ` (nera add copies config/${name}.yaml itself, so no other script is needed)`
244
+ findings.push({
245
+ file: 'package.json',
246
+ line: lineOf('bin', key),
247
+ rule,
248
+ message: `the bin "${key}" → "${target}" is not allowed: ${allowed}; remove it${why}`,
249
+ })
250
+ }
251
+ if (hasViews && !bins.some(({ key, target }) => key === binName && target === PUBLISH_TEMPLATE)) {
252
+ findings.push({
253
+ file: 'package.json',
254
+ line: lineOf('bin'),
255
+ rule,
256
+ message: `"bin" lacks { "${binName}": "${PUBLISH_TEMPLATE}" }: add it, since nera add runs it`,
257
+ })
258
+ }
259
+ return findings
260
+ }
261
+
262
+ /** The `bin` entries as `{ key, target }`, a string `bin` under the package's own name. */
263
+ function binEntries(pkg) {
264
+ if (typeof pkg.bin === 'string') {
265
+ return [{ key: pkg.name.replace(SCOPE, ''), target: normalize(pkg.bin) }]
266
+ }
267
+ if (!isPlainObject(pkg.bin)) {
268
+ return []
269
+ }
270
+ return Object.entries(pkg.bin).map(([key, target]) => ({ key, target: normalize(String(target)) }))
271
+ }
272
+
273
+ /**
274
+ * `structure/theme-tree`: the layout, the contract seams, a `nera.generator` range, and for
275
+ * every `@font-face` its file and a licence file under `assets/fonts/<theme>/`.
276
+ */
277
+ function themeTree(root, pkg, lineOf) {
278
+ const rule = TREE_RULES.theme
279
+ const findings = []
280
+
281
+ if (!existsSync(path.join(root, THEME_LAYOUT))) {
282
+ findings.push({
283
+ file: THEME_LAYOUT,
284
+ line: 1,
285
+ rule,
286
+ message: `"${THEME_LAYOUT}" is missing: every page layout of the theme extends this one layout`,
287
+ })
288
+ }
289
+ for (const seam of THEME_SEAMS) {
290
+ const file = `views/partials/${seam}.pug`
291
+ if (!existsSync(path.join(root, file))) {
292
+ findings.push({
293
+ file,
294
+ line: 1,
295
+ rule,
296
+ message: `the seam "${file}" is missing: ship it empty (or with a plugin-free default), ` +
297
+ `so a site can fill it by overriding the file; the seams are ${THEME_SEAMS.join(', ')}`,
298
+ })
299
+ }
300
+ }
301
+
302
+ const nera = isPlainObject(pkg.nera) ? pkg.nera : {}
303
+ if (!isText(nera.generator)) {
304
+ findings.push({
305
+ file: 'package.json',
306
+ line: lineOf('nera', 'generator'),
307
+ rule,
308
+ message: '"nera.generator" is missing: set it to the core range the theme needs, e.g. ">=4.15.0"',
309
+ })
310
+ }
311
+
312
+ findings.push(...themeFonts(root, themeName(pkg.name)))
313
+ return findings
314
+ }
315
+
316
+ function themeName(name) {
317
+ return String(name ?? '').replace(SCOPE, '').replace(THEME_PREFIX, '')
318
+ }
319
+
320
+ function themeFonts(root, theme) {
321
+ const rule = TREE_RULES.theme
322
+ const folder = `assets/fonts/${theme}`
323
+ const findings = []
324
+ let first = null
325
+
326
+ for (const file of filesUnder(root, 'assets').filter((name) => name.endsWith('.css'))) {
327
+ const text = readFileSync(path.join(root, file), 'utf8').replace(CSS_COMMENT, (comment) => blank(comment))
328
+ for (const face of text.matchAll(FONT_FACE)) {
329
+ for (const url of face[1].matchAll(CSS_URL)) {
330
+ const value = url[2].trim()
331
+ if (value.startsWith('data:')) {
332
+ continue
333
+ }
334
+ const line = lineAt(text, face.index + face[0].indexOf(face[1]) + url.index)
335
+ first ??= { file, line }
336
+ const target = fontTarget(file, value)
337
+ const inside = target !== null && target.startsWith(`${folder}/`)
338
+ if (inside && existsSync(path.join(root, target))) {
339
+ continue
340
+ }
341
+ findings.push({
342
+ file,
343
+ line,
344
+ rule,
345
+ message: inside
346
+ ? `the font "${value}" points to "${target}", which does not exist: add the file or fix the url`
347
+ : `the font "${value}" is not a file under ${folder}/: self-host it there, ` +
348
+ 'with its licence text next to it',
349
+ })
350
+ }
351
+ }
352
+ }
353
+
354
+ const hasLicence = isDirectory(root, folder) &&
355
+ readdirSync(path.join(root, folder)).some((name) => LICENCE_FILE.test(name))
356
+ if (first && !hasLicence) {
357
+ findings.push({
358
+ ...first,
359
+ rule,
360
+ message: `the theme ships fonts, but ${folder}/ holds no licence file: add each font's licence ` +
361
+ '(e.g. OFL-<font>.txt) there',
362
+ })
363
+ }
364
+ return findings
365
+ }
366
+
367
+ /** The repo path a font url in `cssFile` points to, `null` for a remote url. */
368
+ function fontTarget(cssFile, url) {
369
+ const clean = url.replace(/[?#].*$/, '')
370
+ if (REMOTE_URL.test(clean)) {
371
+ return null
372
+ }
373
+ // A root-relative url is served from public/, which the theme's assets/ become.
374
+ const target = clean.startsWith('/')
375
+ ? path.posix.join('assets', clean)
376
+ : path.posix.join(path.posix.dirname(cssFile), clean)
377
+ return path.posix.normalize(target)
378
+ }
379
+
380
+ /**
381
+ * `structure/starter-tree`: `nera.starter.label` and `description`, `files` with only what
382
+ * `nera new` copies, a README whose last H2 is `## First steps`, and no file byte-identical
383
+ * to an installed plugin's `views/` file.
384
+ */
385
+ function starterTree(root, pkg, lineOf) {
386
+ const rule = TREE_RULES.starter
387
+ const findings = []
388
+
389
+ const starter = isPlainObject(pkg.nera?.starter) ? pkg.nera.starter : {}
390
+ for (const key of ['label', 'description']) {
391
+ if (!isText(starter[key])) {
392
+ findings.push({
393
+ file: 'package.json',
394
+ line: lineOf('nera', 'starter', key),
395
+ rule,
396
+ message: `"nera.starter.${key}" is missing: nera new --starter lists the starter by its label ` +
397
+ 'and description, so set both as non-empty strings',
398
+ })
399
+ }
400
+ }
401
+
402
+ findings.push(...starterFiles(pkg, lineOf), ...firstSteps(root), ...copiedPluginFiles(root))
403
+ return findings
404
+ }
405
+
406
+ function starterFiles(pkg, lineOf) {
407
+ const rule = TREE_RULES.starter
408
+ const allowed = [...STARTER_ENTRIES, CHANGELOG]
409
+ if (!Array.isArray(pkg.files)) {
410
+ return [{
411
+ file: 'package.json',
412
+ line: 1,
413
+ rule,
414
+ message: `"files" is missing, so npm ships the whole repo: list only ${allowed.join(', ')}`,
415
+ }]
416
+ }
417
+
418
+ return pkg.files.filter((entry) => {
419
+ if (typeof entry !== 'string') {
420
+ return true
421
+ }
422
+ const negated = entry.startsWith('!')
423
+ const target = normalize(negated ? entry.slice(1) : entry).replace(/\/$/, '')
424
+ if (negated) {
425
+ return !STARTER_ENTRIES.some((folder) => target.startsWith(`${folder}/`))
426
+ }
427
+ return !allowed.includes(target)
428
+ }).map((entry) => ({
429
+ file: 'package.json',
430
+ line: lineOf('files'),
431
+ rule,
432
+ message: `"files" lists ${JSON.stringify(entry)}, which nera new does not copy: list only ` +
433
+ `${allowed.join(', ')}, and "!…" exclusions inside them`,
434
+ }))
435
+ }
436
+
437
+ function firstSteps(root) {
438
+ const rule = TREE_RULES.starter
439
+ const file = path.join(root, README)
440
+ if (!existsSync(file)) {
441
+ return [{
442
+ file: README,
443
+ line: 1,
444
+ rule,
445
+ message: `"${README}" is missing: nera new prints its last section, "${FIRST_STEPS}"`,
446
+ }]
447
+ }
448
+
449
+ const last = headings(readFileSync(file, 'utf8'))
450
+ .filter(({ level }) => level === 2)
451
+ .map(({ text, line }) => ({ text: `## ${text}`, line }))
452
+ .at(-1)
453
+ if (last?.text === FIRST_STEPS) {
454
+ return []
455
+ }
456
+ return [{
457
+ file: README,
458
+ line: last?.line ?? 1,
459
+ rule,
460
+ message: last
461
+ ? `the last H2 is "${last.text}", but it must be "${FIRST_STEPS}", which nera new prints: ` +
462
+ 'move that section to the end'
463
+ : `the README has no "${FIRST_STEPS}" section: add it as the last H2, since nera new prints it`,
464
+ }]
465
+ }
466
+
467
+ /** Files under the copied entries whose bytes equal a file under an installed plugin's `views/`. */
468
+ function copiedPluginFiles(root) {
469
+ const views = pluginViewHashes(root)
470
+ if (views.size === 0) {
471
+ return []
472
+ }
473
+ return STARTER_ENTRIES.flatMap((entry) => filesUnder(root, entry))
474
+ .map((file) => ({ file, source: views.get(hashOf(path.join(root, file))) }))
475
+ .filter(({ source }) => source !== undefined)
476
+ .map(({ file, source }) => ({
477
+ file,
478
+ line: 1,
479
+ rule: TREE_RULES.starter,
480
+ message: `the file is a copy of ${source} and goes stale with every plugin release: ` +
481
+ 'delete it and let the plugin provide it (its getAssets, or npx nera-<name> in the site)',
482
+ }))
483
+ }
484
+
485
+ /** `sha256 → "<package>/views/<file>"` for every non-empty file of an installed plugin's `views/`. */
486
+ function pluginViewHashes(root) {
487
+ const scope = path.join(root, 'node_modules', '@nera-static')
488
+ const hashes = new Map()
489
+ if (!isDirectory(scope, '.')) {
490
+ return hashes
491
+ }
492
+ for (const dir of readdirSync(scope).sort()) {
493
+ const name = `@nera-static/${dir}`
494
+ if (!isPluginPackage(name)) {
495
+ continue
496
+ }
497
+ for (const file of filesUnder(path.join(scope, dir), 'views')) {
498
+ const hash = hashOf(path.join(scope, dir, file))
499
+ if (hash !== null && !hashes.has(hash)) {
500
+ hashes.set(hash, `${name}/${file}`)
501
+ }
502
+ }
503
+ }
504
+ return hashes
505
+ }
506
+
507
+ /** The sha256 of a file's bytes, `null` for an empty file (an empty seam equals every empty file). */
508
+ function hashOf(file) {
509
+ const bytes = readFileSync(file)
510
+ return bytes.length === 0 ? null : createHash('sha256').update(bytes).digest('hex')
511
+ }
512
+
513
+ /** Every file under `<base>/<dir>`, as paths relative to `base` with `/`, skipping `node_modules` and `.git`. */
514
+ function filesUnder(base, dir) {
515
+ if (!isDirectory(base, dir)) {
516
+ return []
517
+ }
518
+ const files = []
519
+ const walk = (relative) => {
520
+ for (const entry of readdirSync(path.join(base, relative), { withFileTypes: true })) {
521
+ const child = `${relative}/${entry.name}`
522
+ if (entry.isDirectory() && !SKIPPED_DIRS.has(entry.name)) {
523
+ walk(child)
524
+ } else if (entry.isFile()) {
525
+ files.push(child)
526
+ }
527
+ }
528
+ }
529
+ walk(dir)
530
+ return files.sort()
531
+ }
532
+
533
+ function packageLines(root) {
534
+ return keyLines(readFileSync(path.join(root, 'package.json'), 'utf8'))
535
+ }
536
+
537
+ /** The comment with every character but its line breaks replaced, so offsets and lines stay. */
538
+ function blank(comment) {
539
+ return comment.replace(/[^\n]/g, ' ')
540
+ }
541
+
542
+ function lineAt(text, offset) {
543
+ return text.slice(0, offset).split('\n').length
544
+ }
package/src/cli.js CHANGED
@@ -1,13 +1,16 @@
1
- import { realpathSync } from 'node:fs'
2
1
  import path from 'node:path'
3
2
  import { fileURLToPath } from 'node:url'
4
3
  import { parseArgs as parseNodeArgs } from 'node:util'
5
4
 
6
- import { isInside } from '@nera-static/plugin-utils/urls'
7
- import { ESLint } from 'eslint'
8
-
9
- import { createConfig } from './eslint/config.js'
5
+ import { canonicalCheck } from './checks/canonical.js'
6
+ import { cssCheck } from './checks/css.js'
7
+ import { docsCheck } from './checks/docs.js'
8
+ import { packageCheck } from './checks/package.js'
9
+ import { pugCheck } from './checks/pug.js'
10
+ import { treeCheck } from './checks/tree.js'
11
+ import { eslintCheck } from './eslint/check.js'
10
12
  import { readPackage } from './kind.js'
13
+ import { assertKnownRules, readSettings } from './settings.js'
11
14
 
12
15
  /** Exit codes of the `nera-stan` bin (D2). */
13
16
  export const EXIT = Object.freeze({ clean: 0, findings: 1, error: 2 })
@@ -25,10 +28,6 @@ Options:
25
28
 
26
29
  Exit codes: 0 clean, 1 findings, 2 usage or internal error.`
27
30
 
28
- /** Rule names for ESLint messages that carry no rule id. */
29
- const PARSE_ERROR = 'parse-error'
30
- const DIRECTIVE = 'eslint-directive'
31
-
32
31
  /** An error in how nera-stan was called; the bin prints it with the usage hint. */
33
32
  export class UsageError extends Error {}
34
33
 
@@ -73,45 +72,56 @@ export function version() {
73
72
  }
74
73
 
75
74
  /**
76
- * Lint the repo at `dir` with the shipped config; its own `eslint.config.js` is
77
- * never read (D3). A file whose real path lies outside `dir` (a symlink out of the
78
- * repo) is neither reported nor fixed, so `fix` never writes outside `dir`.
75
+ * The checks `lint` runs, in order. A check is `{ name, rules(context), run(context) }`:
76
+ * `rules` returns (or resolves to) every rule id it can report and is called only when
77
+ * `nera-stan.skip` names any, `run` resolves to `{ findings }`, each finding
78
+ * `{ file, line, column?, rule, message, fixable }`, with `file` relative to the repo root.
79
+ * The canonical check comes after the package check, since both may rewrite `package.json`.
80
+ */
81
+ export const CHECKS = Object.freeze([
82
+ eslintCheck,
83
+ cssCheck,
84
+ pugCheck,
85
+ packageCheck,
86
+ treeCheck,
87
+ docsCheck,
88
+ canonicalCheck,
89
+ ])
90
+
91
+ /**
92
+ * Check the repo at `dir` with every check and merge their findings into one report.
93
+ * Findings of a rule id under `nera-stan.skip` are dropped.
79
94
  *
80
95
  * @param {string} dir - The repo's root directory.
81
96
  * @param {object} [options]
82
97
  * @param {boolean} [options.fix=false] - Write fixes back to disk.
98
+ * @param {object[]} [options.checks=CHECKS] - The checks to run.
83
99
  * @returns {Promise<{ findings: { file: string, line: number, rule: string, message: string }[], fixable: number }>}
84
- * The remaining findings, sorted by file and line, and how many of them `--fix` would remove.
85
- * @throws {Error} When the repo's `package.json` or its `nera-stan` key is invalid.
100
+ * The remaining findings, sorted by file, line and column, and how many of them `--fix` would remove.
101
+ * @throws {Error} When the repo's `package.json` or its `nera-stan` key is invalid, or `skip`
102
+ * names a rule id no check reports.
86
103
  */
87
- export async function lint(dir, { fix = false } = {}) {
104
+ export async function lint(dir, { fix = false, checks = CHECKS } = {}) {
88
105
  const root = path.resolve(dir)
89
- const eslint = new ESLint({
90
- cwd: root,
91
- overrideConfigFile: true,
92
- overrideConfig: createConfig({ root }),
93
- errorOnUnmatchedPattern: false,
94
- fix,
95
- })
96
-
97
- const realRoot = realpathSync(root)
98
- const results = (await eslint.lintFiles(['.']))
99
- .filter((result) => isInside(realRoot, realpathSync(result.filePath), { self: false }))
100
- if (fix) {
101
- await ESLint.outputFixes(results)
106
+ const pkg = readPackage(root)
107
+ const settings = readSettings(pkg, root)
108
+ const context = { root, pkg, settings, fix }
109
+ if (Object.keys(settings.skip).length > 0) {
110
+ const ruleIds = await Promise.all(checks.map((check) => check.rules(context)))
111
+ assertKnownRules(settings, ruleIds.flat(), root)
112
+ }
113
+
114
+ const findings = []
115
+ for (const check of checks) {
116
+ const result = await check.run(context)
117
+ findings.push(...result.findings.filter((finding) => !Object.hasOwn(settings.skip, finding.rule)))
102
118
  }
119
+ findings.sort((a, b) => compare(a.file, b.file) || a.line - b.line || (a.column ?? 1) - (b.column ?? 1))
103
120
 
104
- const findings = results.flatMap((result) => result.messages.map((message) => ({
105
- file: path.relative(root, result.filePath).split(path.sep).join('/'),
106
- line: message.line ?? 1,
107
- column: message.column ?? 1,
108
- rule: message.ruleId ?? (message.fatal ? PARSE_ERROR : DIRECTIVE),
109
- message: message.message,
110
- })))
111
- findings.sort((a, b) => compare(a.file, b.file) || a.line - b.line || a.column - b.column)
112
-
113
- const fixable = results.reduce((sum, result) => sum + result.fixableErrorCount + result.fixableWarningCount, 0)
114
- return { findings: findings.map(({ file, line, rule, message }) => ({ file, line, rule, message })), fixable }
121
+ return {
122
+ findings: findings.map(({ file, line, rule, message }) => ({ file, line, rule, message })),
123
+ fixable: findings.filter((finding) => finding.fixable).length,
124
+ }
115
125
  }
116
126
 
117
127
  /**