@forwardimpact/libinvariant 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.
@@ -0,0 +1,487 @@
1
+ // The invariant authoring kit: the mechanism an invariant rule module needs to
2
+ // turn the repository into subjects and findings, so the module itself carries
3
+ // only policy. The engine injects a *build kit* into every module's `build`
4
+ // (and `seed`), and a *rule kit* into a module's `rules` when it is written as
5
+ // a function. Modules never import this file — the host (invariants.js) binds a
6
+ // kit per run and passes it in, the same way the rest of the monorepo threads
7
+ // the `runtime` bag instead of importing ambient collaborators.
8
+ //
9
+ // Filesystem and subprocess access route through the injected `runtime`
10
+ // (`runtime.fsSync`, `runtime.subprocess`) so this module — which lives under
11
+ // libraries/<pkg>/src — stays clean under the repo's own ambient-deps invariant.
12
+
13
+ import { isAbsolute, join, relative, resolve } from "node:path";
14
+
15
+ import { parse as acornParse } from "acorn";
16
+ import { parse as parseYaml } from "yaml";
17
+
18
+ import { buildSubjects, ENUM_DRIFT_RULES, seedBodies } from "./enum-drift.js";
19
+
20
+ // -- AST -----------------------------------------------------------------
21
+
22
+ /**
23
+ * Parse an ES module, wrapping acorn's error with the offending path.
24
+ *
25
+ * @param {string} source - Module source text.
26
+ * @param {string} filePath - Path used in parse-error messages.
27
+ * @param {{ locations?: boolean }} [options]
28
+ * @returns {object} The acorn AST.
29
+ */
30
+ export function parse(source, filePath, { locations = false } = {}) {
31
+ try {
32
+ return acornParse(source, {
33
+ ecmaVersion: "latest",
34
+ sourceType: "module",
35
+ locations,
36
+ allowAwaitOutsideFunction: true,
37
+ });
38
+ } catch (err) {
39
+ throw new Error(`failed to parse ${filePath}: ${err.message}`);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Depth-first visit of every typed node in an acorn AST.
45
+ *
46
+ * @param {object|object[]} node - AST node (or array of nodes).
47
+ * @param {(node: object) => void} visit - Called once per typed node.
48
+ */
49
+ export function walk(node, visit) {
50
+ if (!node || typeof node !== "object") return;
51
+ if (Array.isArray(node)) {
52
+ for (const child of node) walk(child, visit);
53
+ return;
54
+ }
55
+ if (typeof node.type !== "string") return;
56
+ visit(node);
57
+ for (const key of Object.keys(node)) {
58
+ if (key === "loc" || key === "start" || key === "end") continue;
59
+ walk(node[key], visit);
60
+ }
61
+ }
62
+
63
+ // -- Small pure utilities ------------------------------------------------
64
+
65
+ /**
66
+ * The 1-based line number a character offset falls on.
67
+ *
68
+ * @param {string} text - The source text.
69
+ * @param {number} offset - A character offset into `text`.
70
+ * @returns {number} The 1-based line number.
71
+ */
72
+ export function lineAt(text, offset) {
73
+ let line = 1;
74
+ for (let i = 0; i < offset && i < text.length; i++) {
75
+ if (text.charCodeAt(i) === 10) line++;
76
+ }
77
+ return line;
78
+ }
79
+
80
+ /**
81
+ * Compile a minimal path glob to a `RegExp`. `**` matches any path segments;
82
+ * `*` matches a non-slash run.
83
+ *
84
+ * @param {string} pattern - The glob.
85
+ * @returns {RegExp} An anchored regular expression.
86
+ */
87
+ export function glob(pattern) {
88
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
89
+ return new RegExp(
90
+ `^${escaped
91
+ .replace(/\*\*/g, "DOUBLESTAR")
92
+ .replace(/\*/g, "[^/]*")
93
+ .replace(/DOUBLESTAR/g, ".*")}$`,
94
+ );
95
+ }
96
+
97
+ // -- Filesystem walking (over runtime.fsSync) ----------------------------
98
+
99
+ function collectFiles(fsSync, dir, skip, match) {
100
+ const out = [];
101
+ if (!fsSync.existsSync(dir)) return out;
102
+ for (const entry of fsSync.readdirSync(dir)) {
103
+ if (skip.has(entry)) continue;
104
+ const full = join(dir, entry);
105
+ if (fsSync.statSync(full).isDirectory()) {
106
+ out.push(...collectFiles(fsSync, full, skip, match));
107
+ } else if (match(entry)) {
108
+ out.push(full);
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+
114
+ function readTextOrNull(fsSync, abs) {
115
+ try {
116
+ return fsSync.readFileSync(abs, "utf8");
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ // -- ripgrep (over runtime.subprocess.runSync) ---------------------------
123
+
124
+ function normalizePatterns(pattern, patterns) {
125
+ const list = patterns ?? (pattern === undefined ? [] : [pattern]);
126
+ return list.map((p) => (typeof p === "string" ? { pattern: p } : p));
127
+ }
128
+
129
+ function parseRgLine(raw) {
130
+ const i = raw.indexOf(":");
131
+ const j = raw.indexOf(":", i + 1);
132
+ return {
133
+ rel: raw.slice(0, i),
134
+ lineNo: Number.parseInt(raw.slice(i + 1, j), 10),
135
+ text: raw.slice(j + 1),
136
+ raw,
137
+ };
138
+ }
139
+
140
+ // Keep the first row per key. `dedupe` is `false`, `true` (key on the raw
141
+ // line), or a key function over the row.
142
+ function dedupeRows(rows, dedupe) {
143
+ if (!dedupe) return rows;
144
+ const keyOf = typeof dedupe === "function" ? dedupe : (m) => m.raw;
145
+ const seen = new Set();
146
+ return rows.filter((r) => {
147
+ const k = keyOf(r);
148
+ if (seen.has(k)) return false;
149
+ seen.add(k);
150
+ return true;
151
+ });
152
+ }
153
+
154
+ // A grep row carries `rel`/`raw` for dedupe; the subject keeps only the
155
+ // reportable fields (plus `reason` when the matching entry supplied one).
156
+ function toGrepSubject({ path, lineNo, text, reason }) {
157
+ const subject = { path, lineNo, text };
158
+ if (reason !== undefined) subject.reason = reason;
159
+ return subject;
160
+ }
161
+
162
+ // -- The build kit -------------------------------------------------------
163
+
164
+ /**
165
+ * Build the kit injected into a rule module's `build` and `seed`. Every
166
+ * collaborator is bound to `root` (the repository root), `dir` (the module's
167
+ * own directory, for co-located config), and `runtime` (the ambient bag).
168
+ *
169
+ * @param {{ root: string, dir: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
170
+ * @returns {object} The build kit.
171
+ */
172
+ export function createBuildKit({ root, dir, runtime }) {
173
+ const { fsSync, subprocess } = runtime;
174
+ const abs = (p) => (isAbsolute(p) ? p : resolve(root, p));
175
+
176
+ /**
177
+ * Collect files under one or more directories as subjects.
178
+ *
179
+ * @param {object} options
180
+ * @param {string[]} options.dirs - Root directories, relative to the repo.
181
+ * @param {(name: string) => boolean} options.match - File-name predicate.
182
+ * @param {Iterable<string>} [options.skip] - Directory names to prune.
183
+ * @param {string} [options.under] - Restrict to `<dir>/<child>/<under>/**`,
184
+ * the per-package `src`/`test` shape.
185
+ * @param {boolean} [options.read] - Attach file `text` (default true).
186
+ * @returns {Array<{ path: string, rel: string, text?: string }>}
187
+ */
188
+ function scan({ dirs, match, skip = [], under, read = true }) {
189
+ const skipSet = new Set(skip);
190
+ const files = [];
191
+ for (const d of dirs) {
192
+ const base = resolve(root, d);
193
+ const roots = under
194
+ ? (fsSync.existsSync(base) ? fsSync.readdirSync(base) : []).map((n) =>
195
+ join(base, n, under),
196
+ )
197
+ : [base];
198
+ for (const r of roots)
199
+ files.push(...collectFiles(fsSync, r, skipSet, match));
200
+ }
201
+ return files.map((path) => {
202
+ const subject = { path, rel: relative(root, path) };
203
+ if (read) subject.text = readTextOrNull(fsSync, path) ?? "";
204
+ return subject;
205
+ });
206
+ }
207
+
208
+ /**
209
+ * Like `scan`, but parse each file and merge `extract(ast)` into the subject.
210
+ * A file that fails to parse becomes `{ path, rel, parseError }` instead, so
211
+ * the module pairs it with the rule kit's `parseError(scope, …)`.
212
+ *
213
+ * @param {object} options - `scan` options plus the two below.
214
+ * @param {(ast: object) => object} options.extract - Subject fields from the AST.
215
+ * @param {boolean} [options.locations] - Pass `locations` to the parser.
216
+ * @returns {Array<object>}
217
+ */
218
+ function scanAst({ extract, locations = false, ...scanOpts }) {
219
+ return scan({ ...scanOpts, read: true }).map(({ path, rel, text }) => {
220
+ try {
221
+ return { path, rel, ...extract(parse(text, rel, { locations })) };
222
+ } catch (err) {
223
+ return { path, rel, parseError: err.message };
224
+ }
225
+ });
226
+ }
227
+
228
+ function assertRg() {
229
+ if (subprocess.runSync("rg", ["--version"]).exitCode !== 0) {
230
+ throw new Error("ripgrep (rg) is required by the invariant rule modules");
231
+ }
232
+ }
233
+
234
+ function rgOnce({ pattern, paths, globs, caseSensitive, onlyMatching }) {
235
+ const args = [
236
+ "--hidden",
237
+ "--no-messages",
238
+ "--line-number",
239
+ "--color",
240
+ "never",
241
+ ];
242
+ if (!caseSensitive) args.push("-i");
243
+ if (onlyMatching) args.push("--only-matching");
244
+ for (const g of globs) args.push("--glob", g);
245
+ args.push("-e", pattern, ...paths);
246
+ const { stdout, exitCode } = subprocess.runSync("rg", args, { cwd: root });
247
+ if (exitCode === 2)
248
+ throw new Error(`ripgrep failed for pattern: ${pattern}`);
249
+ return (stdout || "").split("\n").filter(Boolean).map(parseRgLine);
250
+ }
251
+
252
+ /**
253
+ * Scan the repo with ripgrep and return matches as subjects. Accepts one
254
+ * `pattern` or a list of `patterns` (strings, or `{ pattern, reason?, globs?,
255
+ * caseSensitive?, onlyMatching?, exclude? }`); per-entry options override the
256
+ * call defaults, and a per-entry `exclude` RegExp drops matches whose raw
257
+ * line it tests true (a false-positive filter). `dedupe` is `false`, `true`
258
+ * (key on the raw line), or a key function over `{ path, rel, lineNo, text,
259
+ * raw, reason }`.
260
+ *
261
+ * Each subject is `{ path, lineNo, text }`, plus `reason` when the matching
262
+ * entry carries one. The repo-relative `rel` and full `raw` line are
263
+ * available to the `dedupe` key function but are not part of the subject.
264
+ *
265
+ * @param {object} options
266
+ * @returns {Array<{ path: string, lineNo: number, text: string, reason?: string }>}
267
+ */
268
+ function grep({
269
+ pattern,
270
+ patterns,
271
+ paths = ["."],
272
+ globs = [],
273
+ caseSensitive = false,
274
+ onlyMatching = false,
275
+ dedupe = false,
276
+ }) {
277
+ assertRg();
278
+ const rows = [];
279
+ for (const entry of normalizePatterns(pattern, patterns)) {
280
+ const matches = rgOnce({
281
+ pattern: entry.pattern,
282
+ paths,
283
+ globs: [...globs, ...(entry.globs ?? [])],
284
+ caseSensitive: entry.caseSensitive ?? caseSensitive,
285
+ onlyMatching: entry.onlyMatching ?? onlyMatching,
286
+ });
287
+ for (const m of matches) {
288
+ if (entry.exclude && entry.exclude.test(m.raw)) continue;
289
+ rows.push({ ...m, path: resolve(root, m.rel), reason: entry.reason });
290
+ }
291
+ }
292
+ return dedupeRows(rows, dedupe).map(toGrepSubject);
293
+ }
294
+
295
+ /**
296
+ * Read a repo file's text (path relative to the repo root, or absolute).
297
+ *
298
+ * @param {string} path
299
+ * @returns {string|null} The text, or `null` when missing.
300
+ */
301
+ function readText(path) {
302
+ return readTextOrNull(fsSync, abs(path));
303
+ }
304
+
305
+ /**
306
+ * Read and parse a repo JSON file, returning `null` when missing or invalid.
307
+ *
308
+ * @param {string} path - Relative to the repo root, or absolute.
309
+ * @returns {object|null}
310
+ */
311
+ function readJson(path) {
312
+ const text = readTextOrNull(fsSync, abs(path));
313
+ if (text == null) return null;
314
+ try {
315
+ return JSON.parse(text);
316
+ } catch {
317
+ return null;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Read a config file co-located with the rule module (`<dir>/<name>`),
323
+ * parsed by extension (`.json` / `.yml` / `.yaml`). Returns `fallback` when
324
+ * the file is missing, empty, or unparseable.
325
+ *
326
+ * @param {string} name - File name beside the module.
327
+ * @param {*} [fallback] - Value when absent or unreadable (default `null`).
328
+ * @returns {*}
329
+ */
330
+ function config(name, fallback = null) {
331
+ const text = readTextOrNull(fsSync, join(dir, name));
332
+ if (text == null || text.trim() === "") return fallback;
333
+ try {
334
+ const parsed = name.endsWith(".json")
335
+ ? JSON.parse(text)
336
+ : parseYaml(text);
337
+ return parsed ?? fallback;
338
+ } catch {
339
+ return fallback;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * The shared "single source restated across consumers" check. For every
345
+ * registry `entry` (`{ key, expected, consumers: [{ path, pattern }] }`),
346
+ * scan each consumer file line by line for `pattern` and emit one subject
347
+ * per match: the restated value (capture group 1, else the whole match,
348
+ * trimmed) paired with the entry's `expected` value and an `ok` verdict from
349
+ * `equal(restated, expected, key)`. The module supplies the domain pieces
350
+ * (how `expected` is computed, what `equal` means); the kit owns the scan.
351
+ *
352
+ * Native line-by-line matching, not ripgrep: the surfaces carry URLs and
353
+ * other colon-bearing values that ripgrep's single-file output corrupts, and
354
+ * look-around is sometimes needed.
355
+ *
356
+ * @param {object} options
357
+ * @param {Array<{ key: string, expected: *, consumers: Array<{ path: string, pattern: RegExp|string }> }>} options.entries
358
+ * @param {(restated: string, expected: *, key: string) => boolean} options.equal
359
+ * @returns {Array<{ key: string, path: string, lineNo: number, restated: string, expected: *, ok: boolean }>}
360
+ */
361
+ function restatementDrift({ entries, equal }) {
362
+ const subjects = [];
363
+ for (const { key, expected, consumers } of entries) {
364
+ for (const consumer of consumers) {
365
+ const text = readTextOrNull(fsSync, abs(consumer.path));
366
+ if (text == null) continue;
367
+ const re =
368
+ typeof consumer.pattern === "string"
369
+ ? new RegExp(consumer.pattern)
370
+ : consumer.pattern;
371
+ text.split("\n").forEach((line, i) => {
372
+ const m = line.match(re);
373
+ if (!m) return;
374
+ const restated = (m[1] ?? m[0]).trim();
375
+ subjects.push({
376
+ key,
377
+ path: consumer.path,
378
+ lineNo: i + 1,
379
+ restated,
380
+ expected,
381
+ ok: equal(restated, expected, key),
382
+ });
383
+ });
384
+ }
385
+ }
386
+ return subjects;
387
+ }
388
+
389
+ /**
390
+ * List the entries of a repo directory by name, returning `[]` when missing.
391
+ *
392
+ * @param {string} path - Relative to the repo root, or absolute.
393
+ * @param {{ dirsOnly?: boolean, filesOnly?: boolean }} [options]
394
+ * @returns {string[]}
395
+ */
396
+ function listDir(path, { dirsOnly = false, filesOnly = false } = {}) {
397
+ let entries;
398
+ try {
399
+ entries = fsSync.readdirSync(abs(path), { withFileTypes: true });
400
+ } catch {
401
+ return [];
402
+ }
403
+ return entries
404
+ .filter((e) =>
405
+ dirsOnly ? e.isDirectory() : filesOnly ? e.isFile() : true,
406
+ )
407
+ .map((e) => e.name);
408
+ }
409
+
410
+ // The enumeration-drift engine, bound to this run's root and filesystem. A
411
+ // rule module passes its parsed registry (e.g. `config(topicsFile)`) to
412
+ // `build`/`seed`; the matching rule set is on the rule kit as
413
+ // `enumDriftRules`.
414
+ const enumDrift = {
415
+ build: (registry) => buildSubjects({ registry, root, fsSync }),
416
+ seed: (registry) => seedBodies({ registry, root, fsSync }),
417
+ };
418
+
419
+ return {
420
+ root,
421
+ dir,
422
+ runtime,
423
+ scan,
424
+ scanAst,
425
+ parse,
426
+ walk,
427
+ grep,
428
+ restatementDrift,
429
+ enumDrift,
430
+ readText,
431
+ readJson,
432
+ config,
433
+ listDir,
434
+ lineAt,
435
+ glob,
436
+ };
437
+ }
438
+
439
+ // -- The rule kit --------------------------------------------------------
440
+
441
+ /**
442
+ * Helpers a rule module receives when it exports `rules` as a function. They
443
+ * build the two recurring rule shapes so the module declares only policy.
444
+ */
445
+ export const RULE_KIT = {
446
+ /**
447
+ * The enumeration-drift rule set, paired with the build kit's `enumDrift`. A
448
+ * rule module that delegates to `kit.enumDrift` exposes these via
449
+ * `rules: (kit) => kit.enumDriftRules`.
450
+ */
451
+ enumDriftRules: ENUM_DRIFT_RULES,
452
+
453
+ /**
454
+ * The standard parse-error rule: fails any subject carrying a `parseError`
455
+ * string (as produced by the build kit's `scanAst`).
456
+ *
457
+ * @param {string} scope - The subject scope to guard.
458
+ * @param {{ id?: string, hint?: string }} [options]
459
+ * @returns {object} A rule for the rules engine.
460
+ */
461
+ parseError(scope, { id = `${scope}.parse-error`, hint } = {}) {
462
+ return {
463
+ id,
464
+ scope,
465
+ severity: "fail",
466
+ check: (s) => (s.parseError ? { msg: s.parseError } : null),
467
+ message: (_s, r) => r.msg,
468
+ hint: hint ?? "fix the syntax error so the file can be parsed",
469
+ };
470
+ },
471
+
472
+ /**
473
+ * A rule that fails every subject in `scope` (optionally gated by `when`).
474
+ * The build step has already decided each subject is a violation; the rule
475
+ * only renders it.
476
+ *
477
+ * @param {string} scope
478
+ * @param {{ id: string, message: (s: object, r: object, c: object) => string, hint?: string, when?: (s: object, c: object) => boolean }} options
479
+ * @returns {object} A rule for the rules engine.
480
+ */
481
+ failAll(scope, { id, message, hint, when }) {
482
+ const rule = { id, scope, severity: "fail", check: () => ({}), message };
483
+ if (hint !== undefined) rule.hint = hint;
484
+ if (when !== undefined) rule.when = when;
485
+ return rule;
486
+ },
487
+ };
@@ -0,0 +1,164 @@
1
+ import { resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import * as yaml from "yaml";
4
+ import * as acorn from "acorn";
5
+ import { LIBCLI_IS_COMPILED } from "@forwardimpact/libcli";
6
+ import { runRules } from "@forwardimpact/libutil";
7
+ import { createBuildKit, RULE_KIT } from "./invariant-kit.js";
8
+
9
+ // Rule modules are imported dynamically at runtime, so a compiled binary cannot
10
+ // bundle their bare imports, and the standalone executable has no node_modules
11
+ // to resolve them from — a rule module's `import "yaml"` would fail. Expose the
12
+ // third-party packages libinvariant already bundles as virtual modules, so a
13
+ // compiled rule module resolves them to the embedded copies. Under node/bunx
14
+ // this is a no-op: node_modules resolves them normally. A rule module that
15
+ // imports a package beyond this set must run via the package, not the binary.
16
+ let bundledRuleDepsRegistered = false;
17
+ function registerBundledRuleDeps() {
18
+ if (bundledRuleDepsRegistered) return;
19
+ // Only the standalone binary needs this; node/bunx resolve from node_modules.
20
+ if (!LIBCLI_IS_COMPILED || typeof Bun === "undefined") {
21
+ return;
22
+ }
23
+ Bun.plugin({
24
+ name: "invariant-rule-deps",
25
+ setup(build) {
26
+ build.module("yaml", () => ({ exports: yaml, loader: "object" }));
27
+ build.module("acorn", () => ({ exports: acorn, loader: "object" }));
28
+ },
29
+ });
30
+ bundledRuleDepsRegistered = true;
31
+ }
32
+
33
+ /**
34
+ * Resolve the root whose rules directory applies to the working directory.
35
+ * The nearest `package.json` is not enough — inside a monorepo every
36
+ * workspace package has one — so search upward for the caller-supplied
37
+ * rules directory itself, falling back to the nearest project root so the
38
+ * loader's error names the expected location.
39
+ *
40
+ * @param {import('@forwardimpact/libutil/runtime').Runtime} runtime
41
+ * @param {string} rulesDir - Rules directory relative to the project root.
42
+ * @returns {string} Project root directory path.
43
+ */
44
+ export function findInvariantsRoot(runtime, rulesDir) {
45
+ const found = runtime.finder.findUpward(runtime.proc.cwd(), rulesDir, 8);
46
+ if (!found) return runtime.finder.findProjectRoot();
47
+ // Climb back out of the found rules directory — one level per segment of
48
+ // the caller-supplied path — to land on the project root that contains it.
49
+ const climb = rulesDir
50
+ .split("/")
51
+ .filter(Boolean)
52
+ .map(() => "..");
53
+ return resolve(found, ...climb);
54
+ }
55
+
56
+ // Generic host for repo-local invariant rule modules. A rule module is a
57
+ // `*.rules.mjs` (or `*.rules.js`) file whose default export is:
58
+ //
59
+ // {
60
+ // name: "ambient-deps",
61
+ // build: async ({ root, runtime }) =>
62
+ // ({ subjects: { "<scope>": [subject, …] }, ctx? }),
63
+ // rules: [{ id, scope, severity, when?, check, message, hint? }, …],
64
+ // seed?: async ({ root, runtime }) => "text", // e.g. a refreshed deny-list
65
+ // }
66
+ //
67
+ // `build` walks the repo and returns plain subjects per scope; `rules` are the
68
+ // declarative checks `runRules` applies over them. The repository owns its
69
+ // rule modules — this host only discovers, loads, and runs them, so the
70
+ // policies themselves never ship with the CLI.
71
+
72
+ function assertModuleShape(mod, fileName) {
73
+ const ok =
74
+ mod &&
75
+ typeof mod.name === "string" &&
76
+ typeof mod.build === "function" &&
77
+ (Array.isArray(mod.rules) || typeof mod.rules === "function");
78
+ if (!ok) {
79
+ throw new Error(
80
+ `${fileName}: default export must be { name, build, rules } (rules is an array or a (ruleKit) => array)`,
81
+ );
82
+ }
83
+ }
84
+
85
+ // A module's rules are either a static array or a `(ruleKit) => array` factory
86
+ // that builds them from the shared rule helpers.
87
+ function resolveRules(mod) {
88
+ return typeof mod.rules === "function" ? mod.rules(RULE_KIT) : mod.rules;
89
+ }
90
+
91
+ /**
92
+ * Discover and import every rule module under `rulesDir` (sorted by file
93
+ * name for a stable run order).
94
+ *
95
+ * @param {{ root: string, rulesDir: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
96
+ * `rulesDir` is the rules directory relative to `root`, supplied by the
97
+ * caller (the library carries no discovery default).
98
+ * @returns {Promise<object[]>} The modules' default exports.
99
+ */
100
+ export async function loadRuleModules({ root, rulesDir, runtime }) {
101
+ const dir = resolve(root, rulesDir);
102
+ let entries;
103
+ try {
104
+ entries = await runtime.fs.readdir(dir, { withFileTypes: true });
105
+ } catch {
106
+ throw new Error(`rules directory not found: ${dir}`);
107
+ }
108
+ const names = entries
109
+ .filter((e) => e.isFile() && /\.rules\.m?js$/.test(e.name))
110
+ .map((e) => e.name)
111
+ .sort();
112
+ if (names.length === 0) {
113
+ throw new Error(`no *.rules.mjs modules found in ${dir}`);
114
+ }
115
+ registerBundledRuleDeps();
116
+ const modules = [];
117
+ for (const name of names) {
118
+ const mod = (await import(pathToFileURL(resolve(dir, name)).href)).default;
119
+ assertModuleShape(mod, name);
120
+ modules.push(mod);
121
+ }
122
+ return modules;
123
+ }
124
+
125
+ /**
126
+ * Run already-loaded rule modules: inject the build kit, build each module's
127
+ * subjects, then apply its rule catalogue through the shared rules engine.
128
+ *
129
+ * @param {object[]} modules - Rule-module default exports.
130
+ * @param {{ root: string, runtime: import('@forwardimpact/libutil/runtime').Runtime, dir: string }} options
131
+ * `dir` is the modules' directory (for co-located config), supplied by
132
+ * the caller alongside the rules it loaded.
133
+ * @returns {Promise<object[]>} Structured findings; empty when conformant.
134
+ */
135
+ export async function runRuleModules(modules, { root, runtime, dir }) {
136
+ const findings = [];
137
+ for (const mod of modules) {
138
+ const kit = createBuildKit({ root, dir, runtime });
139
+ const { subjects, ctx = {} } = await mod.build(kit);
140
+ findings.push(
141
+ ...runRules(
142
+ resolveRules(mod),
143
+ { ...ctx, subjects },
144
+ { resolveScope: (key, c) => c.subjects[key] ?? [] },
145
+ ),
146
+ );
147
+ }
148
+ return findings;
149
+ }
150
+
151
+ /**
152
+ * Load every rule module under `root`/`rulesDir` and run it.
153
+ *
154
+ * @param {{ root: string, rulesDir: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
155
+ * @returns {Promise<object[]>} Structured findings; empty when conformant.
156
+ * Each finding is `{ id, level, path, lineNo?, message, hint? }` for use
157
+ * with `emitFindingsText` / `emitFindingsJson` from libutil.
158
+ */
159
+ export async function checkInvariants({ root, rulesDir, runtime }) {
160
+ if (!runtime) throw new Error("runtime is required");
161
+ const dir = resolve(root, rulesDir);
162
+ const modules = await loadRuleModules({ root, rulesDir, runtime });
163
+ return runRuleModules(modules, { root, runtime, dir });
164
+ }