@evobug_com/safe-ts-skill 0.0.0-stage → 0.5.1

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,870 @@
1
+ #!/usr/bin/env node
2
+ // The migration census: what `safe-ts check --idiomatic` reports, per rule and per directory
3
+ // (the idiomatic rules see `x.tag === ...`, `if (isErr(x)) return x`,
4
+ // `'key' in` on a union, casts in tests, `unwrapOr(x, undefined)`, `JsonNull` in app state),
5
+ // the hand-rolled patterns no rule reports (loading/error/data trios, sentinels, string
6
+ // if-chains, boolean flag sets, raw fetch, try/catch, casts, ...), the escape hatches
7
+ // (`unsafe`, `panic`, `trust`, `LegacyNull`, `safe-ts-ignore`, legacy markers, ...), and which
8
+ // SAFE-TS features the code already uses.
9
+ //
10
+ // node census.mjs [dirs or files...] a report (default: the current directory)
11
+ // node census.mjs --json > census.json the same as JSON
12
+ // node census.mjs --show loading-flag every place one pattern was found
13
+ // node census.mjs --write-baseline census-baseline.json
14
+ // node census.mjs --baseline census-baseline.json exit 1 if any count rose (a gate)
15
+ //
16
+ // Options: --depth <n> (directory grouping, default 2), --no-check (patterns only),
17
+ // --no-idiomatic (leave the idiomatic rules out), --entry <file> (check only from these
18
+ // entries; repeatable; default: every scanned file, so tests, scripts and files nothing
19
+ // imports are counted like the patterns are).
20
+ //
21
+ // The patterns are regular expressions over the text, so they are a map of where to look,
22
+ // not findings: read each place before changing it. Comment lines are skipped, except for
23
+ // `safe-ts-ignore` comments, which are counted. The skill's own folder isn't scanned.
24
+ //
25
+ // This file runs before SAFE-TS is installed, so it can't import std: each call that can fail
26
+ // goes through `orExit`, which names what failed and exits 2, and dictionaries are `Map`s. It
27
+ // passes oxlint with the SAFE-TS preset, so a project that lints every file needn't exclude it.
28
+ import { execFileSync, spawnSync } from "node:child_process";
29
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
30
+ import { dirname, extname, join, relative, resolve, sep } from "node:path";
31
+ import { fileURLToPath } from "node:url";
32
+
33
+ import { findSafeTs } from "./safe-ts.mjs";
34
+
35
+ /**
36
+ * Runs `step` and returns its value; when it throws, prints `census: <what>: <why>` and exits 2.
37
+ * @template T
38
+ * @param {string} what
39
+ * @param {() => T} step
40
+ * @returns {T}
41
+ */
42
+ function orExit(what, step) {
43
+ try {
44
+ return step();
45
+ } catch (error) {
46
+ console.error(`census: ${what}: ${error instanceof Error ? error.message : String(error)}`);
47
+ process.exit(2);
48
+ }
49
+ }
50
+
51
+ /** A regular expression built from this file's own pattern text. */
52
+ const regex = (source) => orExit("a pattern of this script doesn't compile", () => new RegExp(source));
53
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
54
+ /** A count per key (file, directory, rule, ...). */
55
+ class Counts extends Map {
56
+ /** Adds `n` to `key`'s count. */
57
+ add(key, n = 1) {
58
+ this.set(key, (this.get(key) ?? 0) + n);
59
+ return this;
60
+ }
61
+ }
62
+ /** A `Map` as a plain object for the JSON report (`fromEntries` defines each key, so `__proto__` is safe). */
63
+ const toObject = (map, value = (v) => v) => Object.fromEntries([...map].map(([key, v]) => [key, value(v)]));
64
+ /** A plain object read from JSON (a baseline) as a `Map`. */
65
+ const toMap = (object) => new Map(object !== null && typeof object === "object" ? Object.entries(object) : []);
66
+ /** A count read from a baseline: 0 when absent; anything but a whole number stops the gate. */
67
+ const countOf = (value, where) => {
68
+ if (value === undefined) return 0;
69
+ if (Number.isInteger(value) && value >= 0) return value;
70
+ console.error(`census: the baseline's ${where} is ${String(value)}, not a count; write it again with --write-baseline`);
71
+ process.exit(2);
72
+ };
73
+
74
+ // ---- options -----------------------------------------------------------------------------
75
+
76
+ const args = process.argv.slice(2);
77
+ const option = (name) => {
78
+ const i = args.indexOf(name);
79
+ return i === -1 ? undefined : args[i + 1];
80
+ };
81
+ const repeated = (name) => args.flatMap((a, i) => (a === name && args[i + 1] !== undefined ? [args[i + 1]] : []));
82
+ const VALUED = new Set(["--depth", "--show", "--baseline", "--write-baseline", "--entry"]);
83
+ const targets = args.filter((a, i) => !a.startsWith("--") && !VALUED.has(args[i - 1]));
84
+ const depth = Number(option("--depth") ?? 2);
85
+ const root = process.cwd();
86
+ const EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts", ".vue", ".jsx"]);
87
+ const SKIPPED_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage", "target", ".output", ".nuxt", ".next", ".cache", ".safe-ts"]);
88
+ // This skill's folder (when the script runs from it), so a copy in `.claude/skills/` is never
89
+ // counted. A copy of the scripts in the project's `scripts/` has no SKILL.md beside it.
90
+ const SKILL_DIR = (() => {
91
+ const dir = dirname(dirname(fileURLToPath(import.meta.url)));
92
+ return existsSync(join(dir, "SKILL.md")) ? dir : undefined;
93
+ })();
94
+
95
+ /** A test file, as the checker sees one: `*.test.*` / `*.spec.*`, a test directory, or a test runner imported. */
96
+ const TEST_NAME = /(?:^|\/)(?:test|tests|__tests__|__mocks__)\/|\.(?:test|spec)\.[^/]*$/;
97
+ const TEST_RUNNER = /\bfrom\s*["'](?:vitest|node:test|bun:test|@jest\/globals|vite-plus\/test|mocha)["']/;
98
+
99
+ // ---- the patterns ------------------------------------------------------------------------
100
+
101
+ const LOADING_NAME = String.raw`(?:is|set)?(?:[Ll]oading|[Bb]usy|[Pp]ending|[Ff]etching|[Ss]aving|[Ss]ubmitting|[Rr]efreshing|[Ww]orking|[Ii]nFlight)\w*`;
102
+ const ERROR_NAME = String.raw`\w*(?:[Ee]rror|[Ee]rr|[Ff]ailure|[Ff]ailed|[Pp]roblem)\w*`;
103
+ // `<E>`, `<Option<E>>`: type arguments, one level of nesting.
104
+ const TYPE_ARGS = String.raw`(?:<(?:[^<>]|<[^<>]*>)*>)?`;
105
+ const BOOL_STATE = String.raw`(?:ref|shallowRef|useState)(?:<boolean>)?\(\s*(?:true|false)\s*\)`;
106
+
107
+ // `x as T`: a value, then `as`, then something that starts a type (a capitalised name, an
108
+ // object, tuple or function type, or a built-in type keyword), so English text in a template
109
+ // ("saved as draft") doesn't count. `as const` isn't a cast.
110
+ const CAST = /(?:[\w$)\]}>'"`]|\?\.)\s+as\s+(?:[A-Z{[(]|(?:string|number|boolean|bigint|symbol|object|unknown|never|any|undefined|readonly|keyof|typeof)\b)/;
111
+ // `import { a as b }`, `export * as ns from`, `export { a as b }`: renames, not casts. The
112
+ // lines inside a list that spans several lines (` type Building as SimBuilding,`) are skipped
113
+ // too (see `renameLines`).
114
+ const REEXPORT = /^\s*(?:import\b|export\s*(?:\*|\{|type\s*\{))/;
115
+ // The start of an import or export list left open on its line: `import {`, `import type {`,
116
+ // `import React, {`, `export {`, `export type {`. Not `export const x = {`.
117
+ const OPEN_LIST = /^\s*(?:import\b[^'"`]*\{|export\s+(?:type\s+)?\{)[^}]*$/;
118
+ // A mapped type's key remapping, `[K in Keys as NewKey]`: the `as` renames keys, it isn't a cast.
119
+ const KEY_REMAP = /(\[\s*[\w$]+\s+in\s+(?:[^[\]\n]|\[[^\]\n]*\])*?)\s+as\s+/g;
120
+ /** The line with what only looks like a cast taken out: mapped-type key remapping. */
121
+ const withoutRenames = (text) => text.replaceAll(KEY_REMAP, "$1 ");
122
+
123
+ /**
124
+ * Each pattern: what it finds, where the catalogue says what to write instead, and whether
125
+ * the architecture gate holds it down (`gate`: its count may only fall).
126
+ * `line` is tested on each line that isn't a comment (`comment`: on each comment line instead).
127
+ */
128
+ const PATTERNS = [
129
+ {
130
+ id: "loading-flag",
131
+ what: "a boolean loading/busy flag (ref, useState or let)",
132
+ see: "patterns-vue.md#a-loading-error-data-trio / patterns-react.md#a-loading-error-data-trio",
133
+ gate: true,
134
+ line: regex(
135
+ String.raw`(?:\b(?:const|let)\s+${LOADING_NAME}\s*=\s*${BOOL_STATE})|(?:\bconst\s*\[\s*${LOADING_NAME}\s*,\s*\w+\s*\]\s*=\s*${BOOL_STATE})|(?:\blet\s+${LOADING_NAME}\s*=\s*(?:true|false)\b)`,
136
+ ),
137
+ },
138
+ {
139
+ id: "error-state",
140
+ what: "an error kept in its own state: ref('')/ref(null)/ref<E>()/shallowRef<Option<E>>()/useState('') named error, failed, ...",
141
+ see: "patterns-vue.md#a-loading-error-data-trio / patterns-vue.md#a-result-returned-to-vue",
142
+ gate: true,
143
+ line: regex(
144
+ String.raw`(?:\b(?:const|let)\s+${ERROR_NAME}\s*=\s*(?:ref|shallowRef)${TYPE_ARGS}\(\s*(?:''|""|null|undefined)?\s*\))|(?:\bconst\s*\[\s*${ERROR_NAME}\s*,\s*\w+\s*\]\s*=\s*useState${TYPE_ARGS}\(\s*(?:''|""|null|undefined)?\s*\))`,
145
+ ),
146
+ },
147
+ {
148
+ id: "error-or-undefined",
149
+ what: "a state set to `isErr(r) ? r.error : undefined`: its undefined means both \"not tried yet\" and \"it worked\"; one Enum names every state",
150
+ see: "patterns-vue.md#a-result-returned-to-vue / patterns-react.md#a-result-returned-to-react",
151
+ gate: true,
152
+ line: /\bisErr\((\w+)\)\s*\?\s*\1\.error\s*:\s*undefined\b/,
153
+ },
154
+ {
155
+ id: "empty-string-sentinel",
156
+ what: "'' compared or returned: check whether it means \"none\" or \"no error\"",
157
+ see: "patterns-core.md#a-sentinel-value",
158
+ gate: true,
159
+ line: /(?:[!=]==?\s*(?:''|""))|(?:(?:''|"")\s*[!=]==?)|(?:\breturn\s+(?:''|"")\s*;?\s*$)/,
160
+ },
161
+ {
162
+ id: "minus-one-sentinel",
163
+ what: "-1 compared, returned or assigned (often \"not found\" or \"none selected\"); a named constant (`const NONE = -1`) counts once, at its declaration",
164
+ see: "patterns-core.md#a-sentinel-value",
165
+ gate: true,
166
+ // A literal -1 only: `x === NONE`, `.fill(NONE)` aren't counted, so a sentinel the project
167
+ // names once (in typed arrays or a file format, where `Option` can't go) is one entry, its
168
+ // declaration, which `NAMED_SENTINEL` also counts when it ends in `as const` or a type.
169
+ line: /(?:[!=]==?\s*-1\b)|(?:\breturn\s+-1\b)|(?:[^=!<>]=\s*-1\s*[;,)]?\s*$)|(?:\(\s*-1\s*\))/,
170
+ or: /^\s*(?:export\s+)?(?:const|(?:(?:private|protected|public)\s+)?static\s+readonly)\s+[A-Z][A-Z0-9_]*\s*(?::\s*[^=]+)?=\s*-1\b/,
171
+ },
172
+ {
173
+ id: "zero-sentinel",
174
+ what: "an id or index that starts at 0 (check whether 0 means \"none\")",
175
+ see: "patterns-core.md#a-sentinel-value",
176
+ gate: false,
177
+ line: /\b(?:const|let)\s+\w*(?:[Ii]d|[Ii]ndex|[Ss]elected|[Aa]ctive|[Cc]urrent)\s*=\s*(?:(?:ref|shallowRef|useState)(?:<number>)?\(\s*0\s*\)|0\s*;?\s*$)/,
178
+ },
179
+ {
180
+ id: "boolean-state",
181
+ what: "a boolean state (ref, useState); 3 or more in a file are listed under boolean-flag-files",
182
+ see: "patterns-core.md#a-set-of-boolean-flags",
183
+ gate: false,
184
+ line: regex(String.raw`\b(?:const|let)\s+(?:\[\s*)?\w+(?:\s*,\s*\w+\s*\])?\s*=\s*${BOOL_STATE}`),
185
+ },
186
+ {
187
+ id: "raw-fetch",
188
+ what: "fetch(...) or an HTTP client called directly (axios, XMLHttpRequest)",
189
+ see: "patterns-core.md#requests-return-a-result",
190
+ gate: true,
191
+ line: /(?:(?<![.\w$])fetch\s*\()|(?:\baxios(?:\.\w+)?\s*\()|(?:\bnew\s+XMLHttpRequest\b)/,
192
+ },
193
+ {
194
+ id: "try-catch",
195
+ what: "a try block (around your own code, a Result is the answer; around a library, unsafe or a safe version)",
196
+ see: "patterns-core.md#try-and-catch-around-your-own-code",
197
+ gate: true,
198
+ line: /\btry\s*\{/,
199
+ },
200
+ {
201
+ id: "promise-catch",
202
+ what: ".catch(...) on a promise (a promise of a Result can't reject; a .catch on it hides that)",
203
+ see: "patterns-core.md#try-and-catch-around-your-own-code",
204
+ gate: true,
205
+ line: /\.catch\s*\(/,
206
+ },
207
+ {
208
+ id: "as-cast",
209
+ what: "an `as` cast (as const excluded)",
210
+ see: "patterns-core.md#a-cast",
211
+ gate: true,
212
+ line: CAST,
213
+ skip: REEXPORT,
214
+ renames: true,
215
+ },
216
+ {
217
+ id: "double-cast",
218
+ what: "as unknown as / as never / as any",
219
+ see: "patterns-core.md#a-cast",
220
+ gate: true,
221
+ line: /\bas\s+(?:unknown\s+as|never|any)\b/,
222
+ skip: REEXPORT,
223
+ renames: true,
224
+ },
225
+ {
226
+ id: "json-parse",
227
+ what: "JSON.parse(...) (parseJson<T> checks the shape)",
228
+ see: "patterns-core.md#json-and-storage",
229
+ gate: true,
230
+ line: /\bJSON\.parse\s*\(/,
231
+ },
232
+ {
233
+ id: "raw-storage",
234
+ what: "localStorage / sessionStorage called directly",
235
+ see: "patterns-core.md#json-and-storage",
236
+ gate: true,
237
+ line: /\b(?:localStorage|sessionStorage)\.(?:getItem|setItem|removeItem|key)\s*\(/,
238
+ },
239
+ {
240
+ id: "unsafe-async",
241
+ what: "unsafeAsync(...) (around your own Result-returning code, pass Panic)",
242
+ see: "escape-hatches.md",
243
+ gate: true,
244
+ line: /\bunsafeAsync\s*\(/,
245
+ },
246
+ {
247
+ id: "unsafe",
248
+ what: "unsafe(...)",
249
+ see: "escape-hatches.md",
250
+ gate: true,
251
+ line: /(?<![\w$.])unsafe\s*\(/,
252
+ },
253
+ {
254
+ id: "unexplained-unsafe",
255
+ what: "unsafe(...)/unsafeAsync(...) with no comment on its line or the line above",
256
+ see: "escape-hatches.md",
257
+ gate: true,
258
+ line: /(?<![\w$.])unsafe(?:Async)?\s*\(/,
259
+ needsReason: true,
260
+ },
261
+ {
262
+ id: "panic",
263
+ what: "panic(...) (only for invariants; never for loading or server data)",
264
+ see: "escape-hatches.md",
265
+ gate: true,
266
+ line: /(?<![\w$.])panic\s*\(/,
267
+ },
268
+ {
269
+ id: "void-call",
270
+ what: "void f(...): a Result or promise dropped on purpose",
271
+ see: "escape-hatches.md",
272
+ gate: true,
273
+ line: /\bvoid\s+[\w$.]+\s*\(/,
274
+ },
275
+ {
276
+ id: "trust",
277
+ what: "trust<T>(value): a trusted boundary, typed without a check",
278
+ see: "escape-hatches.md",
279
+ gate: true,
280
+ line: /(?<![\w$.])trust\s*(?:<[^>]*>\s*)?\(/,
281
+ },
282
+ {
283
+ id: "legacy-null",
284
+ what: "LegacyNull: strict code still taking null from callers not migrated yet (a bridge, meant to go)",
285
+ see: "escape-hatches.md",
286
+ gate: true,
287
+ line: /\bLegacyNull\b/,
288
+ skip: /^\s*import\b/,
289
+ },
290
+ {
291
+ id: "safe-ts-ignore",
292
+ what: "// safe-ts-ignore <rule>: <reason> (and -file, and <!-- --> in templates): a finding silenced",
293
+ see: "escape-hatches.md",
294
+ gate: true,
295
+ comment: true,
296
+ line: /^\s*(?:\/\/|\/\*|<!--)\s*safe-ts-ignore(?:-file)?\b/,
297
+ },
298
+ {
299
+ id: "module-let",
300
+ what: "a `let` at the top of a .ts module (module state); not in test files",
301
+ see: "patterns-vue.md#module-state / patterns-react.md#module-state",
302
+ gate: true,
303
+ line: /^(?:export\s+)?let\s+[\w$]/,
304
+ // A test file's `let errors: string[]` that `beforeEach` resets is the runner's idiom, not
305
+ // app state: each test file is its own module. `no-mutable-global` still sees them.
306
+ only: (file, test) => !file.endsWith(".vue") && !test,
307
+ },
308
+ ];
309
+
310
+ /**
311
+ * Rules whose findings have a catalogue entry: the idiomatic rules a checker-driven migration
312
+ * trips over, and the ones its first census is full of. The report names the entry.
313
+ */
314
+ const RULE_SEE = new Map([
315
+ ["prefer-is-over-tag", "patterns-core.md#reading-an-enum-one-style"],
316
+ ["prefer-constructor-tag", "patterns-core.md#reading-an-enum-one-style"],
317
+ ["prefer-q", "patterns-core.md#passing-an-error-up"],
318
+ ["prefer-map-err", "patterns-core.md#passing-an-error-up"],
319
+ ["q-undeclared-error", "patterns-core.md#passing-an-error-up"],
320
+ ["key-presence-union", "patterns-core.md#a-union-told-apart-by-keys"],
321
+ ["no-type-predicate", "patterns-core.md#a-hand-written-type-guard"],
322
+ ["undeclared-return-type", "patterns-core.md#a-function-result-the-checker-cannot-read"],
323
+ ["unused-code", "patterns-core.md#code-nothing-reaches"],
324
+ ["unused-private", "patterns-core.md#code-nothing-reaches"],
325
+ ["unreachable-code", "patterns-core.md#code-nothing-reaches"],
326
+ ["unknown-event", "patterns-core.md#event-names-at-both-ends"],
327
+ ["unmatched-event", "patterns-core.md#event-names-at-both-ends"],
328
+ ["no-overload", "patterns-core.md#a-hand-written-type-guard"],
329
+ ["cast-in-test", "patterns-core.md#casts-in-tests"],
330
+ ["no-swallowed-error", "patterns-core.md#a-failure-turned-into-undefined"],
331
+ ["sentinel-error", "patterns-core.md#a-sentinel-value"],
332
+ ["strict-truthiness", "patterns-core.md#a-sentinel-value"],
333
+ ["compare-misses-undefined", "patterns-core.md#a-sentinel-value"],
334
+ ["no-ts-suppression", "escape-hatches.md#when-each-is-allowed"],
335
+ ["no-lint-suppression", "escape-hatches.md#when-each-is-allowed"],
336
+ ["unlisted-marker", "escape-hatches.md#when-each-is-allowed"],
337
+ ["no-unchecked-declare", "escape-hatches.md#when-each-is-allowed"],
338
+ ["no-method-signature", "patterns-core.md#a-method-in-an-interface"],
339
+ ["override-parameter", "patterns-core.md#an-override-that-asks-for-more"],
340
+ ["implicit-propagation", "patterns-core.md#a-method-the-language-calls-for-you"],
341
+ ["missing-mut", "patterns-core.md#a-parameter-the-function-changes"],
342
+ ["aliased-mut", "patterns-core.md#a-parameter-the-function-changes"],
343
+ ["mutating-getter", "patterns-core.md#a-parameter-the-function-changes"],
344
+ ["covariant-alias", "patterns-core.md#a-parameter-the-function-changes"],
345
+ ["union-tag-write", "patterns-core.md#a-parameter-the-function-changes"],
346
+ ["readonly-dropped", "patterns-core.md#a-parameter-the-function-changes"],
347
+ ["unbounded-spread", "patterns-core.md#a-list-spread-into-mathmax-or-push"],
348
+ ["not-found-index", "patterns-core.md#a-not-found-answer-used-as-a-value"],
349
+ ["divide-by-length", "patterns-core.md#a-not-found-answer-used-as-a-value"],
350
+ ["sparse-array-write", "patterns-core.md#a-not-found-answer-used-as-a-value"],
351
+ ["number-parse-nan", "patterns-core.md#a-not-found-answer-used-as-a-value"],
352
+ ["regex-last-index", "patterns-core.md#a-regex-with-the-g-flag-tested-again"],
353
+ ["promise-as-value", "patterns-core.md#a-promise-used-as-its-value"],
354
+ ["floating-promise", "patterns-core.md#a-promise-used-as-its-value"],
355
+ ["use-after-consume", "patterns-core.md#a-value-used-after-it-was-used-up"],
356
+ ["stale-across-await", "patterns-core.md#state-across-an-await"],
357
+ ["late-listener", "patterns-core.md#what-happened-during-an-await"],
358
+ ["unused-answer", "patterns-core.md#an-answer-nobody-reads"],
359
+ ["misplaced-argument", "patterns-core.md#an-answer-nobody-reads"],
360
+ ["superseded-task-write", "patterns-core.md#what-happened-during-an-await"],
361
+ ["promise-never-settles", "patterns-core.md#a-promise-that-never-settles-a-resource-kept"],
362
+ ["unreleased-resource", "patterns-core.md#a-promise-that-never-settles-a-resource-kept"],
363
+ ["unbalanced-update", "patterns-core.md#a-change-left-behind-a-test-already-decided"],
364
+ ["decided-test", "patterns-core.md#a-change-left-behind-a-test-already-decided"],
365
+ ["test-without-assertion", "patterns-core.md#a-test-that-cannot-fail"],
366
+ ["assertion-cannot-fail", "patterns-core.md#a-test-that-cannot-fail"],
367
+ ["deferred-assertion", "patterns-core.md#a-test-that-cannot-fail"],
368
+ ["swallowed-assertion", "patterns-core.md#a-test-that-cannot-fail"],
369
+ ["focused-test", "patterns-core.md#a-test-that-cannot-fail"],
370
+ ["skipped-test", "patterns-core.md#a-test-that-cannot-fail"],
371
+ ["duplicate-test-name", "patterns-core.md#a-test-that-cannot-fail"],
372
+ ["empty-test-suite", "patterns-core.md#a-test-that-cannot-fail"],
373
+ ["constructor-calls-override", "patterns-core.md#a-constructor-that-calls-an-overridable-method"],
374
+ ["no-optional-field", "patterns-core.md#an-optional-key"],
375
+ ["brand-constructor", "patterns-core.md#a-cast"],
376
+ ["markup-sink", "patterns-core.md#text-given-to-a-sink"],
377
+ ["url-sink", "patterns-core.md#text-given-to-a-sink"],
378
+ ["code-sink", "patterns-core.md#text-given-to-a-sink"],
379
+ ["command-sink", "patterns-core.md#text-given-to-a-sink"],
380
+ ["path-sink", "patterns-core.md#text-given-to-a-sink"],
381
+ ["pattern-sink", "patterns-core.md#text-given-to-a-sink"],
382
+ ["sql-sink", "patterns-core.md#text-given-to-a-sink"],
383
+ ["brand-sink", "patterns-core.md#text-given-to-a-sink"],
384
+ ["json-null-in-app", "patterns-core.md#an-api-that-sends-null"],
385
+ ["undefined-to-null", "patterns-core.md#an-api-that-sends-null"],
386
+ ["catch-on-result", "patterns-core.md#try-and-catch-around-your-own-code"],
387
+ ["misplaced-axios-check", "patterns-core.md#requests-return-a-result"],
388
+ ["unsafe-project-call", "patterns-core.md#a-bug-inside-a-result-returning-call"],
389
+ ["panic-on-loading", "patterns-core.md#panic-on-a-loading-state"],
390
+ ["latest-wins-counter", "patterns-vue.md#module-state"],
391
+ ["unused-task-signal", "patterns-vue.md#a-loading-error-data-trio"],
392
+ ["no-throw", "patterns-core.md#a-function-that-throws"],
393
+ ["failure-contract", "patterns-core.md#a-failure-behind-an-interface"],
394
+ ["fetch-signal", "patterns-core.md#requests-return-a-result"],
395
+ ["no-unchecked-cast", "patterns-core.md#a-cast"],
396
+ ["no-hidden-any", "patterns-core.md#json-and-storage"],
397
+ ["unbound-method", "patterns-core.md#a-method-handed-over-by-name"],
398
+ ["no-object-dictionary", "patterns-core.md#a-table-keyed-by-server-data"],
399
+ ["json-type", "patterns-core.md#a-cast"],
400
+ ["no-mutable-global", "patterns-vue.md#module-state / patterns-react.md#module-state"],
401
+ ["vue-split-state", "patterns-vue.md#a-loading-error-data-trio"],
402
+ ["vue-async-race", "patterns-vue.md#a-loading-error-data-trio"],
403
+ ["vue-ref-without-value", "patterns-vue.md#a-ref-filled-after-mount"],
404
+ ["vue-template-ref", "patterns-vue.md#a-template-ref"],
405
+ ["vue-v-html", "patterns-vue.md#v-html-and-bound-urls"],
406
+ ["vue-unsafe-url", "patterns-vue.md#v-html-and-bound-urls"],
407
+ ["exhaustive-dispatch", "patterns-core.md#a-closed-set-of-states"],
408
+ ["string-dispatch", "patterns-core.md#a-closed-set-of-states"],
409
+ ["negative-member-guard", "patterns-core.md#a-closed-set-of-states"],
410
+ ["code-range-compare", "patterns-core.md#a-closed-set-of-states"],
411
+ ["inline-member-set", "patterns-core.md#a-closed-set-of-states"],
412
+ ]);
413
+
414
+ /** SAFE-TS features: how often the code uses each (for the final pass). */
415
+ const FEATURES = [
416
+ ["useTask", /\buseTask\s*\(/],
417
+ ["reset()", /\.reset\s*\(\s*\)|\breset\s*\(\s*\)/],
418
+ ["AsyncState", /\bAsyncState\b/],
419
+ ["Enum<", /\bEnum\s*</],
420
+ ["constructors<", /\bconstructors\s*</],
421
+ ["match(", /(?<![\w$.])match\s*\(/],
422
+ ["<Match>", /<Match\b/],
423
+ ["is(", /(?<![\w$.])is\s*\(/],
424
+ ["variant(", /(?<![\w$.])variant\s*\(/],
425
+ ["q(", /(?<![\w$.])q\s*\(/],
426
+ ["mapErr(", /\bmapErr\s*\(/],
427
+ ["Option<", /\bOption\s*</],
428
+ ["parseJson<", /\bparseJson\s*</],
429
+ ["validate<", /\bvalidate\s*</],
430
+ ["useElement", /\buse(?:Optional)?Elements?\s*</],
431
+ ["safeHref(", /\bsafeHref\s*\(/],
432
+ ["PropagateError", /\bPropagateError\b/],
433
+ ["getOwn(", /\bgetOwn\s*\(/],
434
+ ["Open<", /\bOpen\s*</],
435
+ ["lookup(", /(?<![\w$.])lookup\s*\(/],
436
+ ["Patch<", /\bPatch\s*</],
437
+ ["defineSanitizer(", /\bdefineSanitizer\s*\(/],
438
+ ["Html/SafeUrl", /\b(?:Html|SafeUrl)\b/],
439
+ ["toBase64/fromBase64", /\b(?:toBase64|fromBase64(?:Bytes)?)\s*\(/],
440
+ ["fixture/testDouble", /\b(?:fixture|testDouble)\s*</],
441
+ ];
442
+
443
+ // ---- files -------------------------------------------------------------------------------
444
+
445
+ function sourceFiles() {
446
+ const roots = targets.length === 0 ? ["."] : targets;
447
+ const files = new Set();
448
+ for (const target of roots) {
449
+ const absolute = resolve(root, target);
450
+ if (!existsSync(absolute)) {
451
+ console.error(`census: not found: ${target}`);
452
+ process.exit(2);
453
+ }
454
+ if (orExit(`can't read ${target}`, () => statSync(absolute)).isFile()) {
455
+ files.add(absolute);
456
+ continue;
457
+ }
458
+ for (const file of gitFiles(absolute) ?? walk(absolute)) files.add(file);
459
+ }
460
+ const ownFile = (file) => SKILL_DIR !== undefined && (file === SKILL_DIR || file.startsWith(SKILL_DIR + sep));
461
+ return [...files]
462
+ .filter((f) => !ownFile(f) && EXTENSIONS.has(extname(f)) && !/\.d\.[cm]?ts$/.test(f))
463
+ .map((f) => relative(root, f).split(sep).join("/"))
464
+ .sort(byText);
465
+ }
466
+
467
+ /** Tracked and untracked-but-not-ignored files, when the directory is in a git repository. */
468
+ function gitFiles(dir) {
469
+ let out;
470
+ try {
471
+ out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], {
472
+ cwd: dir,
473
+ encoding: "utf8",
474
+ maxBuffer: 256 * 1024 * 1024,
475
+ stdio: ["ignore", "pipe", "ignore"],
476
+ });
477
+ } catch {
478
+ // Not a git repository, or no git: walk the folder instead.
479
+ return undefined;
480
+ }
481
+ return out.split("\0").filter((f) => f !== "").map((f) => join(dir, f)).filter((f) => existsSync(f));
482
+ }
483
+
484
+ function walk(dir) {
485
+ const entries = orExit(`can't list ${relative(root, dir) || "."}`, () => readdirSync(dir, { withFileTypes: true }));
486
+ return entries.flatMap((entry) => {
487
+ if (entry.isDirectory()) return SKIPPED_DIRS.has(entry.name) ? [] : walk(join(dir, entry.name));
488
+ return entry.isFile() ? [join(dir, entry.name)] : [];
489
+ });
490
+ }
491
+
492
+ const directoryOf = (file) => {
493
+ const parts = file.split("/").slice(0, -1);
494
+ return parts.length === 0 ? "." : parts.slice(0, depth).join("/");
495
+ };
496
+
497
+ // ---- scanning ----------------------------------------------------------------------------
498
+
499
+ /** The lines of a file that aren't comments, with their numbers (block comments followed roughly). */
500
+ function codeLines(text) {
501
+ const lines = [];
502
+ let inBlock = false;
503
+ text.split(/\r?\n/).forEach((raw, i) => {
504
+ const line = raw.trim();
505
+ if (inBlock) {
506
+ if (line.includes("*/")) inBlock = false;
507
+ return;
508
+ }
509
+ if (line.startsWith("/*") || line.startsWith("<!--")) {
510
+ if (!line.includes("*/") && !line.includes("-->")) inBlock = line.startsWith("/*");
511
+ return;
512
+ }
513
+ if (line.startsWith("//") || line.startsWith("*")) return;
514
+ lines.push({ number: i + 1, text: raw });
515
+ });
516
+ return lines;
517
+ }
518
+
519
+ /**
520
+ * The numbers of the lines inside an import or export list that spans several lines, from the
521
+ * `import {` line to the `} from` line: their `a as b` are renames.
522
+ */
523
+ function renameLines(lines) {
524
+ const inside = new Set();
525
+ let open = false;
526
+ for (const { number, text } of lines) {
527
+ if (!open && OPEN_LIST.test(text)) open = true;
528
+ if (open) inside.add(number);
529
+ if (open && text.includes("}")) open = false;
530
+ }
531
+ return inside;
532
+ }
533
+
534
+ const hasComment = (text) => /\/\/|\/\*/.test(text);
535
+
536
+ /** One pattern's counts: in total, per file (a `Map`), and every place. */
537
+ const tally = (what, see, gate) => ({ what, see, gate, count: 0, byFile: new Counts(), places: [] });
538
+
539
+ function scan(files) {
540
+ const patterns = new Map(PATTERNS.map((p) => [p.id, tally(p.what, p.see, p.gate)]));
541
+ patterns.set("boolean-flag-files", tally("files with 3 or more boolean states", "patterns-core.md#a-set-of-boolean-flags", true));
542
+ patterns.set("trio-files", tally("files with both a loading flag and an error state: a loading/error/data trio", "patterns-vue.md#a-loading-error-data-trio", true));
543
+ patterns.set("string-if-chain", tally("a value compared with 3 or more string literals in one file (a closed set handled by if-chains)", "patterns-core.md#a-closed-set-of-states", true));
544
+ const counted = (id, file) => patterns.get(id)?.byFile.get(file) ?? 0;
545
+ const features = new Counts(FEATURES.map(([name]) => [name, 0]));
546
+ const legacy = [];
547
+ const std = [];
548
+ let cacheMarks = 0;
549
+ const kinds = new Counts();
550
+
551
+ for (const file of files) {
552
+ const text = orExit(`can't read ${file}`, () => readFileSync(join(root, file), "utf8"));
553
+ kinds.add(extname(file));
554
+ const test = TEST_NAME.test(file) || TEST_RUNNER.test(text);
555
+ // `// @safe-ts legacy`, or `<!-- @safe-ts legacy -->` in a component.
556
+ if (/(?:\/\/|<!--)\s*@safe-ts legacy\b/.test(text)) legacy.push(file);
557
+ if (/\/\/\s*@safe-ts std\b/.test(text)) std.push(file);
558
+ cacheMarks += (text.match(/\/\*\*\s*@cache\s*\*\//g) ?? []).length;
559
+ const raw = text.split(/\r?\n/);
560
+ const lines = codeLines(text);
561
+ const renames = renameLines(lines);
562
+ const hit = (id, line) => {
563
+ const p = patterns.get(id);
564
+ if (p === undefined) return;
565
+ p.count += 1;
566
+ p.byFile.add(file);
567
+ p.places.push(`${file}:${line.number}: ${line.text.trim().slice(0, 140)}`);
568
+ };
569
+ raw.forEach((line, i) => {
570
+ for (const pattern of PATTERNS) {
571
+ if (pattern.comment && (!pattern.only || pattern.only(file, test)) && pattern.line.test(line)) hit(pattern.id, { number: i + 1, text: line });
572
+ }
573
+ });
574
+ const comparisons = new Map();
575
+ for (const line of lines) {
576
+ for (const pattern of PATTERNS) {
577
+ if (pattern.comment) continue;
578
+ if (pattern.only && !pattern.only(file, test)) continue;
579
+ if (pattern.skip?.test(line.text)) continue;
580
+ if (pattern.renames && renames.has(line.number)) continue;
581
+ const seen = pattern.renames ? withoutRenames(line.text) : line.text;
582
+ if (!pattern.line.test(seen) && !pattern.or?.test(seen)) continue;
583
+ if (pattern.needsReason) {
584
+ const above = raw[line.number - 2] ?? "";
585
+ if (hasComment(line.text) || /^\s*(?:\/\/|\*|\/\*)/.test(above)) continue;
586
+ }
587
+ hit(pattern.id, line);
588
+ }
589
+ for (const [name, re] of FEATURES) if (re.test(line.text)) features.add(name);
590
+ for (const m of line.text.matchAll(/([\w$][\w$.?]*)\s*[!=]==\s*(['"])([^'"\n]+)\2/g)) {
591
+ const subject = m[1];
592
+ if (subject.endsWith(".tag") || subject === "typeof" || /^(?:process\.env|import\.meta)/.test(subject)) continue;
593
+ const seen = comparisons.get(subject) ?? { literals: new Set(), first: line };
594
+ seen.literals.add(m[3]);
595
+ comparisons.set(subject, seen);
596
+ }
597
+ }
598
+ for (const [subject, { literals, first }] of comparisons) {
599
+ if (literals.size >= 3) hit("string-if-chain", { number: first.number, text: `${subject}: ${[...literals].map((l) => `'${l}'`).join(", ")}` });
600
+ }
601
+ const booleans = counted("boolean-state", file);
602
+ if (booleans >= 3) hit("boolean-flag-files", { number: 1, text: `${booleans} boolean states` });
603
+ if (counted("loading-flag", file) > 0 && counted("error-state", file) > 0) {
604
+ hit("trio-files", { number: 1, text: "loading flag and error state in one file" });
605
+ }
606
+ }
607
+ return { patterns, features, legacy, std, cacheMarks, kinds };
608
+ }
609
+
610
+ // ---- the checker -------------------------------------------------------------------------
611
+
612
+ function runChecker(files) {
613
+ if (args.includes("--no-check")) return { skipped: "--no-check" };
614
+ const binary = findSafeTs(root);
615
+ if (binary === undefined) return { skipped: "no safe-ts binary found (install @evobug_com/safe-ts-transform, or set SAFE_TS_BIN)" };
616
+ const given = repeated("--entry");
617
+ // Every scanned file as an entry. `check` follows imports (relative, tsconfig `paths`,
618
+ // workspace packages) from its entries, so the app's entry points would reach the app; but
619
+ // tests, scripts, workers whose path is built at runtime and files nothing imports would be
620
+ // left out, while the patterns count them.
621
+ const entries = given.length > 0 ? given : files;
622
+ // The idiomatic rules see several hand-rolled forms (raw tag reads, `if (isErr(x)) return x`,
623
+ // `'key' in` on a union, ...): count them whether or not package.json turns the layer on yet.
624
+ const flags = args.includes("--no-idiomatic") ? ["--json"] : ["--json", "--idiomatic"];
625
+ const chunks = [];
626
+ // Keep each command line well under Windows' 32k characters.
627
+ let chunk = [];
628
+ let length = 0;
629
+ for (const entry of entries) {
630
+ if (chunk.length > 0 && length + entry.length > 24_000) {
631
+ chunks.push(chunk);
632
+ chunk = [];
633
+ length = 0;
634
+ }
635
+ chunk.push(entry);
636
+ length += entry.length + 1;
637
+ }
638
+ if (chunk.length > 0) chunks.push(chunk);
639
+ const seen = new Set();
640
+ const diagnostics = [];
641
+ for (const part of chunks) {
642
+ const run = spawnSync(binary, ["check", ...part, ...flags], { cwd: root, encoding: "utf8", maxBuffer: 1024 * 1024 * 1024 });
643
+ if (run.error) return { skipped: `could not run ${binary}: ${run.error.message}` };
644
+ let parsed;
645
+ try {
646
+ parsed = JSON.parse(run.stdout);
647
+ } catch {
648
+ // Not JSON: the checker failed before it could report. Say so in the report.
649
+ return { skipped: `safe-ts check failed (exit ${run.status}): ${(run.stderr || run.stdout).trim().split("\n").slice(0, 5).join(" | ")}` };
650
+ }
651
+ for (const d of parsed) {
652
+ const key = `${d.file}:${d.line}:${d.column}:${d.rule}:${d.message}`;
653
+ if (seen.has(key)) continue;
654
+ seen.add(key);
655
+ diagnostics.push(d);
656
+ }
657
+ }
658
+ const version = spawnSync(binary, ["--version"], { encoding: "utf8" }).stdout?.trim().replace(/^safe-ts /, "");
659
+ return { binary, version, idiomatic: flags.includes("--idiomatic"), entries: entries.length, diagnostics };
660
+ }
661
+
662
+ function summarizeFindings(diagnostics) {
663
+ const byRule = new Map();
664
+ const byDir = new Counts();
665
+ const origins = new Counts();
666
+ let warnings = 0;
667
+ for (const d of diagnostics) {
668
+ const file = d.file.split(sep).join("/");
669
+ const dir = directoryOf(file);
670
+ const rule = byRule.get(d.rule) ?? { total: 0, severity: d.severity ?? "error", byDir: new Counts(), byFile: new Counts() };
671
+ byRule.set(d.rule, rule);
672
+ rule.total += 1;
673
+ if (d.severity === "warning") warnings += 1;
674
+ rule.byDir.add(dir);
675
+ rule.byFile.add(file);
676
+ byDir.add(dir);
677
+ if (d.origin) origins.add(d.origin);
678
+ }
679
+ const topOrigins = [...origins].filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]).slice(0, 15);
680
+ return {
681
+ total: diagnostics.length,
682
+ errors: diagnostics.length - warnings,
683
+ warnings,
684
+ byRule,
685
+ byDir,
686
+ origins: topOrigins.map(([origin, count]) => ({ origin, count })),
687
+ };
688
+ }
689
+
690
+ // ---- report ------------------------------------------------------------------------------
691
+
692
+ const files = sourceFiles();
693
+ const scanned = scan(files);
694
+ const checker = runChecker(files);
695
+ const findings = checker.diagnostics ? summarizeFindings(checker.diagnostics) : undefined;
696
+ const byDir = (byFile) => {
697
+ const out = new Counts();
698
+ for (const [file, n] of byFile) out.add(directoryOf(file), n);
699
+ return out;
700
+ };
701
+ const pattern = (id) => scanned.patterns.get(id)?.count ?? 0;
702
+
703
+ /** The report, with plain objects, as `--json` prints it. */
704
+ const report = {
705
+ generated: new Date().toISOString(),
706
+ root,
707
+ files: { total: files.length, byExtension: toObject(scanned.kinds), legacy: scanned.legacy.length, std: scanned.std },
708
+ checker: checker.diagnostics
709
+ ? { binary: checker.binary, version: checker.version, idiomatic: checker.idiomatic, entries: checker.entries }
710
+ : { skipped: checker.skipped },
711
+ findings: findings && {
712
+ ...findings,
713
+ byRule: toObject(findings.byRule, (x) => ({ ...x, byDir: toObject(x.byDir), byFile: toObject(x.byFile) })),
714
+ byDir: toObject(findings.byDir),
715
+ },
716
+ escapeHatches: {
717
+ legacyFiles: scanned.legacy.length,
718
+ unsafe: pattern("unsafe"),
719
+ unsafeAsync: pattern("unsafe-async"),
720
+ unexplainedUnsafe: pattern("unexplained-unsafe"),
721
+ panic: pattern("panic"),
722
+ trust: pattern("trust"),
723
+ legacyNull: pattern("legacy-null"),
724
+ safeTsIgnore: pattern("safe-ts-ignore"),
725
+ void: pattern("void-call"),
726
+ cacheMarks: scanned.cacheMarks,
727
+ stdFiles: scanned.std.length,
728
+ casts: pattern("as-cast"),
729
+ },
730
+ patterns: toObject(scanned.patterns, (p) => ({
731
+ what: p.what,
732
+ see: p.see,
733
+ gate: p.gate,
734
+ count: p.count,
735
+ files: p.byFile.size,
736
+ byDir: toObject(byDir(p.byFile)),
737
+ byFile: toObject(p.byFile),
738
+ })),
739
+ features: toObject(scanned.features),
740
+ };
741
+
742
+ const show = option("--show");
743
+ if (show !== undefined) {
744
+ const places = scanned.patterns.get(show)?.places;
745
+ const rule = checker.diagnostics?.filter((d) => d.rule === show);
746
+ if (places) for (const place of places) console.log(place);
747
+ else if (rule && rule.length > 0) for (const d of rule) console.log(`${d.file}:${d.line}:${d.column}: ${d.message}`);
748
+ else {
749
+ console.error(`census: no pattern or reported rule named "${show}"; patterns: ${[...scanned.patterns.keys()].join(", ")}`);
750
+ process.exit(2);
751
+ }
752
+ process.exit(0);
753
+ }
754
+
755
+ const written = option("--write-baseline");
756
+ if (written !== undefined) {
757
+ const text = orExit("can't serialize the baseline", () => JSON.stringify(baselineOf(), null, 2));
758
+ orExit(`can't write ${written}`, () => writeFileSync(written, `${text}\n`));
759
+ console.error(`census: baseline written to ${written}`);
760
+ }
761
+
762
+ const baseline = option("--baseline");
763
+ if (baseline !== undefined) {
764
+ const text = orExit(`can't read the baseline ${baseline}`, () => readFileSync(baseline, "utf8"));
765
+ const before = orExit(`the baseline ${baseline} isn't JSON`, () => JSON.parse(text));
766
+ process.exit(gate(before));
767
+ }
768
+
769
+ if (args.includes("--json")) console.log(orExit("can't serialize the report", () => JSON.stringify(report, null, 2)));
770
+ else if (written === undefined) printReport();
771
+
772
+ /** What a baseline keeps: per gated pattern and per rule, the count in each file. */
773
+ function baselineOf() {
774
+ const gated = [...scanned.patterns].filter(([, p]) => p.gate).map(([id, p]) => [id, toObject(p.byFile)]);
775
+ const rules = [...(findings?.byRule ?? [])].map(([rule, x]) => [rule, toObject(x.byFile)]);
776
+ return { generated: report.generated, patterns: Object.fromEntries(gated), rules: Object.fromEntries(rules), legacyFiles: scanned.legacy.length };
777
+ }
778
+
779
+ /** The architecture gate: 1 when a count rose in any file, with the files named. */
780
+ function gate(before) {
781
+ const rises = [];
782
+ const oldPatterns = toMap(before?.patterns);
783
+ const oldRules = toMap(before?.rules);
784
+ const compare = (kind, id, old, current) => {
785
+ for (const [file, n] of current) {
786
+ const was = countOf(old.get(file), `${kind} ${id} ${file}`);
787
+ if (n > was) rises.push(`${kind} ${id}: ${file} ${was} -> ${n}`);
788
+ }
789
+ };
790
+ for (const [id, p] of scanned.patterns) if (p.gate) compare("pattern", id, toMap(oldPatterns.get(id)), p.byFile);
791
+ if (findings) for (const [rule, x] of findings.byRule) compare("rule", rule, toMap(oldRules.get(rule)), x.byFile);
792
+ const legacyBefore = countOf(before?.legacyFiles, "legacyFiles");
793
+ if (scanned.legacy.length > legacyBefore) rises.push(`legacy files: ${legacyBefore} -> ${scanned.legacy.length}`);
794
+ if (rises.length === 0) {
795
+ console.log("census gate: no count rose against the baseline");
796
+ return 0;
797
+ }
798
+ console.log(`census gate: ${rises.length} count(s) rose against the baseline`);
799
+ for (const rise of rises) console.log(` ${rise}`);
800
+ console.log("Fix them, or (for a reviewed exception) write a new baseline with --write-baseline.");
801
+ return 1;
802
+ }
803
+
804
+ function printReport() {
805
+ const n = (x) => x.toLocaleString("en-US");
806
+ const pad = (s, w) => String(s).padEnd(w);
807
+ const lpad = (s, w) => String(s).padStart(w);
808
+ const top = (dirs, k = 3) => [...dirs].sort((a, b) => b[1] - a[1]).slice(0, k).map(([d, c]) => `${d} (${n(c)})`).join(", ");
809
+ const kinds = [...scanned.kinds].map(([e, c]) => `${n(c)} ${e}`).join(", ");
810
+ console.log(`SAFE-TS census: ${n(files.length)} files (${kinds}), ${n(scanned.legacy.length)} marked legacy\n`);
811
+
812
+ if (findings) {
813
+ const how = `safe-ts ${checker.version ?? ""} check --json${checker.idiomatic ? " --idiomatic" : ""}`.replace(" ", " ");
814
+ console.log(
815
+ `Checker findings (${how}, ${n(checker.entries)} entries): ${n(findings.total)} ` +
816
+ `(${n(findings.errors)} errors, ${n(findings.warnings)} warnings)`,
817
+ );
818
+ const rules = [...findings.byRule].sort((a, b) => b[1].total - a[1].total);
819
+ for (const [rule, x] of rules) {
820
+ const level = x.severity === "warning" ? " (warn)" : "";
821
+ console.log(` ${pad(rule + level, 30)} ${lpad(n(x.total), 7)} ${top(x.byDir)}`);
822
+ const see = RULE_SEE.get(rule);
823
+ if (see) console.log(` ${pad("", 30)} ${" ".repeat(7)} see references/${see}`);
824
+ }
825
+ if (findings.origins.length > 0) {
826
+ console.log("\n Root causes (one origin, 3 or more findings):");
827
+ for (const { origin, count } of findings.origins) console.log(` ${lpad(n(count), 7)} ${origin}`);
828
+ }
829
+ if (scanned.legacy.length > 0) console.log("\n Legacy files report nothing; remove a marker to see that file's findings.");
830
+ } else {
831
+ console.log(`Checker not run: ${checker.skipped}`);
832
+ }
833
+
834
+ console.log("\nPatterns the checker doesn't report (heuristic: read each place):");
835
+ for (const [id, p] of scanned.patterns) {
836
+ if (p.count === 0) continue;
837
+ console.log(` ${pad(id, 24)} ${lpad(n(p.count), 6)} in ${lpad(n(p.byFile.size), 4)} files ${top(byDir(p.byFile), 2)}`);
838
+ console.log(` ${pad("", 24)} ${p.what}; see references/${p.see}`);
839
+ }
840
+
841
+ const h = report.escapeHatches;
842
+ console.log(
843
+ `\nEscape hatches: ${n(h.legacyFiles)} legacy file(s), ${n(h.unsafe)} unsafe(), ${n(h.unsafeAsync)} unsafeAsync(), ` +
844
+ `${n(h.unexplainedUnsafe)} without a reason comment, ${n(h.panic)} panic(), ${n(h.trust)} trust(), ` +
845
+ `${n(h.legacyNull)} LegacyNull, ${n(h.safeTsIgnore)} safe-ts-ignore, ${n(h.void)} void calls, ` +
846
+ `${n(h.casts)} as-casts, ${n(h.cacheMarks)} @cache, ${n(h.stdFiles)} std file(s)`,
847
+ );
848
+
849
+ console.log("\nSAFE-TS features in use (for the final pass):");
850
+ console.log(` ${[...scanned.features].map(([f, c]) => `${f} ${n(c)}`).join(" · ")}`);
851
+
852
+ const dirs = new Set([...(findings?.byDir.keys() ?? []), ...files.map(directoryOf)]);
853
+ const patternsByDir = [...scanned.patterns]
854
+ .filter(([id]) => !["boolean-state", "unsafe", "unexplained-unsafe"].includes(id))
855
+ .map(([id, p]) => [id, byDir(p.byFile)]);
856
+ console.log(`\nPer directory (depth ${depth}): findings, then the most frequent patterns`);
857
+ const rows = [...dirs].map((dir) => {
858
+ const patterns = patternsByDir
859
+ .map(([id, counts]) => [id, counts.get(dir) ?? 0])
860
+ .filter(([, c]) => c > 0)
861
+ .sort((a, b) => b[1] - a[1])
862
+ .slice(0, 4);
863
+ return { dir, findings: findings?.byDir.get(dir) ?? 0, patterns };
864
+ });
865
+ rows.sort((a, b) => b.findings - a.findings || a.dir.localeCompare(b.dir));
866
+ for (const row of rows) {
867
+ console.log(` ${pad(row.dir, 40)} ${lpad(n(row.findings), 6)} ${row.patterns.map(([id, c]) => `${id} ${n(c)}`).join(", ")}`);
868
+ }
869
+ console.log("\n`--show <pattern or rule>` lists every place; `--json` gives all of it.");
870
+ }