@gobing-ai/ts-rule-engine 0.2.7 → 0.2.9

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 (54) hide show
  1. package/README.md +565 -1
  2. package/dist/config/extensions.d.ts +7 -4
  3. package/dist/config/extensions.d.ts.map +1 -1
  4. package/dist/config/extensions.js +11 -6
  5. package/dist/config/loader.d.ts +29 -2
  6. package/dist/config/loader.d.ts.map +1 -1
  7. package/dist/config/loader.js +104 -34
  8. package/dist/engine.d.ts +8 -1
  9. package/dist/engine.d.ts.map +1 -1
  10. package/dist/engine.js +9 -19
  11. package/dist/evaluators/coverage-gate-evaluator.js +12 -3
  12. package/dist/evaluators/file-utils.d.ts +55 -0
  13. package/dist/evaluators/file-utils.d.ts.map +1 -1
  14. package/dist/evaluators/file-utils.js +49 -0
  15. package/dist/evaluators/forbidden-import-evaluator.d.ts +5 -0
  16. package/dist/evaluators/forbidden-import-evaluator.d.ts.map +1 -1
  17. package/dist/evaluators/forbidden-import-evaluator.js +14 -17
  18. package/dist/evaluators/import-boundary-evaluator.d.ts +5 -0
  19. package/dist/evaluators/import-boundary-evaluator.d.ts.map +1 -1
  20. package/dist/evaluators/import-boundary-evaluator.js +45 -15
  21. package/dist/evaluators/regex-evaluator.d.ts +9 -1
  22. package/dist/evaluators/regex-evaluator.d.ts.map +1 -1
  23. package/dist/evaluators/regex-evaluator.js +43 -14
  24. package/dist/evaluators/secrets-scanner-evaluator.d.ts +5 -0
  25. package/dist/evaluators/secrets-scanner-evaluator.d.ts.map +1 -1
  26. package/dist/evaluators/secrets-scanner-evaluator.js +13 -13
  27. package/dist/evaluators/tsdoc-export-evaluator.d.ts.map +1 -1
  28. package/dist/evaluators/tsdoc-export-evaluator.js +9 -11
  29. package/dist/formatters/json.d.ts.map +1 -1
  30. package/dist/formatters/json.js +2 -0
  31. package/dist/formatters/text.d.ts.map +1 -1
  32. package/dist/formatters/text.js +2 -0
  33. package/dist/resolvers/test-path-resolver.d.ts.map +1 -1
  34. package/dist/resolvers/test-path-resolver.js +5 -0
  35. package/dist/types.d.ts +28 -3
  36. package/dist/types.d.ts.map +1 -1
  37. package/dist/types.js +37 -9
  38. package/package.json +6 -3
  39. package/schemas/preset.schema.json +54 -0
  40. package/schemas/rule-file.schema.json +49 -0
  41. package/src/config/extensions.ts +16 -8
  42. package/src/config/loader.ts +151 -34
  43. package/src/engine.ts +9 -19
  44. package/src/evaluators/coverage-gate-evaluator.ts +15 -5
  45. package/src/evaluators/file-utils.ts +92 -0
  46. package/src/evaluators/forbidden-import-evaluator.ts +14 -19
  47. package/src/evaluators/import-boundary-evaluator.ts +56 -40
  48. package/src/evaluators/regex-evaluator.ts +43 -13
  49. package/src/evaluators/secrets-scanner-evaluator.ts +13 -14
  50. package/src/evaluators/tsdoc-export-evaluator.ts +10 -9
  51. package/src/formatters/json.ts +2 -0
  52. package/src/formatters/text.ts +2 -0
  53. package/src/resolvers/test-path-resolver.ts +5 -0
  54. package/src/types.ts +45 -9
@@ -1,7 +1,7 @@
1
- import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path';
2
- import { NodeFileSystem } from '@gobing-ai/ts-runtime';
3
- import { parse } from 'yaml';
1
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
2
+ import { loadStructuredConfig, NodeFileSystem } from '@gobing-ai/ts-runtime';
4
3
  import { ConstraintRuleFileSchema, ConstraintRuleSchema, PresetDefinitionSchema, } from '../types.js';
4
+ import { collectExtensions } from './extensions.js';
5
5
  /**
6
6
  * Load and normalize a preset by name, resolving across one or more rule roots.
7
7
  *
@@ -9,59 +9,111 @@ import { ConstraintRuleFileSchema, ConstraintRuleSchema, PresetDefinitionSchema,
9
9
  * so a caller can layer project-local rules over shared/global rules and inherit
10
10
  * the rest of a preset's categories from the lower-priority roots.
11
11
  */
12
- export async function loadPresetRules(name, options) {
12
+ export async function loadPreset(name, options) {
13
13
  const merged = await buildMergedRoots(options.roots.map((root) => resolve(root)));
14
14
  const presetPath = findMergedPreset(merged, name);
15
15
  if (presetPath === null)
16
- return [];
17
- const preset = PresetDefinitionSchema.parse(await readStructuredFile(presetPath));
16
+ return { rules: [], extensions: [] };
17
+ const preset = PresetDefinitionSchema.parse(await readStructuredFile(presetPath, options));
18
18
  const rules = [];
19
+ const extensions = collectExtensions(preset.name, dirname(presetPath), preset.extensions);
19
20
  for (const entry of preset.extends) {
20
- rules.push(...(await loadPresetEntry(merged, entry, new Set([name]))));
21
+ const loaded = await loadPresetEntry(merged, entry, new Set([name]), options);
22
+ rules.push(...loaded.rules);
23
+ extensions.push(...loaded.extensions);
21
24
  }
22
- const disabled = new Set(preset.disable ?? []);
23
- const normalized = rules.filter((rule) => !disabled.has(rule.id));
24
- for (const rule of normalized) {
25
- const override = preset.overrides?.[rule.id];
25
+ return { rules: applyPresetControls(preset.name, rules, preset.disable, preset.overrides), extensions };
26
+ }
27
+ /** Collapse rules sharing an id to a single entry; later definitions win (last-wins merge). */
28
+ function dedupeById(rules) {
29
+ const byId = new Map();
30
+ for (const rule of rules)
31
+ byId.set(rule.id, rule);
32
+ return [...byId.values()];
33
+ }
34
+ /** Apply a preset's local disable and override controls after composing its children. */
35
+ function applyPresetControls(presetName, rules, disabledIds, overrides) {
36
+ const disabled = new Set(disabledIds ?? []);
37
+ const controlled = dedupeById(rules).filter((rule) => !disabled.has(rule.id));
38
+ for (const rule of controlled) {
39
+ const override = overrides?.[rule.id];
26
40
  if (override?.fix !== undefined) {
41
+ assertFixModeNotPromoted(presetName, rule, override.fix.mode);
27
42
  rule.fix = { ...(rule.fix ?? { mode: 'none' }), ...override.fix };
28
43
  }
29
44
  }
30
- return normalized;
45
+ return controlled;
46
+ }
47
+ /** Fix-mode authority ordering; an override may lower but never raise a rule's mode. */
48
+ const FIX_MODE_AUTHORITY = { none: 0, suggest: 1, auto: 2 };
49
+ /** Throw when a preset override would escalate a rule's fix authority above its authored level. */
50
+ function assertFixModeNotPromoted(presetName, rule, overrideMode) {
51
+ const ruleMode = rule.fix?.mode ?? 'none';
52
+ if (FIX_MODE_AUTHORITY[overrideMode] > FIX_MODE_AUTHORITY[ruleMode]) {
53
+ throw new Error(`Preset "${presetName}" override for rule "${rule.id}" raises fix mode from "${ruleMode}" to "${overrideMode}"; overrides may only lower fix authority`);
54
+ }
31
55
  }
32
- /** Load a direct rule file from disk. */
33
- export async function loadRuleFile(filePath) {
34
- return normalizeRuleFile(await readStructuredFile(resolve(filePath)), dirname(resolve(filePath)));
56
+ export async function loadPresetRules(name, options) {
57
+ return (await loadPreset(name, options)).rules;
58
+ }
59
+ /**
60
+ * Load a direct rule file from disk.
61
+ *
62
+ * Returns the normalized rules plus any extension modules the file declares in an
63
+ * `extensions` block, resolved to absolute paths. Rule-file extensions are treated
64
+ * exactly like preset extensions — pass the refs to {@link loadExtensionsIntoHost},
65
+ * which enforces the same `allowExtensions` trust gate. A single-rule file (one rule
66
+ * object, not a `rules:` array) cannot declare extensions and yields `extensions: []`.
67
+ */
68
+ export async function loadRuleFile(filePath, options = {}) {
69
+ const resolved = resolve(filePath);
70
+ const raw = await readStructuredFile(resolved, options);
71
+ const rules = normalizeRuleFile(raw, resolved);
72
+ const parsed = ConstraintRuleFileSchema.safeParse(raw);
73
+ const extensions = parsed.success
74
+ ? collectExtensions(basename(resolved), dirname(resolved), parsed.data.extensions)
75
+ : [];
76
+ return { rules, extensions };
35
77
  }
36
- async function loadPresetEntry(merged, entry, seen) {
78
+ async function loadPresetEntry(merged, entry, seen, options) {
37
79
  // Sub-preset reference — recurse, erroring on a genuine cycle.
38
80
  const presetPath = findMergedPreset(merged, entry);
39
81
  if (presetPath !== null) {
40
82
  if (seen.has(entry)) {
41
83
  throw new Error(`Circular preset dependency detected: ${[...seen, entry].join(' → ')}`);
42
84
  }
43
- seen.add(entry);
44
- const preset = PresetDefinitionSchema.safeParse(await readStructuredFile(presetPath));
85
+ const nextSeen = new Set([...seen, entry]);
86
+ const preset = PresetDefinitionSchema.safeParse(await readStructuredFile(presetPath, options));
45
87
  if (preset.success) {
46
88
  const rules = [];
47
- for (const child of preset.data.extends)
48
- rules.push(...(await loadPresetEntry(merged, child, seen)));
49
- return rules.filter((rule) => !(preset.data.disable ?? []).includes(rule.id));
89
+ const extensions = collectExtensions(preset.data.name, dirname(presetPath), preset.data.extensions);
90
+ for (const child of preset.data.extends) {
91
+ const loaded = await loadPresetEntry(merged, child, nextSeen, options);
92
+ rules.push(...loaded.rules);
93
+ extensions.push(...loaded.extensions);
94
+ }
95
+ return {
96
+ rules: applyPresetControls(preset.data.name, rules, preset.data.disable, preset.data.overrides),
97
+ extensions,
98
+ };
50
99
  }
51
100
  }
52
101
  // Category folder reference — load every winning file under that prefix.
53
102
  if (merged.categories.has(entry)) {
54
103
  const rules = [];
55
104
  for (const absPath of mergedFilesInCategory(merged, entry)) {
56
- rules.push(...(await loadRuleFile(absPath)));
105
+ rules.push(...normalizeRuleFile(await readStructuredFile(absPath, options), absPath));
57
106
  }
58
- return rules;
107
+ return { rules, extensions: [] };
59
108
  }
60
109
  // Sub-path reference — a single winning rule file within a category.
61
110
  const subPath = findMergedFile(merged, entry);
62
111
  if (subPath !== null)
63
- return loadRuleFile(subPath);
64
- return [];
112
+ return {
113
+ rules: normalizeRuleFile(await readStructuredFile(subPath, options), subPath),
114
+ extensions: [],
115
+ };
116
+ return { rules: [], extensions: [] };
65
117
  }
66
118
  /**
67
119
  * Build the merged view across ordered roots.
@@ -155,27 +207,45 @@ async function listImmediateDirs(fs, dir) {
155
207
  }
156
208
  return dirs;
157
209
  }
158
- async function readStructuredFile(path) {
159
- const content = await new NodeFileSystem().readFile(path);
160
- return extname(path) === '.json' ? JSON.parse(content) : parse(content);
210
+ async function readStructuredFile(path, options = {}) {
211
+ return await loadStructuredConfig(path, {
212
+ validateSchema: options.validateSchema,
213
+ fetch: options.fetch,
214
+ });
161
215
  }
162
- function normalizeRuleFile(raw, sourceDir) {
216
+ function normalizeRuleFile(raw, filePath) {
217
+ const sourceDir = dirname(filePath);
163
218
  const maybeFile = ConstraintRuleFileSchema.safeParse(raw);
164
219
  if (maybeFile.success)
165
220
  return normalizeFileRules(maybeFile.data, sourceDir);
166
221
  const maybeRule = ConstraintRuleSchema.safeParse(raw);
167
222
  if (maybeRule.success)
168
- return [normalizeRule(maybeRule.data, {}, sourceDir)];
169
- throw new Error(`Invalid rule file: ${basename(sourceDir)}`);
223
+ return [normalizeRule(maybeRule.data, sourceDir)];
224
+ // Surface the schema diagnostics that best fit the input: a `rules:` array means
225
+ // the author intended a rule file, so report against that schema; otherwise the
226
+ // single-rule schema. Include field paths so the offending key is obvious.
227
+ const isRuleFileShape = typeof raw === 'object' && raw !== null && 'rules' in raw;
228
+ const issues = (isRuleFileShape ? maybeFile.error : maybeRule.error).issues;
229
+ throw new Error(`Invalid rule file "${basename(filePath)}": ${formatIssues(issues)}`);
230
+ }
231
+ /** Render Zod issues as `path: message` fragments for actionable diagnostics. */
232
+ function formatIssues(issues) {
233
+ return issues
234
+ .map((issue) => {
235
+ const path = issue.path.map(String).join('.');
236
+ return path.length > 0 ? `${path}: ${issue.message}` : issue.message;
237
+ })
238
+ .join('; ');
170
239
  }
171
240
  function normalizeFileRules(file, sourceDir) {
172
241
  return file.rules.map((rule) => normalizeRule({
173
242
  ...rule,
174
- severity: rule.severity ?? file.severity ?? 'error',
243
+ // Rule-level severity wins, then the file-level default, then 'error'.
244
+ severity: rule.severity ?? file.severity,
175
245
  include: rule.include ?? file.include,
176
246
  // File-level excludes always apply; a rule's own excludes add to (not replace) them.
177
247
  exclude: mergeExcludes(file.exclude, rule.exclude),
178
- }, {}, sourceDir));
248
+ }, sourceDir));
179
249
  }
180
250
  /** Union of file-level and rule-level excludes, de-duplicated. Returns undefined when both empty. */
181
251
  function mergeExcludes(fileExclude, ruleExclude) {
@@ -183,7 +253,7 @@ function mergeExcludes(fileExclude, ruleExclude) {
183
253
  return undefined;
184
254
  return [...new Set([...(fileExclude ?? []), ...(ruleExclude ?? [])])];
185
255
  }
186
- function normalizeRule(rule, _defaults, _sourceDir) {
256
+ function normalizeRule(rule, _sourceDir) {
187
257
  return {
188
258
  ...rule,
189
259
  enabled: rule.enabled ?? true,
package/dist/engine.d.ts CHANGED
@@ -18,7 +18,14 @@ export declare class RuleEngine {
18
18
  constructor(options?: RuleEngineOptions);
19
19
  /** Register or replace an evaluator. */
20
20
  registerEvaluator(type: string, evaluator: RuleEvaluator): void;
21
- /** Evaluate all enabled rules against a working directory. */
21
+ /**
22
+ * Evaluate all enabled rules against a working directory.
23
+ *
24
+ * Thin delegate to {@link evaluateWithFixes} with `maxFixMode = 'none'`; the fix
25
+ * branch in that path is short-circuited by `effectiveFixMode` so callers see only
26
+ * findings, never auto-generated fixes. Keeps the rule loop and error-finding
27
+ * semantics in one place.
28
+ */
22
29
  evaluate(rules: ConstraintRule[], workdir: string): Promise<RuleEngineResult>;
23
30
  /**
24
31
  * Evaluate all enabled rules and collect candidate fixes.
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAKH,KAAK,oBAAoB,EAE5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAqB,cAAc,EAAE,GAAG,EAAE,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGhH,6CAA6C;AAC7C,MAAM,WAAW,iBAAiB;IAC9B,+DAA+D;IAC/D,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,mCAAmC;IACnC,IAAI,CAAC,EAAE,cAAc,CAAC;CACzB;AAED,4EAA4E;AAC5E,qBAAa,UAAU;IACnB,2CAA2C;IAC3C,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAE9B,+CAA+C;IAC/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiC;gBAE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xC,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,GAAG,IAAI;IAI/D;;;;;;;OAOG;IACG,QAAQ,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAInF;;;;;;;;;;;OAWG;IACG,iBAAiB,CACnB,KAAK,EAAE,cAAc,EAAE,EACvB,OAAO,EAAE,MAAM,EACf,UAAU,GAAE,OAAgB,GAC7B,OAAO,CAAC,gBAAgB,CAAC;IAkD5B;;;;;;;OAOG;IACG,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,EAAE,EAAE,MAAM,UAAQ,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAG1G"}
package/dist/engine.js CHANGED
@@ -17,26 +17,16 @@ export class RuleEngine {
17
17
  registerEvaluator(type, evaluator) {
18
18
  this.host.evaluators.register(type, evaluator, 'extension');
19
19
  }
20
- /** Evaluate all enabled rules against a working directory. */
20
+ /**
21
+ * Evaluate all enabled rules against a working directory.
22
+ *
23
+ * Thin delegate to {@link evaluateWithFixes} with `maxFixMode = 'none'`; the fix
24
+ * branch in that path is short-circuited by `effectiveFixMode` so callers see only
25
+ * findings, never auto-generated fixes. Keeps the rule loop and error-finding
26
+ * semantics in one place.
27
+ */
21
28
  async evaluate(rules, workdir) {
22
- const findings = [];
23
- const fixes = [];
24
- for (const rule of rules) {
25
- if (rule.enabled === false)
26
- continue;
27
- try {
28
- const result = await this.host.evaluators.get(rule.evaluator.type).evaluate(rule, { rule, workdir });
29
- findings.push(...result.findings);
30
- fixes.push(...result.fixes);
31
- }
32
- catch (error) {
33
- findings.push(createFinding(rule, error instanceof Error ? error.message : String(error), null, {
34
- code: `evaluator:${rule.evaluator.type}`,
35
- kind: 'error',
36
- }));
37
- }
38
- }
39
- return { findings, fixes };
29
+ return this.evaluateWithFixes(rules, workdir, 'none');
40
30
  }
41
31
  /**
42
32
  * Evaluate all enabled rules and collect candidate fixes.
@@ -77,18 +77,27 @@ function parseLcov(raw) {
77
77
  linesHit = 0;
78
78
  }
79
79
  else if (trimmed.startsWith('LF:')) {
80
- linesFound = Number(trimmed.slice(3));
80
+ linesFound = parseCount(trimmed.slice(3));
81
81
  }
82
82
  else if (trimmed.startsWith('LH:')) {
83
- linesHit = Number(trimmed.slice(3));
83
+ linesHit = parseCount(trimmed.slice(3));
84
84
  }
85
85
  else if (trimmed === 'end_of_record' && file !== null) {
86
- result.set(file, { linesFound, linesHit });
86
+ // Skip records with malformed counts: a non-numeric LF:/LH: would
87
+ // otherwise yield NaN coverage and a spurious below-threshold finding.
88
+ if (linesFound !== null && linesHit !== null) {
89
+ result.set(file, { linesFound, linesHit });
90
+ }
87
91
  file = null;
88
92
  }
89
93
  }
90
94
  return result;
91
95
  }
96
+ /** Parse an lcov count field; return null for non-finite or negative values. */
97
+ function parseCount(raw) {
98
+ const value = Number(raw);
99
+ return Number.isFinite(value) && value >= 0 ? value : null;
100
+ }
92
101
  /** Standard exclusions applied regardless of config (tests, generated, deps). */
93
102
  function isAlwaysExcluded(filePath) {
94
103
  return (filePath.includes('node_modules') ||
@@ -14,6 +14,46 @@ export interface SourceDiscoveryOptions {
14
14
  export declare function discoverFiles(options: SourceDiscoveryOptions): Promise<string[]>;
15
15
  /** Read a file from a workdir-relative path. */
16
16
  export declare function readWorkdirFile(workdir: string, filePath: string, fs?: NodeFileSystem): Promise<string>;
17
+ /** A discovered in-scope file paired with its contents. */
18
+ export interface ScannedFile {
19
+ /** Workdir-relative path. */
20
+ readonly file: string;
21
+ /** Full file contents. */
22
+ readonly content: string;
23
+ }
24
+ /** How `scanFiles` matches `include` / `exclude` against discovered paths. */
25
+ export type ScanMatchMode = 'loose' | 'glob';
26
+ /** Options for {@link scanFiles}. */
27
+ export interface ScanFilesOptions {
28
+ /** Working directory to walk. */
29
+ workdir: string;
30
+ /** Include patterns; semantics depend on `matchMode`. Undefined/empty = all files. */
31
+ include?: string[];
32
+ /** Exclude patterns; semantics depend on `matchMode`. */
33
+ exclude?: string[];
34
+ /**
35
+ * Scope matching policy:
36
+ * - `loose` — substring/suffix fragments via {@link matchesAny} (back-compat for
37
+ * evaluators that historically accepted bare fragments like `.ts` or `src/`).
38
+ * - `glob` — anchored `**`/`*` globs via {@link matchesGlob}.
39
+ *
40
+ * The two are NOT interchangeable: a bare `src/` matches different sets under each.
41
+ * Each evaluator declares the mode that preserves its existing behavior.
42
+ */
43
+ matchMode: ScanMatchMode;
44
+ /** Filesystem adapter. */
45
+ fs?: FileSystem;
46
+ }
47
+ /**
48
+ * Discover in-scope files and read each once — the shared scaffolding behind the
49
+ * line-scanning evaluators. Owns discovery, scope filtering (per `matchMode`), and
50
+ * reads, so each evaluator is left with only its own matcher.
51
+ *
52
+ * Scope is a parameter, not assumed one-per-rule: callers that scan under several
53
+ * scopes (e.g. import boundaries) pass no `include` here and apply their own globs to
54
+ * the returned paths.
55
+ */
56
+ export declare function scanFiles(options: ScanFilesOptions): Promise<ScannedFile[]>;
17
57
  /** Ensure a path is workdir-relative for findings. */
18
58
  export declare function relativeToWorkdir(workdir: string, path: string): string;
19
59
  /** Return parent directory for a workdir-relative path. */
@@ -28,4 +68,19 @@ export declare function matchesAny(path: string, patterns: string[] | undefined)
28
68
  * (coverage scoping, test-file location) where a loose match would change findings.
29
69
  */
30
70
  export declare function matchesGlob(path: string, pattern: string): boolean;
71
+ /** Escape a string for safe literal use inside a `RegExp` source. */
72
+ export declare function escapeRegExp(value: string): string;
73
+ /** Return the value as a `string[]` when every item is a string, otherwise undefined. */
74
+ export declare function stringArray(value: unknown): string[] | undefined;
75
+ /**
76
+ * Split a leading ripgrep/PCRE-style `(?flags)` inline group off a regex source.
77
+ *
78
+ * Returns the JS-relevant flags found in the group (filtered to `imsu`) and the
79
+ * remaining source with the group removed. When no leading group is present, returns
80
+ * empty flags and the source unchanged. Shared by evaluators that accept inline flags.
81
+ */
82
+ export declare function parseInlineFlags(source: string): {
83
+ flags: string;
84
+ rest: string;
85
+ };
31
86
  //# sourceMappingURL=file-utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"file-utils.d.ts","sourceRoot":"","sources":["../../src/evaluators/file-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAE,cAAc,EAAW,MAAM,uBAAuB,CAAC;AAEjF,yCAAyC;AACzC,MAAM,WAAW,sBAAsB;IACnC,yBAAyB;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,0CAA0C;IAC1C,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,8BAA8B;IAC9B,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,0BAA0B;IAC1B,EAAE,CAAC,EAAE,UAAU,CAAC;CACnB;AAID,qFAAqF;AACrF,wBAAsB,aAAa,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAWtF;AAED,gDAAgD;AAChD,wBAAsB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,iBAAuB,GAAG,OAAO,CAAC,MAAM,CAAC,CAEnH;AAED,sDAAsD;AACtD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,2DAA2D;AAC3D,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGnD;AAED,uEAAuE;AACvE,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,OAAO,CAMhF;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAUlE"}
1
+ {"version":3,"file":"file-utils.d.ts","sourceRoot":"","sources":["../../src/evaluators/file-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE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,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,2DAA2D;AAC3D,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGnD;AAED,uEAAuE;AACvE,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,OAAO,CAMhF;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAUlE;AAqBD,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,yFAAyF;AACzF,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,GAAG,SAAS,CAEhE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAKhF"}
@@ -15,6 +15,33 @@ export async function discoverFiles(options) {
15
15
  export async function readWorkdirFile(workdir, filePath, fs = new NodeFileSystem()) {
16
16
  return await fs.readFile(resolve(workdir, filePath));
17
17
  }
18
+ /**
19
+ * Discover in-scope files and read each once — the shared scaffolding behind the
20
+ * line-scanning evaluators. Owns discovery, scope filtering (per `matchMode`), and
21
+ * reads, so each evaluator is left with only its own matcher.
22
+ *
23
+ * Scope is a parameter, not assumed one-per-rule: callers that scan under several
24
+ * scopes (e.g. import boundaries) pass no `include` here and apply their own globs to
25
+ * the returned paths.
26
+ */
27
+ export async function scanFiles(options) {
28
+ const fs = options.fs ?? new NodeFileSystem();
29
+ const files = options.matchMode === 'loose'
30
+ ? await discoverFiles({ workdir: options.workdir, include: options.include, exclude: options.exclude, fs })
31
+ : await discoverFilesByGlob(options.workdir, options.include, options.exclude, fs);
32
+ const scanned = [];
33
+ for (const file of files) {
34
+ scanned.push({ file, content: await readWorkdirFile(options.workdir, file, fs) });
35
+ }
36
+ return scanned;
37
+ }
38
+ /** Discover files then filter with anchored globs (strict mode for {@link scanFiles}). */
39
+ async function discoverFilesByGlob(workdir, include, exclude, fs) {
40
+ const all = await discoverFiles({ workdir, fs });
41
+ return all
42
+ .filter((file) => include === undefined || include.length === 0 || include.some((g) => matchesGlob(file, g)))
43
+ .filter((file) => exclude === undefined || !exclude.some((g) => matchesGlob(file, g)));
44
+ }
18
45
  /** Ensure a path is workdir-relative for findings. */
19
46
  export function relativeToWorkdir(workdir, path) {
20
47
  return relative(workdir, resolve(path));
@@ -73,3 +100,25 @@ function matchSegment(segment, pattern) {
73
100
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replaceAll('*', '[^/]*');
74
101
  return new RegExp(`^${escaped}$`).test(segment);
75
102
  }
103
+ /** Escape a string for safe literal use inside a `RegExp` source. */
104
+ export function escapeRegExp(value) {
105
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
106
+ }
107
+ /** Return the value as a `string[]` when every item is a string, otherwise undefined. */
108
+ export function stringArray(value) {
109
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined;
110
+ }
111
+ /**
112
+ * Split a leading ripgrep/PCRE-style `(?flags)` inline group off a regex source.
113
+ *
114
+ * Returns the JS-relevant flags found in the group (filtered to `imsu`) and the
115
+ * remaining source with the group removed. When no leading group is present, returns
116
+ * empty flags and the source unchanged. Shared by evaluators that accept inline flags.
117
+ */
118
+ export function parseInlineFlags(source) {
119
+ const match = /^\(\?([a-z]+)\)/.exec(source);
120
+ if (!match)
121
+ return { flags: '', rest: source };
122
+ const flags = [...(match[1] ?? '')].filter((flag) => 'imsu'.includes(flag)).join('');
123
+ return { flags, rest: source.slice(match[0].length) };
124
+ }
@@ -9,6 +9,11 @@ import { type ConstraintRule, type RuleContext, type RuleEvaluationResult, type
9
9
  * entry is an exact `specifier` (also matching require/dynamic forms unless
10
10
  * `includeRequire:false`) or a raw `pattern`, scoped by `scope.include` /
11
11
  * `scope.exclude` globs.
12
+ *
13
+ * Trust assumption: rule config is trusted input. A raw `pattern` is compiled with
14
+ * `new RegExp` and run per line without a backtracking bound, so a
15
+ * catastrophic-backtracking pattern is the rule author's responsibility. Runtime
16
+ * ReDoS hardening is deferred (see task 0003).
12
17
  */
13
18
  export declare class ForbiddenImportEvaluator implements RuleEvaluator {
14
19
  /** Evaluate import/usage against the configured forbidden set. */
@@ -1 +1 @@
1
- {"version":3,"file":"forbidden-import-evaluator.d.ts","sourceRoot":"","sources":["../../src/evaluators/forbidden-import-evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,cAAc,EAEnB,KAAK,WAAW,EAChB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EACrB,MAAM,UAAU,CAAC;AAclB;;;;;;;;;;GAUG;AACH,qBAAa,wBAAyB,YAAW,aAAa;IAC1D,kEAAkE;IAC5D,QAAQ,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAOzF,0FAA0F;YAC5E,cAAc;IA+B5B,4EAA4E;YAC9D,kBAAkB;CAoCnC"}
1
+ {"version":3,"file":"forbidden-import-evaluator.d.ts","sourceRoot":"","sources":["../../src/evaluators/forbidden-import-evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,cAAc,EAEnB,KAAK,WAAW,EAChB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EACrB,MAAM,UAAU,CAAC;AAclB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,wBAAyB,YAAW,aAAa;IAC1D,kEAAkE;IAC5D,QAAQ,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAOzF,0FAA0F;YAC5E,cAAc;IAgC5B,4EAA4E;YAC9D,kBAAkB;CAiCnC"}
@@ -1,5 +1,5 @@
1
1
  import { createFinding, } from '../types.js';
2
- import { discoverFiles, matchesGlob, readWorkdirFile } from './file-utils.js';
2
+ import { escapeRegExp, scanFiles, stringArray } from './file-utils.js';
3
3
  /**
4
4
  * Detects forbidden imports / API usage.
5
5
  *
@@ -10,6 +10,11 @@ import { discoverFiles, matchesGlob, readWorkdirFile } from './file-utils.js';
10
10
  * entry is an exact `specifier` (also matching require/dynamic forms unless
11
11
  * `includeRequire:false`) or a raw `pattern`, scoped by `scope.include` /
12
12
  * `scope.exclude` globs.
13
+ *
14
+ * Trust assumption: rule config is trusted input. A raw `pattern` is compiled with
15
+ * `new RegExp` and run per line without a backtracking bound, so a
16
+ * catastrophic-backtracking pattern is the rule author's responsibility. Runtime
17
+ * ReDoS hardening is deferred (see task 0003).
13
18
  */
14
19
  export class ForbiddenImportEvaluator {
15
20
  /** Evaluate import/usage against the configured forbidden set. */
@@ -22,14 +27,15 @@ export class ForbiddenImportEvaluator {
22
27
  /** Legacy path: `{ patterns: string[] }`, substring-matched against import specifiers. */
23
28
  async evaluateSimple(rule, context, config) {
24
29
  const forbidden = arrayConfig(config, 'patterns');
25
- const files = await discoverFiles({
30
+ const files = await scanFiles({
26
31
  workdir: context.workdir,
27
32
  include: rule.include ?? ['.ts', '.tsx', '.js', '.jsx'],
28
33
  exclude: rule.exclude,
34
+ matchMode: 'loose',
29
35
  });
30
36
  const findings = [];
31
- for (const file of files) {
32
- const lines = (await readWorkdirFile(context.workdir, file)).split('\n');
37
+ for (const { file, content } of files) {
38
+ const lines = content.split('\n');
33
39
  for (const [index, line] of lines.entries()) {
34
40
  const imported = importSpecifier(line);
35
41
  if (imported === undefined)
@@ -54,14 +60,11 @@ export class ForbiddenImportEvaluator {
54
60
  }
55
61
  const exclude = stringArray(scope?.exclude) ?? [];
56
62
  const entries = config.forbidden.map(compileEntry);
57
- // Discover all source files, then apply scope globs precisely (discoverFiles'
58
- // include matching is intentionally loose, so it cannot do `**`-anchored scoping).
59
- const files = (await discoverFiles({ workdir: context.workdir }))
60
- .filter((file) => include.some((glob) => matchesGlob(file, glob)))
61
- .filter((file) => !exclude.some((glob) => matchesGlob(file, glob)));
63
+ // Anchored `**`-glob scoping: scanFiles' 'glob' mode applies matchesGlob precisely.
64
+ const files = await scanFiles({ workdir: context.workdir, include, exclude, matchMode: 'glob' });
62
65
  const findings = [];
63
- for (const file of files) {
64
- const lines = (await readWorkdirFile(context.workdir, file)).split('\n');
66
+ for (const { file, content } of files) {
67
+ const lines = content.split('\n');
65
68
  for (const [index, line] of lines.entries()) {
66
69
  const hit = entries.find((entry) => entry.regex.test(line));
67
70
  if (hit !== undefined) {
@@ -91,9 +94,6 @@ function compileEntry(entry) {
91
94
  }
92
95
  return { regex: new RegExp(entry.pattern), label: entry.pattern };
93
96
  }
94
- function escapeRegExp(value) {
95
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
96
- }
97
97
  function arrayConfig(config, key) {
98
98
  const value = config[key];
99
99
  if (Array.isArray(value) && value.every((item) => typeof item === 'string'))
@@ -102,6 +102,3 @@ function arrayConfig(config, key) {
102
102
  return [value];
103
103
  throw new Error(`forbidden-import evaluator requires string[] config "${key}"`);
104
104
  }
105
- function stringArray(value) {
106
- return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined;
107
- }
@@ -11,6 +11,11 @@ import { type ConstraintRule, type RuleContext, type RuleEvaluationResult, type
11
11
  * - `scope` — glob pattern selecting files this boundary applies to.
12
12
  * - `forbidden` — array of strings or `{ pattern, mode?, syntax? }` objects.
13
13
  * - `exclude` — optional globs within the scope to ignore.
14
+ *
15
+ * Trust assumption: rule config is trusted input. A `pattern` is compiled with
16
+ * `new RegExp` and run per line without a backtracking bound, so a
17
+ * catastrophic-backtracking pattern is the rule author's responsibility. Runtime
18
+ * ReDoS hardening is deferred (see task 0003).
14
19
  */
15
20
  export declare class ImportBoundaryEvaluator implements RuleEvaluator {
16
21
  /** Evaluate import boundaries across all in-scope files. */
@@ -1 +1 @@
1
- {"version":3,"file":"import-boundary-evaluator.d.ts","sourceRoot":"","sources":["../../src/evaluators/import-boundary-evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,cAAc,EAEnB,KAAK,WAAW,EAChB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EACrB,MAAM,UAAU,CAAC;AA4BlB;;;;;;;;;;;;GAYG;AACH,qBAAa,uBAAwB,YAAW,aAAa;IACzD,4DAA4D;IACtD,QAAQ,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAuC5F"}
1
+ {"version":3,"file":"import-boundary-evaluator.d.ts","sourceRoot":"","sources":["../../src/evaluators/import-boundary-evaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,cAAc,EAEnB,KAAK,WAAW,EAChB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EACrB,MAAM,UAAU,CAAC;AAUlB;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,uBAAwB,YAAW,aAAa;IACzD,4DAA4D;IACtD,QAAQ,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAsC5F"}