@lintsure/core 0.3.9 → 0.3.11

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.
@@ -12,7 +12,8 @@ export * from "./guidance.js";
12
12
  export { toAssessmentHtml } from "./assessment.js";
13
13
  export * from "./knowledge/index.js";
14
14
  export { loadPacks, registerPack, type Pack } from "./packs.js";
15
- export declare const RULES_VERSION = "0.3.9";
15
+ export { checksFor } from "./plan.js";
16
+ export declare const RULES_VERSION = "0.3.11";
16
17
  /** Shown with every result, in every interface. Lintsure prepares; people decide. */
17
18
  export declare const DISCLAIMER: string;
18
19
  /** What a report must never be read as. Used in the report and by the MCP server. */
@@ -35,6 +36,7 @@ export interface Config {
35
36
  skipped: string[];
36
37
  ignore: string[];
37
38
  packsMissing?: string[];
39
+ packs?: string[];
38
40
  /** Per-rule settings: "off" stops a rule; "low" | "medium" | "high" changes its risk level. */
39
41
  rules: Record<string, "off" | Severity>;
40
42
  /** "all" also shows medium-confidence findings. */
@@ -77,6 +79,35 @@ export interface ScanOptions extends RecordOptions {
77
79
  base: string;
78
80
  lines: Record<string, number[]>;
79
81
  };
82
+ /** Workspace rules from a Lintsure account, handed in by the caller (the plugin downloads them with an API key).
83
+ * The scan never fetches anything; it only hashes what it is given into the policy fingerprint. */
84
+ workspaceRules?: unknown;
80
85
  }
86
+ /** The repo's .lintsure/rules.yml (the Drift Guard's rules), normalized: comments, blank lines and trailing spaces dropped.
87
+ * null when the file isn't there. */
88
+ /** A YAML line without its comment: a # at the start or after a space, outside quotes ("rm # a" keeps its #). Pure. */
89
+ export declare function stripYamlComment(l: string): string;
90
+ /** The policy a scan ran under, as one short code. Same rules and settings give the same code on any machine;
91
+ * any change (a rule switched off or re-rated, a framework, an ignore path, show: all, a new rules version) gives a new one.
92
+ * `fingerprint` is the first 8 hex digits of `sha256`, shown as XXXX-XXXX. It names the policy; it doesn't sign anything. */
93
+ export declare function policyFingerprint(p: {
94
+ frameworks: string[];
95
+ rules: {
96
+ id: string;
97
+ severity: string;
98
+ }[];
99
+ rulesOff: string[];
100
+ ignore: string[];
101
+ show?: string;
102
+ repoRules?: string | null;
103
+ workspaceRules?: unknown;
104
+ packs?: string[];
105
+ }): {
106
+ fingerprint: string;
107
+ sha256: string;
108
+ rulesActive: number;
109
+ repoRules: boolean;
110
+ workspaceRules: boolean;
111
+ };
81
112
  export declare function scan(root: string, frameworks?: FrameworkId[], opts?: ScanOptions): Promise<Report>;
82
113
  export declare function toMarkdown(r: Report): string;
package/dist/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Scout (file walk) + Checker (rules) + Auditor (dedupe, sort) + Officer (outside code).
2
2
  // No network calls anywhere in this package: a test enforces it.
3
- import { readdir, readFile } from "node:fs/promises";
3
+ import { createHash } from "node:crypto";
4
+ import { readdir, readFile, stat } from "node:fs/promises";
4
5
  import { basename, extname, join, relative, sep } from "node:path";
5
6
  import { outsideFor } from "./knowledge/index.js";
6
7
  import { rules } from "./rules/index.js";
@@ -18,8 +19,10 @@ export * from "./guidance.js";
18
19
  export { toAssessmentHtml } from "./assessment.js";
19
20
  export * from "./knowledge/index.js";
20
21
  export { loadPacks, registerPack } from "./packs.js";
21
- import { loadPacks } from "./packs.js";
22
- export const RULES_VERSION = "0.3.9";
22
+ export { checksFor } from "./plan.js";
23
+ import { configPacks, loadPacks, packFrameworks, packsLoaded } from "./packs.js";
24
+ import { buildGraph, declaredEntries, reachOf } from "./reach.js";
25
+ export const RULES_VERSION = "0.3.11";
23
26
  /** Shown with every result, in every interface. Lintsure prepares; people decide. */
24
27
  export const DISCLAIMER = "Lintsure is a readiness tool, not an audit, a certification or legal advice. " +
25
28
  "Its rules reflect our reading of the publicly available text of each framework, and they check code only. " +
@@ -110,7 +113,7 @@ export async function readConfig(root) {
110
113
  for (const id of Object.keys(ruleSet))
111
114
  if (!ruleIds.has(id))
112
115
  problems.push(`rules: no rule called "${id}"`);
113
- const base = { ignore, packsMissing, rules: ruleSet, show, problems };
116
+ const base = { ignore, packsMissing, packs: lists.packs, rules: ruleSet, show, problems };
114
117
  if (emptyFw)
115
118
  return { frameworks: [], skipped: [], ...base };
116
119
  const ids = lists.frameworks;
@@ -121,6 +124,16 @@ export async function readConfig(root) {
121
124
  }
122
125
  // Dependencies, build output and caches: generated code, not code you wrote.
123
126
  // Also other people's code copied in (vendor, third_party): not code you wrote (field test, 139 repos).
127
+ /** The exact change for a finding, when its rule knows one. Pure. */
128
+ function patchFor(r, line, old) {
129
+ if (r.insert)
130
+ return { patch: { line, old: null, text: r.insert } };
131
+ const text = r.patch?.(old);
132
+ return text != null && text !== old ? { patch: { line, old, text } } : {};
133
+ }
134
+ // What a Partial finding can't show. Rules read lines and statements, not how data moves through the program.
135
+ const UNSEEN = "Lintsure reads this code on its own. It can't see where the values come from or whether they're checked elsewhere, so a person needs to look.";
136
+ const UNSEEN_TESTS = "This is in a test, fixture or example file. Lintsure can't tell whether it ships or is a throwaway value.";
124
137
  export const SKIP_DIRS = ["node_modules", ".git", "dist", "build", "out", ".output", ".next", ".nuxt", ".svelte-kit", ".astro", ".vercel", ".netlify", ".wrangler", ".turbo", ".cache", "venv", ".venv", "__pycache__", "coverage", "vendor", "third_party", "bower_components"];
125
138
  const SKIP = new Set(SKIP_DIRS);
126
139
  // Bundled builds of libraries checked into a repo, e.g. vue.global.js (field test, 139 repos).
@@ -161,12 +174,12 @@ export async function listFiles(root, ignore = []) {
161
174
  }
162
175
  // Code that doesn't ship: tests, fixtures, examples, docs, demos, stories and seed data. Most false alarms in the
163
176
  // 139-repo field test came from here. Only the secret rules read these paths, and their findings there are Partial.
164
- export const NON_SHIPPING = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|factories|\.dev|benchmarks?|scripts?|\.agents|\.claude|\.cursor)\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)(conftest\.py|pytest\.ini|tox\.ini)$|(^|\/)\.env\.(example|sample|template|dist)$|(^|\/)(playwright|vitest|jest|cypress)\.config\.[cm]?[jt]s$/i;
177
+ export const NON_SHIPPING = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|factories|\.dev|benchmarks?|scripts?|\.agents|\.claude|\.cursor|\.devcontainer)\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)(conftest\.py|pytest\.ini|tox\.ini)$|(^|\/)\.env\.(example|sample|template|dist)$|(^|\/)(playwright|vitest|jest|cypress)\.config\.[cm]?[jt]s$/i;
165
178
  // In Next.js, Remix and Supabase a folder name is a route or a function name: app/api/demo and a function called
166
179
  // "test" are live endpoints (review P3). Inside these roots only real test files count as non-shipping.
167
180
  // Example, demo, docs and sample folders inside application source (src/, lib/, server/) are shipping code too.
168
181
  const LIVE_ROOT = /(^|\/)(app|pages|api|routes|supabase\/functions|src|lib|server)\//;
169
- const NS_FOLDER = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|benchmarks?|scripts?|\.agents|\.claude|\.cursor)\//i;
182
+ const NS_FOLDER = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|benchmarks?|scripts?|\.agents|\.claude|\.cursor|\.devcontainer)\//i;
170
183
  // Dev scripts at the top of a repo (scripts/test-*.mjs, build and seed helpers) and agent tooling (.agents/, .claude/)
171
184
  // don't ship: they were the largest single source of false alarms in the 0.3.9 labelled sample (44 of 242).
172
185
  const TEST_FILE = /(^|\/)__tests__\/|(^|\/)test[-_]?(utils?|helpers?|rig)\/|(^|\/)test-[^/]+\.[cm]?[jt]s$|[._-]tests?\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)(conftest\.py|pytest\.ini|tox\.ini)$/i;
@@ -190,6 +203,8 @@ export function isNonShipping(file) {
190
203
  }
191
204
  // Rules that also read test files. Not auth.hardcoded-password: test logins are fake by design (field test, 50 repos).
192
205
  const SECRET_RULES = new Set(["secret.in-source"]); // not config.default-secret-key: a test secret is a test value (review P19)
206
+ // Rules that read agent tooling folders on purpose: an agent hook in .claude/ runs on real machines.
207
+ const TOOLING_RULES = new Set(["agent.config-runs-remote-code", "agent.instructions-unsafe", "agent.permissions-allow-all"]);
193
208
  // Lines a person already reviewed. lintsure-ignore and the secret allowlist pragma count only in a comment and apply
194
209
  // to every rule. Other linters' markers (noqa, nosec, NOSONAR) don't hide secrets: `# noqa: E501` is about line length.
195
210
  const REVIEWED = /(#|\/\/|\/\*|--)\s*(lintsure-ignore|pragma:\s*allowlist secret)\b/;
@@ -219,7 +234,7 @@ const JOIN_RULES = new Set(["pii.logged", "pii.to-analytics", "log.injection", "
219
234
  "ssrf.user-url", "path.user-input", "redirect.open", "nosql.operator-input", "template.user-string", "error.stack-to-client",
220
235
  // Narrow call-plus-value patterns, where unrelated parts of a statement rarely complete a match.
221
236
  "transport.plain-http", "transport.tls-verify-off", "jwt.unverified", "crypto.weak-cipher", "fs.world-writable",
222
- "mobile.token-in-plain-storage", "config.debug-on", "cookie.trusted-role"]);
237
+ "mobile.token-in-plain-storage", "config.debug-on", "cookie.trusted-role", "code.eval"]);
223
238
  const MAX_JOIN_LINES = 25, MAX_JOIN_CHARS = 2000;
224
239
  /** Groups lines into statements: lines join while a ( or [ or a template literal is open. Joining stops at a function
225
240
  * body (`=> {`, `) {`), so a handler passed as an argument stays line by line. `prose` marks a multi-line template
@@ -319,9 +334,66 @@ export function commentLines(lines, ext) {
319
334
  return t.startsWith("//") || (C_LIKE.has(ext) && t.startsWith("*")) || t.startsWith("<!--") || (hash && t.startsWith("#")) || (sql && t.startsWith("--"));
320
335
  });
321
336
  }
337
+ /** The repo's .lintsure/rules.yml (the Drift Guard's rules), normalized: comments, blank lines and trailing spaces dropped.
338
+ * null when the file isn't there. */
339
+ /** A YAML line without its comment: a # at the start or after a space, outside quotes ("rm # a" keeps its #). Pure. */
340
+ export function stripYamlComment(l) {
341
+ let q = "";
342
+ for (let i = 0; i < l.length; i++) {
343
+ const c = l[i];
344
+ if (q) {
345
+ if (c === q)
346
+ q = "";
347
+ continue;
348
+ }
349
+ if (c === '"' || c === "'")
350
+ q = c;
351
+ else if (c === "#" && (i === 0 || /\s/.test(l[i - 1])))
352
+ return l.slice(0, i);
353
+ }
354
+ return l;
355
+ }
356
+ async function readRepoRules(root) {
357
+ try {
358
+ const text = await readFile(join(root, ".lintsure", "rules.yml"), "utf8");
359
+ return text.split(/\r?\n/).map((l) => stripYamlComment(l).trimEnd()).filter((l) => l.trim()).join("\n");
360
+ }
361
+ catch {
362
+ return null;
363
+ }
364
+ }
365
+ /** JSON with object keys sorted at every level, so the same data always hashes the same. */
366
+ const stable = (v) => Array.isArray(v) ? `[${v.map(stable).join(",")}]`
367
+ : v && typeof v === "object" ? `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(",")}}`
368
+ : JSON.stringify(v ?? null);
369
+ /** The policy a scan ran under, as one short code. Same rules and settings give the same code on any machine;
370
+ * any change (a rule switched off or re-rated, a framework, an ignore path, show: all, a new rules version) gives a new one.
371
+ * `fingerprint` is the first 8 hex digits of `sha256`, shown as XXXX-XXXX. It names the policy; it doesn't sign anything. */
372
+ export function policyFingerprint(p) {
373
+ const canon = JSON.stringify({
374
+ rulesVersion: RULES_VERSION,
375
+ frameworks: [...p.frameworks].sort(),
376
+ rules: [...p.rules].sort((a, b) => a.id.localeCompare(b.id)).map((r) => `${r.id}:${r.severity}`),
377
+ rulesOff: [...p.rulesOff].sort(),
378
+ ignore: [...p.ignore].sort(),
379
+ show: p.show ?? "default",
380
+ // Installed rule packs and their versions. Left out when none, so codes from before packs existed stay the same.
381
+ ...(p.packs?.length ? { packs: [...p.packs].sort() } : {}),
382
+ // The Drift Guard's .lintsure/rules.yml, comments and blank lines dropped, so only a real rule change moves the code.
383
+ repoRules: p.repoRules ?? null,
384
+ // Account (workspace) rules, when the caller passed them: key order doesn't matter, content does.
385
+ workspaceRules: p.workspaceRules == null ? null : stable(p.workspaceRules),
386
+ });
387
+ const sha256 = createHash("sha256").update(canon).digest("hex");
388
+ return { fingerprint: `${sha256.slice(0, 4)}-${sha256.slice(4, 8)}`.toUpperCase(), sha256, rulesActive: p.rules.length, repoRules: p.repoRules != null, workspaceRules: p.workspaceRules != null };
389
+ }
322
390
  export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
323
391
  const config = await readConfig(root);
324
392
  const { ignore } = config;
393
+ // Packs are registered for the whole process; this scan uses only the ones its own config lists.
394
+ const ownPacks = new Set(config.packs ?? []);
395
+ const usable = (packId) => !configPacks.has(packId) || ownPacks.has(packId);
396
+ frameworks = frameworks.filter((f) => !packFrameworks.has(f) || usable(packFrameworks.get(f)));
325
397
  const rulesOff = Object.keys(config.rules).filter((id) => config.rules[id] === "off");
326
398
  const active = rules.filter((r) => r.controls.some((c) => frameworks.includes(c.framework)) && !rulesOff.includes(r.id));
327
399
  const findings = [];
@@ -338,8 +410,29 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
338
410
  continue;
339
411
  const controls = r.controls.filter((c) => frameworks.includes(c.framework));
340
412
  findings.push({ id: "", ruleId: r.id, file, line: 1, status: r.status, severity: r.severity, title: r.title, controls, fix: r.fix, note: r.note,
341
- proposal: proposalFor({ file, line: 1, title: r.title, fix: r.fix, note: r.note, controls }), fingerprint: fingerprint(r.id, file, "") });
413
+ proposal: proposalFor({ file, line: 1, title: r.title, fix: r.fix, note: r.note, controls }), fingerprint: fingerprint(r.id, file, ""),
414
+ ...(r.status === "partial" ? { unseen: r.unseen ?? UNSEEN } : {}) });
342
415
  }
416
+ // Every file is read once per scan, with one size and binary guard for every reader (code review: files were read up
417
+ // to four times, one at a time). Reads run 32 at a time; null means too big, binary or unreadable.
418
+ const cache = new Map();
419
+ const textOf = (abs) => {
420
+ let t = cache.get(abs);
421
+ if (!t) {
422
+ t = stat(abs).then(async (st) => { if (st.size > MAX_BYTES)
423
+ return null; const b = await readFile(abs); return b.includes(0) ? null : b.toString("utf8"); }).catch(() => null);
424
+ cache.set(abs, t);
425
+ }
426
+ return t;
427
+ };
428
+ // Prefetch only files some reader needs: a rule that applies to it, a shared-file rule, or reachability.
429
+ const needed = all.filter((abs, k) => {
430
+ const ext = extOf(abs), name = basename(abs), file = paths[k];
431
+ return /\.(m|c)?[jt]sx?$|\.html?$|(^|\/)(package|tsconfig)\.json$/.test(file) || active.some((r) => r.sharedFiles?.test(file)
432
+ || (r.extensions.includes(ext) && (!r.fileName || r.fileName.test(name)) && (!r.pathMatch || r.pathMatch.test(file)) && !r.unlessPath?.test(file)));
433
+ });
434
+ for (let i = 0; i < needed.length; i += 32)
435
+ await Promise.all(needed.slice(i, i + 32).map(textOf));
343
436
  // Rules that look across files get the joined text of every file they read, read once up front.
344
437
  const shared = new Map();
345
438
  for (const r of active.filter((x) => x.sharedContext)) {
@@ -348,7 +441,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
348
441
  const ext = extOf(abs), file = paths[k];
349
442
  if (!r.extensions.includes(ext) || (r.fileName && !r.fileName.test(basename(abs))) || (r.pathMatch && !r.pathMatch.test(file)) || r.unlessPath?.test(file))
350
443
  continue;
351
- const text = await readFile(abs, "utf8").catch(() => "");
444
+ const text = (await textOf(abs)) ?? "";
352
445
  // Commented-out lines don't count: "-- alter table x enable row level security" switches nothing on.
353
446
  const comment = commentLines(text.split(/\r?\n/), ext);
354
447
  texts.push(text.split(/\r?\n/).filter((_, i) => !comment[i]).join("\n"));
@@ -361,7 +454,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
361
454
  const files = {};
362
455
  for (const [k, abs] of all.entries())
363
456
  if (r.sharedFiles.test(paths[k]))
364
- files[paths[k]] = await readFile(abs, "utf8").catch(() => "");
457
+ files[paths[k]] = (await textOf(abs)) ?? "";
365
458
  sharedFiles.set(r.id, files);
366
459
  }
367
460
  for (const abs of all) {
@@ -371,10 +464,10 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
371
464
  const relevant = active.filter((r) => r.extensions.includes(ext) && (!r.fileName || r.fileName.test(name)) && (!r.pathMatch || r.pathMatch.test(file)) && !r.unlessPath?.test(file));
372
465
  if (!relevant.length)
373
466
  continue;
374
- const buf = await readFile(abs);
375
- if (buf.length > MAX_BYTES || buf.includes(0))
376
- continue; // skip big or binary files
377
- const raw = buf.toString("utf8").split(/\r?\n/);
467
+ const whole = await textOf(abs);
468
+ if (whole === null)
469
+ continue; // big, binary or unreadable
470
+ const raw = whole.split(/\r?\n/);
378
471
  if (isMinified(raw))
379
472
  continue; // minified or generated
380
473
  // A single very long line (a data URL, a long prompt) is ignored on its own; the rest of the file is still read.
@@ -386,6 +479,8 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
386
479
  id: "", ruleId: r.id, file, line, status, severity: r.severity, title: r.title, controls, fix: r.fix, note: r.note,
387
480
  proposal: proposalFor({ file, line, title: r.title, fix: r.fix, note: r.note, controls }),
388
481
  fingerprint: fingerprint(r.id, file, lines[line - 1] ?? ""),
482
+ ...(status === "partial" ? { unseen: inTests && !TOOLING_RULES.has(r.id) ? UNSEEN_TESTS : r.unseen ?? UNSEEN } : {}),
483
+ ...patchFor(r, line, lines[line - 1] ?? ""),
389
484
  });
390
485
  };
391
486
  // Tests, fixtures, examples and docs are full of fake tokens and planted examples: only secret rules look at them,
@@ -404,7 +499,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
404
499
  prose[i] = true;
405
500
  for (const r of relevant) {
406
501
  const secret = SECRET_RULES.has(r.id);
407
- if (inTests && !secret)
502
+ if (inTests && !secret && !TOOLING_RULES.has(r.id))
408
503
  continue;
409
504
  // Count only what actually ran: a file skipped as a test is not a check point (review P1).
410
505
  ran++;
@@ -425,14 +520,14 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
425
520
  return;
426
521
  if (r.unlessInKey && r.unlessInKey.test(enclosingKey(lines, i)))
427
522
  return;
428
- if (inTests && PLACEHOLDER.test(text))
523
+ if (inTests && secret && PLACEHOLDER.test(text))
429
524
  return; // password="test_password", token="xoxb-test-..."
430
525
  if (inTests && /PRIVATE KEY/.test(text))
431
526
  return; // test keys and certificates are fixtures by design (review P24)
432
527
  if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
433
528
  return; // someone already looked at this line and marked it
434
529
  hitLines.add(i);
435
- add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
530
+ add(r, i + 1, hit === "partial" || (inTests && !TOOLING_RULES.has(r.id)) ? "partial" : r.status);
436
531
  });
437
532
  // A statement spread over several lines: test it as one, and report it only when no single line already did,
438
533
  // so line-by-line results never shrink (review step A).
@@ -455,7 +550,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
455
550
  continue;
456
551
  if (lines.slice(s.start, s.end + 1).some((l) => REVIEWED.test(l) || OTHER_LINTER.test(l)))
457
552
  continue;
458
- add(r, s.start + 1, hit === "partial" || inTests ? "partial" : r.status);
553
+ add(r, s.start + 1, hit === "partial" || (inTests && !TOOLING_RULES.has(r.id)) ? "partial" : r.status);
459
554
  }
460
555
  // File rules see comment lines as blank, so "<img> in a comment" or a commented-out call doesn't count (field test).
461
556
  if (r.fileTest)
@@ -469,6 +564,39 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
469
564
  const seen = new Set();
470
565
  const unique = findings.filter((f) => { const k = `${f.ruleId}|${f.file}|${f.line}`; return seen.has(k) ? false : (seen.add(k), true); })
471
566
  .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.ruleId.localeCompare(b.ruleId));
567
+ // Reachability for findings in JS/TS: read the project's own JS/TS files once (skipping very large ones) and follow
568
+ // imports back to entry points. It adds context; it doesn't change any status.
569
+ const JSTS = /\.(m|c)?[jt]sx?$/;
570
+ if (unique.some((f) => JSTS.test(f.file))) {
571
+ const code = {};
572
+ for (const [k, abs] of all.entries())
573
+ if (JSTS.test(paths[k]) && !/\.d\.ts$/.test(paths[k])) {
574
+ const t = (await textOf(abs)) ?? "";
575
+ if (t.length < 500_000)
576
+ code[paths[k]] = t;
577
+ }
578
+ const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
579
+ const tsconfigs = {};
580
+ for (const [k, abs] of all.entries())
581
+ if (/(^|\/)tsconfig\.json$/.test(paths[k]))
582
+ tsconfigs[dirOf(paths[k])] = (await textOf(abs)) ?? "";
583
+ const pkgDirs = paths.filter((p) => /(^|\/)package\.json$/.test(p)).map(dirOf);
584
+ // Entry points no code imports: package.json main/bin/exports and <script src> in HTML pages.
585
+ const pkgs = {}, html = {};
586
+ for (const [k, abs] of all.entries()) {
587
+ if (/(^|\/)package\.json$/.test(paths[k]))
588
+ pkgs[paths[k]] = (await textOf(abs)) ?? "";
589
+ else if (/\.html?$/.test(paths[k])) {
590
+ const t = (await textOf(abs)) ?? "";
591
+ if (t.length < 500_000)
592
+ html[paths[k]] = t;
593
+ }
594
+ }
595
+ const graph = buildGraph(code, tsconfigs, pkgDirs.length ? pkgDirs : [""], declaredEntries(pkgs, html, new Set(Object.keys(code))));
596
+ for (const f of unique)
597
+ if (JSTS.test(f.file))
598
+ f.reach = reachOf(graph, f.file);
599
+ }
472
600
  // A rule that fired still counts as checked (not Met) even when its findings are held back or outside the diff.
473
601
  const hit = new Set(unique.map((f) => f.ruleId));
474
602
  for (const f of unique) {
@@ -489,6 +617,11 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
489
617
  const report = await applyReview({
490
618
  rulesVersion: RULES_VERSION,
491
619
  frameworks: [...frameworks].sort(),
620
+ policy: policyFingerprint({
621
+ frameworks, rulesOff, ignore, show: opts.all ? "all" : config.show, repoRules: await readRepoRules(root), workspaceRules: opts.workspaceRules,
622
+ packs: packsLoaded.filter((p) => usable(p.slice(0, p.lastIndexOf("@")))),
623
+ rules: active.map((r) => ({ id: r.id, severity: (config.rules[r.id] && config.rules[r.id] !== "off" ? config.rules[r.id] : r.severity) })),
624
+ }),
492
625
  findings: deduped,
493
626
  // Only the Checker sets Met: a rule that read at least one file and found nothing. A rule with nothing to read
494
627
  // (mobile rules in a web app) is not Met: nothing was checked.
@@ -504,7 +637,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
504
637
  ...(held ? [`${held} medium-confidence finding${held === 1 ? " was" : "s were"} held back. Run with --all to see ${held === 1 ? "it" : "them"}.`] : []),
505
638
  ...(rulesOff.length ? [`Switched off in lintsure.config.yaml: ${rulesOff.join(", ")}.`] : []),
506
639
  ...(ignore.length ? [`Ignored by config: ${ignore.join(", ")}.`] : []),
507
- ...(nonShipping ? [`${nonShipping} test, fixture or tooling file${nonShipping === 1 ? " was" : "s were"} checked for secrets only.`] : []),
640
+ ...(nonShipping ? [`${nonShipping} test, fixture or tooling file${nonShipping === 1 ? " was" : "s were"} checked only for secrets and agent hooks.`] : []),
508
641
  "Each rule reads one file at a time. Data that flows between files, and how the app behaves when it runs, are not checked.",
509
642
  "Languages beyond JavaScript, TypeScript and Python get secret and config checks only.",
510
643
  ],
@@ -545,7 +678,7 @@ function recordLines(r) {
545
678
  export function toMarkdown(r) {
546
679
  const lines = [
547
680
  "# Lintsure report", "",
548
- `Frameworks: ${r.frameworks.join(", ")} · Rules v${r.rulesVersion}`, "",
681
+ `Frameworks: ${r.frameworks.join(", ")} · Rules v${r.rulesVersion}${r.policy ? ` · Policy #${r.policy.fingerprint} (${r.policy.rulesActive} rules active${r.policy.repoRules ? " + .lintsure/rules.yml" : ""}${r.policy.workspaceRules ? " + workspace rules" : ""})` : ""}`, "",
549
682
  `> ${DISCLAIMER}`, "",
550
683
  ...recordLines(r),
551
684
  `## Findings (${r.findings.length})`, "",
@@ -557,7 +690,8 @@ export function toMarkdown(r) {
557
690
  // Fix first: Gaps before Partials, then by severity; file order within each group.
558
691
  const rank = (f) => (f.status === "gap" ? 0 : 3) + { high: 0, medium: 1, low: 2 }[f.severity];
559
692
  for (const f of [...r.findings].sort((a, b) => rank(a) - rank(b)))
560
- lines.push(`### ${f.id} · ${f.status === "gap" ? "Finding" : "Observation"} (${LABEL[f.status]}) · \`${f.file}:${f.line}\`${f.change === "new" ? " · New since baseline" : ""}`, `**${f.title}** · Risk level: ${f.severity}`, "", ...(f.accepted ? [acceptedLine(f.accepted), ""] : []), `- Rules: ${ctl(f.controls)}`, `- Auditor note: ${f.note}`, "", `**${PROPOSAL_HEADING}**`, "", `- Where: \`${f.proposal.where}\``, `- What: ${f.proposal.what}`, `- Why: ${f.proposal.why}`, `- Benefit: ${f.proposal.benefit}`, "");
693
+ lines.push(`### ${f.id} · ${f.status === "gap" ? "Finding" : "Observation"} (${LABEL[f.status]}) · \`${f.file}:${f.line}\`${f.change === "new" ? " · New since baseline" : ""}`, `**${f.title}** · Risk level: ${f.severity}`, "", ...(f.accepted ? [acceptedLine(f.accepted), ""] : []), `- Rules: ${ctl(f.controls)}`, `- Auditor note: ${f.note}`, ...(f.unseen ? [`- What Lintsure couldn't see: ${f.unseen}`] : []), ...(rules.find((x) => x.id === f.ruleId)?.seenIn ?? []).map((s) => `- Seen in a real incident: ${s.title} (${s.url})`), ...(f.reach ? [`- Reached from: ${f.reach.status === "entry" ? "this file is an entry point (route, handler or function)" : f.reach.status === "reachable" ? f.reach.via.join(" → ") : f.reach.status === "unknown" ? "unknown (an import Lintsure couldn't resolve may lead here)" : "not reached from any entry point Lintsure recognises (it may be loaded some other way, or be unused)"}`] : []), "", `**${PROPOSAL_HEADING}**`, "", `- Where: \`${f.proposal.where}\``, `- What: ${f.proposal.what}`, `- Why: ${f.proposal.why}`, `- Benefit: ${f.proposal.benefit}`, "", ...(f.patch ? [`Exact change (still needs your approval), line ${f.patch.line}:`, "", "```diff",
694
+ ...(f.patch.old != null ? [`- ${f.patch.old}`] : []), ...f.patch.text.replace(/\n$/, "").split("\n").map((t) => `+ ${t}`), "```", ""] : []));
561
695
  if (r.baseline?.fixed.length)
562
696
  lines.push(`## Fixed since baseline (${r.baseline.fixed.length})`, "", ...r.baseline.fixed.map((x) => `- ${x.ruleId} in \`${x.file}\``), "");
563
697
  lines.push(`## Met (${r.met.length})`, "", ...r.met.map((m) => `- ${m.title} · ${ctl(m.controls)}`), "");
@@ -17,7 +17,7 @@ export const cra = {
17
17
  ],
18
18
  obligations: [
19
19
  { ref: "Annex I Part I (2)(b)", title: "Secure by default configuration", inCode: "partly",
20
- rules: ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "cors.any-origin", "build.sourcemaps-public", "csrf.disabled", "session.cookie-insecure"],
20
+ rules: ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "cors.any-origin", "build.sourcemaps-public", "release.env-not-ignored", "csrf.disabled", "session.cookie-insecure"],
21
21
  plain: "The product ships with safe settings switched on: debug off, real host names, strong secrets, secure cookies, nothing left open that the user has to close.",
22
22
  evidence: "Production configuration and the default settings a new install starts with." },
23
23
  { ref: "Annex I Part I (2)(d)", title: "Protection from unauthorised access", inCode: "partly",
@@ -10,22 +10,22 @@ export const owaspLlm = {
10
10
  return null;
11
11
  },
12
12
  obligations: [
13
- { ref: "LLM01:2026", title: "Prompt Injection", inCode: "partly", rules: ["llm.user-input-in-system-prompt"],
13
+ { ref: "LLM01:2026", title: "Prompt Injection", inCode: "partly", rules: ["llm.user-input-in-system-prompt", "agent.instructions-unsafe", "llm.client-controls-system"],
14
14
  plain: "User text, web pages or files can carry instructions that change what the model does. Keep instructions and user content apart, and limit what the model can do.",
15
15
  evidence: "How prompts are built, and tests with hostile input." },
16
16
  { ref: "LLM02:2026", title: "Sensitive Information Disclosure", inCode: "partly", rules: ["secret.in-source", "secret.public-env", "pii.logged", "log.secret"],
17
17
  plain: "Keys, personal data and internal details must not reach the model, its logs or its answers unless they're meant to.",
18
18
  evidence: "What data is sent to the model provider, and the provider's data retention terms." },
19
- { ref: "LLM03:2026", title: "Excessive Agency", inCode: "no",
19
+ { ref: "LLM03:2026", title: "Excessive Agency", inCode: "partly", rules: ["agent.permissions-allow-all"],
20
20
  plain: "Tools and permissions given to an agent should be the minimum it needs, with a person approving anything risky.",
21
21
  evidence: "A list of the tools each agent can call and which need approval." },
22
- { ref: "LLM04:2026", title: "Supply Chain", inCode: "partly", rules: ["deps.unpinned-version", "deps.install-script"],
22
+ { ref: "LLM04:2026", title: "Supply Chain", inCode: "partly", rules: ["deps.unpinned-version", "deps.install-script", "agent.config-runs-remote-code"],
23
23
  plain: "Models, datasets, plugins and packages come from others. Pin and check them like any dependency.",
24
24
  evidence: "Where each model and dataset comes from, and its licence." },
25
25
  { ref: "LLM05:2026", title: "Data and Model Poisoning", inCode: "no",
26
26
  plain: "Training, fine-tuning or retrieval data can be tampered with to change the model's behaviour.",
27
27
  evidence: "Data sources, who can change them, and checks on new data." },
28
- { ref: "LLM06:2026", title: "Unbounded Consumption", inCode: "partly", rules: ["llm.no-output-limit", "ai.call-not-logged"],
28
+ { ref: "LLM06:2026", title: "Unbounded Consumption", inCode: "partly", rules: ["llm.no-output-limit", "ai.call-not-logged", "llm.unbounded-agent-loop"],
29
29
  plain: "Limit output size, request rate and cost per user, so one person can't run up a bill or take the service down.",
30
30
  evidence: "Rate limits, spending alerts and usage monitoring." },
31
31
  { ref: "LLM07:2026", title: "Misinformation", inCode: "no",
@@ -56,7 +56,7 @@ export const cweTop25 = {
56
56
  { ref: "CWE-22, CWE-434", title: "Path traversal and dangerous uploads", inCode: "yes", rules: ["path.user-input", "upload.unrestricted"], plain: "File paths and uploads are limited to what's expected." },
57
57
  { ref: "CWE-502, CWE-20", title: "Unsafe deserialization and input validation", inCode: "partly", rules: ["deserialize.unsafe", "nosql.operator-input", "mass-assignment"], plain: "Untrusted data is validated and never turned back into objects unsafely." },
58
58
  { ref: "CWE-918", title: "Server-side request forgery", inCode: "yes", rules: ["ssrf.user-url"], plain: "The server doesn't fetch any address a user picks." },
59
- { ref: "CWE-200", title: "Exposure of sensitive information", inCode: "partly", rules: ["pii.logged", "pii.in-url", "log.secret", "error.stack-to-client", "build.sourcemaps-public", "secret.public-env"], plain: "Personal data, secrets and internals don't leak into logs, URLs, errors or the browser." },
59
+ { ref: "CWE-200", title: "Exposure of sensitive information", inCode: "partly", rules: ["pii.logged", "pii.in-url", "log.secret", "error.stack-to-client", "build.sourcemaps-public", "secret.public-env", "release.env-not-ignored"], plain: "Personal data, secrets and internals don't leak into logs, URLs, errors or the browser." },
60
60
  { ref: "CWE-770", title: "Resources without limits", inCode: "partly", rules: ["llm.no-output-limit"], plain: "Expensive work, including AI calls, has limits.", evidence: "Rate limits and quotas." },
61
61
  { ref: "CWE-306", title: "Missing authentication for a critical function", inCode: "no", plain: "Every sensitive endpoint requires a signed-in user. Needs a route-by-route review.", evidence: "A list of endpoints and their authentication." },
62
62
  { ref: "CWE-787, 416, 125, 120, 476, 121, 122", title: "Memory safety", inCode: "no", plain: "Buffer and pointer errors in C and C++. Lintsure doesn't check these languages; use a memory-safe language or a dedicated tool.", evidence: "Results from a C/C++ analyser or fuzzing." },
@@ -23,14 +23,14 @@ export const owaspTop10 = {
23
23
  plain: "Whether each endpoint checks that the record belongs to the person asking (often called IDOR). A line-by-line code check can't tell; it needs design review and testing with two accounts.",
24
24
  evidence: "Access control tests per role, or a penetration test report." },
25
25
  { ref: "A02:2025", title: "Security Misconfiguration", inCode: "partly",
26
- rules: ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "xml.external-entities", "cors.any-origin", "session.cookie-insecure", "error.stack-to-client", "build.sourcemaps-public"],
26
+ rules: ["config.debug-on", "agent.permissions-allow-all", "config.allowed-hosts-any", "config.default-secret-key", "xml.external-entities", "cors.any-origin", "session.cookie-insecure", "error.stack-to-client", "build.sourcemaps-public", "release.env-not-ignored"],
27
27
  plain: "Safe settings by default: debug off, real host names, strong secret keys, cookies marked secure, XML parsers that don't load outside files, and errors that don't reveal internals.",
28
28
  evidence: "Production configuration and a hardening checklist." },
29
29
  { ref: "A02:2025 (deployed settings)", title: "Server, cloud and header configuration in production", inCode: "no",
30
30
  plain: "What is actually running: server and cloud settings, open ports, default accounts, security headers on real responses. These need a scan of the deployed system.",
31
31
  evidence: "Infrastructure configuration, a header scan and a cloud configuration review." },
32
32
  { ref: "A03:2025", title: "Software Supply Chain Failures", inCode: "partly",
33
- rules: ["deps.unpinned-version", "deps.install-script", "ci.action-unpinned", "ci.prt-checkout-head", "ci.write-all-permissions", "ci.script-injection", "update.unverified-download"],
33
+ rules: ["deps.unpinned-version", "deps.install-script", "agent.config-runs-remote-code", "agent.instructions-unsafe", "ci.action-unpinned", "ci.prt-checkout-head", "ci.write-all-permissions", "ci.script-injection", "update.unverified-download"],
34
34
  plain: "The code you didn't write: dependencies, build tools and CI. Versions should be pinned, install scripts shouldn't fetch code, CI actions should be pinned, untrusted pull requests must not run with your secrets, and text from issues or pull requests must never become part of a CI command.",
35
35
  evidence: "Lockfiles, CI workflow files and the dependency update process." },
36
36
  { ref: "A03:2025 (known vulnerabilities)", title: "Dependencies with known vulnerabilities", inCode: "no",
@@ -55,7 +55,7 @@ export const owaspTop10 = {
55
55
  plain: "Thinking through how a feature could be misused before building it: rate limits, business rule abuse, trust boundaries. Code checks can't show whether this happened.",
56
56
  evidence: "Threat models or security design reviews for key features." },
57
57
  { ref: "A07:2025", title: "Authentication Failures", inCode: "partly",
58
- rules: ["auth.hardcoded-password", "jwt.no-expiry", "jwt.unverified", "config.default-secret-key", "session.cookie-insecure", "secret.in-source", "transport.tls-verify-off"],
58
+ rules: ["auth.hardcoded-password", "jwt.no-expiry", "jwt.unverified", "config.default-secret-key", "session.cookie-insecure", "secret.in-source", "transport.tls-verify-off", "auth.no-rate-limit"],
59
59
  plain: "Logins and sessions that hold up: no passwords in code, strong secrets, tokens that expire and are verified, and session cookies protected from scripts and plain HTTP.",
60
60
  evidence: "Login, session and token settings." },
61
61
  { ref: "A07:2025 (login protections)", title: "Brute-force protection, MFA and account recovery", inCode: "no",
@@ -3,11 +3,19 @@ import type { Control, Rule } from "./types.js";
3
3
  export interface Pack {
4
4
  /** Package name, for example "@lintsure/pack-pci-dss". */
5
5
  id: string;
6
+ /** Pack version. Goes into the policy fingerprint, so a pack update gives a new code. */
7
+ version?: string;
6
8
  rules: Rule[];
7
9
  knowledge: FrameworkKnowledge[];
8
10
  /** Controls this pack adds to rules that already exist, by rule id. */
9
11
  forExisting?: Record<string, Control[]>;
10
12
  }
13
+ /** Packs registered in this process, as "id@version", for the policy fingerprint. */
14
+ export declare const packsLoaded: string[];
15
+ /** Which pack added each framework, so a scan only uses the packs its own repo lists (the MCP server scans many repos). */
16
+ export declare const packFrameworks: Map<string, string>;
17
+ /** Packs loaded because some repo's lintsure.config.yaml listed them. Packs registered in code apply to every scan. */
18
+ export declare const configPacks: Set<string>;
11
19
  /** Adds a pack's frameworks, rules and mappings. Loading the same pack twice does nothing. */
12
20
  export declare function registerPack(p: Pack): void;
13
21
  /** Loads packs by name. Returns the names that couldn't be loaded (wrong name or not installed). */
package/dist/src/packs.js CHANGED
@@ -8,16 +8,24 @@ import { knowledge } from "./knowledge/index.js";
8
8
  import { rules } from "./rules/index.js";
9
9
  const PACK_NAME = /^@lintsure\/pack-[a-z0-9-]+$/;
10
10
  const loaded = new Set();
11
+ /** Packs registered in this process, as "id@version", for the policy fingerprint. */
12
+ export const packsLoaded = [];
13
+ /** Which pack added each framework, so a scan only uses the packs its own repo lists (the MCP server scans many repos). */
14
+ export const packFrameworks = new Map();
15
+ /** Packs loaded because some repo's lintsure.config.yaml listed them. Packs registered in code apply to every scan. */
16
+ export const configPacks = new Set();
11
17
  /** Adds a pack's frameworks, rules and mappings. Loading the same pack twice does nothing. */
12
18
  export function registerPack(p) {
13
19
  if (loaded.has(p.id))
14
20
  return;
15
21
  loaded.add(p.id);
22
+ packsLoaded.push(`${p.id}@${p.version ?? "0"}`);
16
23
  for (const [id, cs] of Object.entries(p.forExisting ?? {}))
17
24
  rules.find((r) => r.id === id)?.controls.push(...cs);
18
25
  rules.push(...p.rules);
19
26
  for (const k of p.knowledge) {
20
27
  knowledge.push(k);
28
+ packFrameworks.set(k.id, p.id);
21
29
  if (!ALL_FRAMEWORKS.includes(k.id))
22
30
  ALL_FRAMEWORKS.push(k.id);
23
31
  }
@@ -33,7 +41,9 @@ export async function loadPacks(names) {
33
41
  }
34
42
  try {
35
43
  const mod = await import(pathToFileURL(require.resolve(name)).href);
36
- registerPack((mod.default ?? mod.pack));
44
+ const pack = (mod.default ?? mod.pack);
45
+ registerPack(pack);
46
+ configPacks.add(pack.id);
37
47
  }
38
48
  catch {
39
49
  failed.push(name);
@@ -0,0 +1,3 @@
1
+ import type { Rule } from "./types.js";
2
+ /** The rules a described feature most likely runs into, best match first. Pure. */
3
+ export declare function checksFor(description: string, max?: number): Rule[];
@@ -0,0 +1,35 @@
1
+ // Before code is written: which Lintsure checks a planned feature is likely to meet, so the agent can avoid them.
2
+ // Plain word matching against what each rule is about, plus a few feature words. No model, same answer every time.
3
+ import { rules } from "./rules/index.js";
4
+ // Feature words people use, mapped to the rule id parts they usually lead to.
5
+ const TOPICS = [
6
+ [/\b(log ?in|sign ?(in|up)|auth\w*|password|session|account|oauth|sso)\b/i, ["session", "jwt", "password", "csrf", "cookie", "redirect", "secret"]],
7
+ [/\b(upload\w*|files?|images?|attachments?|download\w*)\b/i, ["upload", "path"]],
8
+ [/\b(pay\w*|stripe|checkout|billing|cards?|invoices?)\b/i, ["secret", "webhook", "transport", "pii"]],
9
+ [/\b(ai|llm|gpt|claude|chat\w*|prompts?|agents?|openai|anthropic|model)\b/i, ["ai", "llm"]],
10
+ [/\b(databases?|sql|quer\w*|supabase|postgres|tables?|prisma|mongo\w*)\b/i, ["sql", "supabase", "nosql", "mass"]],
11
+ [/\b(users?|profiles?|emails?|personal|customers?|analytics|tracking|gdpr)\b/i, ["pii", "gdpr"]],
12
+ [/\b(webhooks?|fetch\w*|urls?|proxy|crawl\w*|scrap\w*|preview)\b/i, ["ssrf", "transport", "redirect"]],
13
+ [/\b(api|endpoints?|routes?|server|backend|handlers?)\b/i, ["cors", "error", "sql", "mass", "config"]],
14
+ [/\b(shell|commands?|exec\w*|scripts?|cli|deploy\w*|ci|github actions?|workflows?)\b/i, ["cmd", "ci", "deps", "code"]],
15
+ [/\b(hooks?|mcp|cursor|claude code|agent config)\b/i, ["agent"]],
16
+ [/\b(env\w*|keys?|secrets?|tokens?|config\w*)\b/i, ["secret", "release", "config"]],
17
+ [/\b(html|render\w*|templates?|markdown|comments?|rich text)\b/i, ["xss", "template"]],
18
+ [/\b(mobile|android|ios|react native|expo)\b/i, ["mobile"]],
19
+ ];
20
+ const STOP = new Set(["with", "that", "this", "from", "into", "user", "users", "make", "build", "want", "need", "should", "will", "page", "feature", "add", "new", "the", "and", "for", "mode", "toggle", "button", "show", "list", "screen", "simple", "dark", "light"]);
21
+ /** The rules a described feature most likely runs into, best match first. Pure. */
22
+ export function checksFor(description, max = 8) {
23
+ const text = description.slice(0, 2000);
24
+ const parts = new Set(TOPICS.filter(([re]) => re.test(text)).flatMap(([, p]) => p));
25
+ const words = new Set((text.toLowerCase().match(/[a-z]{4,}/g) ?? []).filter((w) => !STOP.has(w)));
26
+ const scored = rules.map((r) => {
27
+ const idParts = r.id.split(/[.-]/);
28
+ let s = idParts.some((p) => parts.has(p)) ? 3 : 0;
29
+ for (const w of new Set(`${r.title} ${r.id}`.toLowerCase().match(/[a-z]{4,}/g) ?? []))
30
+ if (words.has(w))
31
+ s += 2;
32
+ return { r, s: s + (s && r.severity === "high" ? 1 : 0) };
33
+ });
34
+ return scored.filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.r.id.localeCompare(b.r.id)).slice(0, max).map((x) => x.r);
35
+ }
@@ -0,0 +1,32 @@
1
+ export type Reach = {
2
+ status: "entry" | "reachable" | "unreachable" | "unknown";
3
+ via?: string[];
4
+ };
5
+ export interface Graph {
6
+ importers: Map<string, Set<string>>;
7
+ imports: Map<string, Set<string>>;
8
+ entries: Set<string>;
9
+ unresolved: Map<string, string[]>;
10
+ /** Filled on first use: for each reached file, the file that imports it on a shortest path from an entry. */
11
+ parent?: Map<string, string>;
12
+ unresolvedNames?: Set<string>;
13
+ }
14
+ /** Literal specifiers a file imports. Pure. */
15
+ export declare function specifiers(text: string): string[];
16
+ export declare function stripJsonComments(text: string): string;
17
+ /** Path aliases from a tsconfig.json text (comments allowed): baseUrl and paths, as [prefix, targets] pairs. Pure. */
18
+ export declare function tsAliases(text: string | null, root?: string): {
19
+ root: string;
20
+ baseUrl: string | null;
21
+ paths: [string, string[], boolean][];
22
+ };
23
+ /** The project file a specifier points at, "external" for a package, or null when it looks local but can't be found. Pure. */
24
+ export declare function resolveSpec(from: string, spec: string, files: Set<string>, alias: ReturnType<typeof tsAliases>): string | "external" | null;
25
+ /** Files a project starts from that no code imports: package.json main/module/bin/exports, and scripts an HTML page
26
+ * loads with <script src>. Paths come back relative to the project root. Pure. */
27
+ export declare function declaredEntries(pkgs: Record<string, string>, html: Record<string, string>, files: Set<string>): string[];
28
+ /** Builds the import graph and the entry points from the project's JS/TS files. Pure. */
29
+ export declare function buildGraph(files: Record<string, string>, tsconfigs?: string | null | Record<string, string>, pkgDirs?: string[], extraEntries?: string[]): Graph;
30
+ /** Whether an entry point reaches this file, with the shortest chain entry -> ... -> file. "unknown" when nothing
31
+ * reaches it but an unresolved import somewhere could be pointing at it (same file name). Pure. */
32
+ export declare function reachOf(g: Graph, file: string): Reach;