@starci/eslint-canon-be 3.17.4 → 3.18.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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.18.0 - 2026-11-05
4
+
5
+ - Added (PROJECT-LINT-3): `starciBeConfig` and `starciBePackagesConfig` load the ESLint rules of the app's rule packs (hfs.json `rulePacks`) for the be side and the root packages, one plugin per pack, each rule at its severity; a refused pack throws `HFS_RULE_PACK_INVALID`. The runtime copies carry `scripts/lib/rule-packs.mjs`, the `rulePacks` key of the declaration check, R16, R381 and R382, and the canon pins of `@starci/hfs` 5.11.0.
6
+
3
7
  ## 3.17.4 - 2026-11-05
4
8
 
5
9
  - Changed: the runtime copy of the canon pins names `@starci/hfs` 5.10.4 and the Grammar family 0.21.34.
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@
16
16
  * every conversation about the failure. Aliasing one here to match a target's older spelling would
17
17
  * leave two names for one rule and no way to tell which a message came from.
18
18
  */
19
+ import { packEslintConfigs } from "#runtime/scripts/lib/rule-packs.mjs";
19
20
  import { buildBeConfig, buildBePackagesConfig } from "./lib/config.js";
20
21
  import { pluginForEdition } from "./lib/edition.js";
21
22
  import { recommended as aiGatewayRecommended, rules as aiGatewayRules } from "./ai-gateway.js";
@@ -180,7 +181,19 @@ export default plugin;
180
181
  * @param input - The HFS view of the repository.
181
182
  * @returns The flat config.
182
183
  */
183
- export const starciBeConfig = ({ hfs }) => buildBeConfig({ hfs, plugin: pluginForEdition({ plugin, hfs }), recommended });
184
+ export const starciBeConfig = async ({ hfs }) => [
185
+ ...(await buildBeConfig({ hfs, plugin: pluginForEdition({ plugin, hfs }), recommended })),
186
+ ...withPackRules(hfs, "be"),
187
+ ];
188
+ /**
189
+ * The ESLint rules of the app's rule packs (hfs.json `rulePacks`, contexts/project/lint.md PROJECT-LINT-3) for one scope: the one sanctioned way an app adds
190
+ * a lint law, loaded by this factory so no tool config of the app defines a rule. A refused pack throws (HFS_RULE_PACK_INVALID): a lint run never guesses.
191
+ *
192
+ * @param hfs - The HFS view the config was built for (its repoRoot is the folder of the eslint.config.mjs).
193
+ * @param side - The scope: the be side, or the root packages.
194
+ * @returns The pack blocks, none when the app declares no pack.
195
+ */
196
+ const withPackRules = (hfs, side) => hfs === null || hfs === undefined ? [] : packEslintConfigs(hfs.repoRoot, side, side === "packages" ? ["packages/*/src/**/*.{ts,tsx,mts,cts}"] : undefined);
184
197
  /** The levels a package is judged by: every rule of the be side but the project-graph rules, which judge the import graph of a side folder (the packages are not part of it). */
185
198
  const packageRecommended = Object.fromEntries(Object.entries(recommended).filter(([name]) => !(name in projectGraphRecommended)));
186
199
  /**
@@ -190,7 +203,10 @@ const packageRecommended = Object.fromEntries(Object.entries(recommended).filter
190
203
  * @param input - The package view of the app root.
191
204
  * @returns The flat config.
192
205
  */
193
- export const starciBePackagesConfig = ({ hfs }) => buildBePackagesConfig({ hfs, plugin: pluginForEdition({ plugin, hfs }), recommended: packageRecommended });
206
+ export const starciBePackagesConfig = async ({ hfs }) => [
207
+ ...(await buildBePackagesConfig({ hfs, plugin: pluginForEdition({ plugin, hfs }), recommended: packageRecommended })),
208
+ ...withPackRules(hfs, "packages"),
209
+ ];
194
210
  export { linterOptions } from "./lib/config.js";
195
211
  export { loadHfs, loadPackagesHfs } from "./lib/hfs.js";
196
212
  // A12 registration is appended so the shared registry can be union-merged.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starci/eslint-canon-be",
3
- "version": "3.17.4",
3
+ "version": "3.18.0",
4
4
  "description": "The StarCi back-end lint canon: every rule its laws publish, gathered as one flat-config plugin.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -170,6 +170,7 @@
170
170
  "scripts/lib/path-key.mjs",
171
171
  "scripts/lib/read-text.mjs",
172
172
  "scripts/lib/regex.mjs",
173
+ "scripts/lib/rule-packs.mjs",
173
174
  "scripts/lib/same-text.mjs",
174
175
  "scripts/lib/sops-envelope.mjs",
175
176
  "scripts/lib/stack-services.mjs",
@@ -38,7 +38,7 @@ pins:
38
38
  source: packages/next-data/package.json
39
39
  why: 'the SWR data helpers of every front end (fe-stack data, owner:next-data-package): pollingRestart, the viewer and tenant key helpers, viewerSwrConfig and the viewer cache; each operation hook stays in the app and the package holds no component.'
40
40
  '@starci/grammar':
41
- version: 0.21.34
41
+ version: 0.21.35
42
42
  group: starci
43
43
  install: registry
44
44
  side: fe
@@ -52,28 +52,28 @@ pins:
52
52
  source: packages/next-i18n/package.json
53
53
  why: 'the next-intl stack of every front end (fe-stack i18n, owner:next-i18n-package): defineI18n over the locales of the app, the locale-negotiating proxy, the locale-aware navigation, the request config that loads the catalogs of the app and the locale read of the [locale] layout; the app keeps its message catalogs and writes none of the stack.'
54
54
  '@starci/eslint-canon-be':
55
- version: 3.17.4
55
+ version: 3.18.0
56
56
  group: starci
57
57
  install: registry
58
58
  side: be
59
59
  source: packages/eslint-canon-be/package.json
60
60
  why: 'the back-end ESLint canon: `loadHfs(import.meta.url)` of be/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the be side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; `starciBeConfig({ hfs: loadHfs(import.meta.url) })` is the typed factory and the BE-CONVENTION laws are its rules.'
61
61
  '@starci/eslint-canon-fe':
62
- version: 9.13.16
62
+ version: 9.14.0
63
63
  group: starci
64
64
  install: registry
65
65
  side: fe
66
66
  source: packages/eslint-canon-fe/package.json
67
67
  why: 'the front-end ESLint canon: `loadHfs(import.meta.url)` of fe/eslint.config.mjs finds the app-root hfs.json (kind app) and gives every linted file the view of the fe side, and the project graph is built per side; its bundled runtime copies (slots, canon-pins, failure codes, the architecture machine) put .starcistacks and .sops.yaml at the app root; the front end has no tests (FE_NO_TESTS R97 in hfs) and no-vietnamese-in-source (R91) applies.'
68
68
  '@starci/eslint-grammar-core':
69
- version: 0.21.34
69
+ version: 0.21.35
70
70
  group: starci
71
71
  install: registry
72
72
  side: fe
73
73
  source: packages/eslint-grammar-core/package.json
74
74
  why: 'the StarCi Grammar component API lint, versioned with @starci/grammar; front ends compose this family package with the universal FE canon.'
75
75
  '@starci/eslint-grammar-offset-pop':
76
- version: 0.21.34
76
+ version: 0.21.35
77
77
  group: starci
78
78
  install: registry
79
79
  side: fe
@@ -155,7 +155,7 @@ pins:
155
155
  source: packages/mail/package.json
156
156
  why: 'outgoing mail of a back end: a NestJS module and the Mailer port over SMTP (connect, greeting, socket and total timeouts, STARTTLS required by default, recipient, message and attachment checks, a shared SMTP target policy, coded errors, typed escaping render helpers returning { subject, text, html }), with @starci/mail/testing for its specs; the only importer of nodemailer (R90).'
157
157
  '@starci/hfs':
158
- version: 5.10.4
158
+ version: 5.11.0
159
159
  group: starci
160
160
  install: registry
161
161
  side: both
@@ -292,7 +292,7 @@ rules:
292
292
  code: "HFS_TOOL_CONFIG_LOCAL"
293
293
  editions: ["lite", "full"]
294
294
  docs: ["docs/managed-tooling-coverage.md#local-tool-configuration"]
295
- law: "Configs only call the factories; no local rules."
295
+ law: "Configs only call the factories; no local rules. An app's own lint rules come only through the rule packs of hfs.json rulePacks, which the canon factories load (R381, PROJECT-LINT-3)."
296
296
  kinds: [check, codemod]
297
297
  gates: [land, ci]
298
298
  failureCodes: ["HFS_TOOL_CONFIG_LOCAL"]
@@ -6698,7 +6698,7 @@ rules:
6698
6698
  - {path: packages/hfs/src/branch-profile.spec.mjs, editions: [lite, full]}
6699
6699
  - id: R379
6700
6700
  code: "LINT_RATCHET_RAISED"
6701
- law: "On a branch whose profile runs lint as report, a commit never adds lint findings to a file it touches: each touched source file has no more ESLint error findings than at the base (the parent commit for the pre-commit hook, the merge-base with the pushed range or the remote branch, else HEAD^, for the pre-push hook and CI) and a new file has none, judged by linting both versions of the touched files through the side's installed config; the findings a file already carried stay report-only, and a ratchet violation blocks at any count."
6701
+ law: "On a branch whose profile runs lint as report, a commit never adds lint findings to a file it touches: each touched source file has no more ESLint error findings than at the base (the parent commit for the pre-commit hook, the merge-base with the pushed range or the remote branch, else HEAD^, for the pre-push hook and CI) and a new file has none, judged by the lint records of the base commit's committed cache and of the run when both hold a file and no rule rose, else by linting both versions of the touched files through the side's installed config in bounded children; the findings a file already carried stay report-only, and a ratchet violation blocks at any count."
6702
6702
  kinds: [check]
6703
6703
  gates: [pre-commit, settle, land, ci]
6704
6704
  failureCodes: ["LINT_RATCHET_RAISED"]
@@ -6728,3 +6728,33 @@ rules:
6728
6728
  - {path: packages/eslint/grammar-core/choice-controls.spec.mjs, editions: [lite, full], codes: [FE_GROUPED_CHOICE_CONTROL]}
6729
6729
  witness:
6730
6730
  - {path: packages/eslint/grammar-core/choice-controls.spec.mjs, editions: [lite, full], codes: [FE_GROUPED_CHOICE_CONTROL]}
6731
+ - id: R381
6732
+ code: "HFS_RULE_PACK_INVALID"
6733
+ law: "An app adds its own laws only through rule packs hfs.json rulePacks names: an installed package that exports ./rule-pack, a starci/rule-pack@1 manifest whose every rule carries an id, a finding code, a severity, its spec and its doc and exactly one engine (a machine rule the app check runs, or an ESLint rule the canon factories load); a pack only adds, so a rule with any other key, a code the harness reports, an id or code another pack holds, a rule that throws or a finding without a path refuses the pack, which then lends nothing; its findings go through the harness's policy (a machine rule blocks like hfs, an ESLint rule follows the lint gate, its branch profile and the ratchet)."
6734
+ kinds: [check]
6735
+ gates: [settle, land, ci]
6736
+ failureCodes: ["HFS_RULE_PACK_INVALID"]
6737
+ enforcers:
6738
+ - {kind: hfs, id: rule-packs, at: scripts/hfs/rules/app-extension-findings.mjs}
6739
+ editions: [lite, full]
6740
+ docs:
6741
+ - {path: contexts/project/lint.md#project-lint-3-an-app-extends-the-law-through-rule-packs-and-package-slot-manifests, editions: [lite, full]}
6742
+ proves:
6743
+ - {path: packages/hfs/src/rule-packs.spec.mjs, editions: [lite, full]}
6744
+ witness:
6745
+ - {path: packages/hfs/src/rule-packs.spec.mjs, editions: [lite, full]}
6746
+ - id: R382
6747
+ code: "HFS_PACKAGE_SLOT_UNPLACED"
6748
+ law: "A root workspace package that declares packages/<name>/slots.yaml (starci/package-slots@1) is held to it as the be and fe sides are held to theirs: every file below its src/ belongs to a declared slot (unless closed is false), each instance of a folder slot holds every file the slot requires and nothing its allows leave out, and the manifest itself is readable; its coverage follows the slots, every file measured at 100 per file but the barrels, the type files and a slot that opts out with coverage: { none: <reason> }."
6749
+ kinds: [check]
6750
+ gates: [settle, land, ci]
6751
+ failureCodes: ["HFS_PACKAGE_SLOT_UNPLACED", "HFS_PACKAGE_SLOT_MISSING", "HFS_PACKAGE_SLOT_DISALLOWED", "HFS_PACKAGE_SLOTS_INVALID"]
6752
+ enforcers:
6753
+ - {kind: hfs, id: package-slots, at: scripts/hfs/rules/app-extension-findings.mjs}
6754
+ editions: [lite, full]
6755
+ docs:
6756
+ - {path: contexts/project/lint.md#project-lint-3-an-app-extends-the-law-through-rule-packs-and-package-slot-manifests, editions: [lite, full]}
6757
+ proves:
6758
+ - {path: packages/hfs/src/package-slots.spec.mjs, editions: [lite, full]}
6759
+ witness:
6760
+ - {path: packages/hfs/src/package-slots.spec.mjs, editions: [lite, full]}
@@ -149,7 +149,9 @@ function observeBlockProblems(observe) {
149
149
  bad.push('observe.reporter must name the optional error reporter');
150
150
  return bad;
151
151
  }
152
- const DECLARATION_KEYS = new Set(['hfs', 'kind', 'project', 'edition', 'db', 'sides', 'browser', 'modules', 'lexicon', 'observe']);
152
+ const DECLARATION_KEYS = new Set(['hfs', 'kind', 'project', 'edition', 'db', 'sides', 'browser', 'modules', 'lexicon', 'observe', 'rulePacks']);
153
+ /** A rule pack hfs.json names (PROJECT-LINT-3): an npm package name, each once. */
154
+ const RULE_PACK_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
153
155
  const RUNTIME_DECLARATION_KEYS = new Set(['hfs', 'kind', 'project']);
154
156
  function productDeclarationProblems(declaration, profiles) {
155
157
  const bad = [];
@@ -159,6 +161,8 @@ function productDeclarationProblems(declaration, profiles) {
159
161
  bad.push(...dbBlockProblems(declaration.db), ...lexiconBlockProblems(declaration.lexicon), ...observeBlockProblems(declaration.observe));
160
162
  if (declaration.browser !== undefined && declaration.browser !== true)
161
163
  bad.push('browser is `true` when the app has a browser journey (slot app.browser), and is left out otherwise');
164
+ if (declaration.rulePacks !== undefined && (!Array.isArray(declaration.rulePacks) || declaration.rulePacks.length === 0 || declaration.rulePacks.some((name) => typeof name !== 'string' || !RULE_PACK_NAME.test(name)) || new Set(declaration.rulePacks).size !== declaration.rulePacks.length))
165
+ bad.push('rulePacks is a non-empty list of the installed rule pack packages the app adds its laws with, each once (PROJECT-LINT-3)');
162
166
  if (declaration.modules !== undefined && declaration.modules !== 'data')
163
167
  bad.push('modules is `"data"` when the app keeps its modules as data (seeds, no rendered registry package), and is left out otherwise');
164
168
  if (declaration.kind !== APP_KIND)
@@ -0,0 +1,243 @@
1
+ // rule-packs.mjs - an app's rule packs (PROJECT-LINT-3): the packages hfs.json `rulePacks` names, each adding the app's own laws to the harness's
2
+ // gates without a local rule in a tool config. A pack is an installed package that exports `./rule-pack`, an ES module whose default export is
3
+ // { schema: 'starci/rule-pack@1', name: '<the package name>', rules: [<rule>, ...] }
4
+ // and every rule carries an id (`NIVO-BLOCK-1`), a finding code (`NIVO_BLOCK_INCOMPLETE`), a severity (error or warning), the spec that proves it
5
+ // (a file of the package) and its doc (a file of the package or an https link), plus exactly one engine:
6
+ // check a machine rule `(context) => findings` of the hfs family: `starci app check` runs it over the tracked files (context.files, context.read)
7
+ // eslint { name, rule, sides } an ESLint rule the canon factories (eslint-canon-be, eslint-canon-fe, the packages config) load for the sides it names
8
+ // A pack only adds: a rule with any other key (an `off`, `overrides` or `disable`), a code the harness already reports, or an id or code another
9
+ // pack uses is refused (HFS_RULE_PACK_INVALID, R381) and the pack lends nothing. Pack findings go through the same policy as the harness's own:
10
+ // a check rule is an hfs finding (blocking on every branch), an eslint rule a lint finding (report under a branch profile, held by the ratchet).
11
+ import fs from 'node:fs';
12
+ import { createRequire } from 'node:module';
13
+ import path from 'node:path';
14
+ export const RULE_PACK_SCHEMA = 'starci/rule-pack@1';
15
+ /** The subpath a pack exports its manifest at. */
16
+ export const RULE_PACK_ENTRY = 'rule-pack';
17
+ /** The sides an eslint pack rule may name: the two side folders and the root packages. */
18
+ export const PACK_SIDES = Object.freeze(['be', 'fe', 'packages']);
19
+ const RULE_KEYS = new Set(['id', 'code', 'severity', 'spec', 'doc', 'check', 'eslint']);
20
+ const ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/u;
21
+ const CODE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/u;
22
+ const ESLINT_NAME = /^[a-z][a-z0-9-]*$/u;
23
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
24
+ const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
25
+ const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null);
26
+ const FAILURE_CODES = new URL('../../modules/kernel/failure-codes.yaml', import.meta.url);
27
+ let harnessCodes = null;
28
+ /**
29
+ * Every code the harness reports (the top-level keys of its failure-code catalog), the codes a pack may not take; empty where the catalog is not
30
+ * shipped (a canon package's runtime copy), where the app check refuses such a pack instead.
31
+ */
32
+ export function reservedCodes() {
33
+ if (harnessCodes === null) {
34
+ let catalog = '';
35
+ try {
36
+ catalog = fs.readFileSync(FAILURE_CODES, 'utf8');
37
+ }
38
+ catch { /* not shipped beside this copy */ }
39
+ harnessCodes = new Set([...catalog.matchAll(/^([A-Z][A-Z0-9_]+):\s*$/gmu)].map((match) => match[1]));
40
+ }
41
+ return harnessCodes;
42
+ }
43
+ /** The app root above `start` (a side folder or the root itself): the nearest folder whose hfs.json declares kind app; null when there is none. */
44
+ export function appRootOf(start) {
45
+ for (let dir = path.resolve(start);; dir = path.dirname(dir)) {
46
+ try {
47
+ const declared = JSON.parse(fs.readFileSync(path.join(dir, 'hfs.json'), 'utf8'));
48
+ if (declared.kind === 'app')
49
+ return dir;
50
+ }
51
+ catch { /* no declaration here: one folder up */ }
52
+ if (path.dirname(dir) === dir)
53
+ return null;
54
+ }
55
+ }
56
+ /** The pack names hfs.json `rulePacks` declares (its shape is judged by the declaration check). */
57
+ export function declaredRulePacks(appRoot) {
58
+ try {
59
+ const declared = JSON.parse(fs.readFileSync(path.join(appRoot, 'hfs.json'), 'utf8'));
60
+ return Array.isArray(declared.rulePacks) ? declared.rulePacks.filter((name) => typeof name === 'string') : [];
61
+ }
62
+ catch {
63
+ return [];
64
+ }
65
+ }
66
+ /** The problems of one rule entry of pack `pack` (whose folder is `root`), or the rule when it is sound. */
67
+ function judgeRule(pack, root, entry, at) {
68
+ const where = `rule ${String(at)}`;
69
+ if (!plain(entry))
70
+ return { problems: [`${where} is not an object`] };
71
+ const problems = [];
72
+ const extra = Object.keys(entry).filter((key) => !RULE_KEYS.has(key));
73
+ if (extra.length > 0)
74
+ problems.push(`${where} has ${extra.join(', ')}: a pack only adds rules, it never turns one off, overrides or lowers it (keys ${[...RULE_KEYS].join(', ')})`);
75
+ const id = text(entry['id']), code = text(entry['code']), spec = text(entry['spec']), doc = text(entry['doc']);
76
+ const label = id ?? where;
77
+ if (id === null || !ID.test(id))
78
+ problems.push(`${where}: id must be an upper-case law id such as NIVO-BLOCK-1`);
79
+ if (code === null || !CODE.test(code))
80
+ problems.push(`${label}: code must be an upper-case finding code such as NIVO_BLOCK_INCOMPLETE`);
81
+ const severity = entry['severity'];
82
+ if (severity !== 'error' && severity !== 'warning')
83
+ problems.push(`${label}: severity must be error or warning`);
84
+ const inPack = (file) => { const resolved = path.resolve(root, file); return resolved.startsWith(`${path.resolve(root)}${path.sep}`) && fs.existsSync(resolved); };
85
+ if (spec === null || !inPack(spec))
86
+ problems.push(`${label}: spec must name the file of the package that proves the rule (${spec ?? 'none'} is not there)`);
87
+ if (doc === null || !(/^https:\/\/\S+$/u.test(doc) || inPack(doc)))
88
+ problems.push(`${label}: doc must be a file of the package or an https link (${doc ?? 'none'})`);
89
+ const check = entry['check'];
90
+ const eslint = entry['eslint'];
91
+ if ((check === undefined) === (eslint === undefined))
92
+ problems.push(`${label}: a rule has exactly one engine, check (a machine rule of the app check) or eslint (a rule the canon factories load)`);
93
+ if (check !== undefined && typeof check !== 'function')
94
+ problems.push(`${label}: check must be a function (context) => findings`);
95
+ let lint;
96
+ if (eslint !== undefined) {
97
+ const name = plain(eslint) ? text(eslint['name']) : null;
98
+ const rule = plain(eslint) ? eslint['rule'] : undefined;
99
+ const sides = plain(eslint) && Array.isArray(eslint['sides']) ? eslint['sides'] : [];
100
+ if (name === null || !ESLINT_NAME.test(name))
101
+ problems.push(`${label}: eslint.name must be a kebab-case rule name`);
102
+ if (!plain(rule) || typeof rule['create'] !== 'function')
103
+ problems.push(`${label}: eslint.rule must be an ESLint rule module with create()`);
104
+ if (sides.length === 0 || sides.some((side) => !PACK_SIDES.includes(side)))
105
+ problems.push(`${label}: eslint.sides must name some of ${PACK_SIDES.join(', ')}`);
106
+ if (name !== null && plain(rule))
107
+ lint = { name, rule: rule, sides: sides };
108
+ }
109
+ if (problems.length > 0)
110
+ return { problems };
111
+ return { rule: { pack, id: id, code: code, severity: severity, spec: spec, doc: doc, ...(typeof check === 'function' ? { check: check } : {}), ...(lint === undefined ? {} : { eslint: lint }) }, problems: [] };
112
+ }
113
+ /**
114
+ * The rule packs of the app at `appRoot`, loaded through the app's own install (a pack is an ES module required synchronously, so a pack has no
115
+ * top-level await) and judged. `reserved` holds the codes the harness reports: a pack never reuses one.
116
+ */
117
+ export function loadRulePacks(appRoot, reserved = reservedCodes()) {
118
+ const result = { rules: [], problems: [] };
119
+ const names = declaredRulePacks(appRoot);
120
+ const ids = new Map(), codes = new Map();
121
+ const requireHere = createRequire(path.join(appRoot, 'package.json'));
122
+ for (const name of names) {
123
+ const fail = (message) => { result.problems.push({ pack: name, message }); };
124
+ if (!PACKAGE_NAME.test(name)) {
125
+ fail('is not a package name');
126
+ continue;
127
+ }
128
+ let manifest, root;
129
+ try {
130
+ root = path.dirname(requireHere.resolve(`${name}/package.json`));
131
+ const loaded = requireHere(`${name}/${RULE_PACK_ENTRY}`);
132
+ manifest = loaded.default ?? loaded;
133
+ }
134
+ catch (error) {
135
+ fail(`cannot be loaded from the app's install (${name}/${RULE_PACK_ENTRY}): ${String(error?.message ?? error).split('\n')[0]}`);
136
+ continue;
137
+ }
138
+ if (!plain(manifest) || manifest['schema'] !== RULE_PACK_SCHEMA) {
139
+ fail(`its ${RULE_PACK_ENTRY} export is not a ${RULE_PACK_SCHEMA} manifest`);
140
+ continue;
141
+ }
142
+ if (manifest['name'] !== name) {
143
+ fail(`its manifest names ${String(manifest['name'])}, not the package`);
144
+ continue;
145
+ }
146
+ const extra = Object.keys(manifest).filter((key) => !['schema', 'name', 'rules'].includes(key));
147
+ if (extra.length > 0) {
148
+ fail(`its manifest has ${extra.join(', ')}: a pack holds only schema, name and the rules it adds`);
149
+ continue;
150
+ }
151
+ const entries = Array.isArray(manifest['rules']) ? manifest['rules'] : [];
152
+ if (entries.length === 0) {
153
+ fail('adds no rule');
154
+ continue;
155
+ }
156
+ const judged = entries.map((entry, at) => judgeRule(name, root, entry, at));
157
+ const problems = judged.flatMap((one) => one.problems);
158
+ const sound = judged.flatMap((one) => (one.rule === undefined ? [] : [one.rule]));
159
+ for (const [at, rule] of sound.entries()) {
160
+ if (sound.findIndex((other) => other.id === rule.id) < at)
161
+ problems.push(`${rule.id}: the id is also a rule of ${name}`);
162
+ if (sound.findIndex((other) => other.code === rule.code) < at)
163
+ problems.push(`${rule.id}: ${rule.code} is also a code of ${name}`);
164
+ if (reserved.has(rule.code))
165
+ problems.push(`${rule.id}: ${rule.code} is a code the harness reports; a pack adds its own codes and never stands in for a harness rule`);
166
+ const otherId = ids.get(rule.id), otherCode = codes.get(rule.code);
167
+ if (otherId !== undefined)
168
+ problems.push(`${rule.id}: the id is also a rule of ${otherId}`);
169
+ if (otherCode !== undefined)
170
+ problems.push(`${rule.id}: ${rule.code} is also a code of ${otherCode}`);
171
+ }
172
+ if (problems.length > 0) {
173
+ for (const message of problems)
174
+ fail(message);
175
+ continue;
176
+ }
177
+ for (const rule of sound) {
178
+ ids.set(rule.id, name);
179
+ codes.set(rule.code, name);
180
+ result.rules.push(rule);
181
+ }
182
+ }
183
+ return result;
184
+ }
185
+ /** One plugin object per pack and rule set, so two blocks of one config that name a pack hand ESLint the same plugin. */
186
+ const plugins = new Map();
187
+ const pluginOf = (pack, rules) => {
188
+ const key = `${pack}|${rules.map((rule) => rule.id).join(',')}`;
189
+ let made = plugins.get(key);
190
+ if (made === undefined) {
191
+ made = { rules: Object.fromEntries(rules.map((rule) => [rule.eslint?.name, rule.eslint?.rule])) };
192
+ plugins.set(key, made);
193
+ }
194
+ return made;
195
+ };
196
+ /**
197
+ * The flat-config blocks that load the eslint rules of the app's packs for `side`, for a canon factory: one plugin per pack (named by the package)
198
+ * and each rule at its severity. Throws when a pack is refused: a lint run never guesses which of an app's laws hold.
199
+ */
200
+ export function packEslintConfigs(start, side, files = ['**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}']) {
201
+ const appRoot = appRootOf(start);
202
+ if (appRoot === null || declaredRulePacks(appRoot).length === 0)
203
+ return [];
204
+ const packs = loadRulePacks(appRoot);
205
+ if (packs.problems.length > 0)
206
+ throw new Error(`HFS_RULE_PACK_INVALID: ${packs.problems.map((problem) => `${problem.pack} ${problem.message}`).join('; ')} (hfs.json rulePacks, PROJECT-LINT-3)`);
207
+ const byPack = new Map();
208
+ for (const rule of packs.rules)
209
+ if (rule.eslint?.sides.includes(side))
210
+ byPack.set(rule.pack, [...(byPack.get(rule.pack) ?? []), rule]);
211
+ return [...byPack].map(([pack, rules]) => ({
212
+ files: [...files],
213
+ plugins: { [pack]: pluginOf(pack, rules) },
214
+ rules: Object.fromEntries(rules.map((rule) => [`${pack}/${rule.eslint?.name}`, rule.severity === 'error' ? 'error' : 'warn'])),
215
+ }));
216
+ }
217
+ /** The findings of the check rules of the app's packs over `files`, and one HFS_RULE_PACK_INVALID per refused pack or per rule that threw. */
218
+ export function rulePackFindings({ repoRoot, files, reserved, read }) {
219
+ const packs = loadRulePacks(repoRoot, reserved);
220
+ const out = packs.problems.map((problem) => ({ code: RULE_PACK_INVALID, level: 'error', path: 'hfs.json', message: `hfs.json rulePacks: ${problem.pack} ${problem.message} (R381, PROJECT-LINT-3)` }));
221
+ const context = Object.freeze({ repoRoot, files: Object.freeze([...files]), read });
222
+ for (const rule of packs.rules) {
223
+ if (rule.check === undefined)
224
+ continue;
225
+ let found;
226
+ try {
227
+ found = rule.check(context);
228
+ }
229
+ catch (error) {
230
+ out.push({ code: RULE_PACK_INVALID, level: 'error', path: 'hfs.json', message: `hfs.json rulePacks: ${rule.pack} ${rule.id} threw (${String(error?.message ?? error).split('\n')[0]}); a rule that cannot judge is no rule (R381)` });
231
+ continue;
232
+ }
233
+ for (const finding of Array.isArray(found) ? found : []) {
234
+ if (!plain(finding) || text(finding.path) === null || text(finding.message) === null) {
235
+ out.push({ code: RULE_PACK_INVALID, level: 'error', path: 'hfs.json', message: `hfs.json rulePacks: ${rule.pack} ${rule.id} returned a finding without a path and a message (R381)` });
236
+ continue;
237
+ }
238
+ out.push({ code: rule.code, level: rule.severity, path: String(finding.path), message: `${String(finding.message)} (${rule.id}, ${rule.doc})`, ...(typeof finding.line === 'number' ? { line: finding.line } : {}), ...(typeof finding.column === 'number' ? { column: finding.column } : {}) });
239
+ }
240
+ }
241
+ return out;
242
+ }
243
+ export const RULE_PACK_INVALID = 'HFS_RULE_PACK_INVALID';