-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcheck-error-patterns.ts
More file actions
389 lines (354 loc) · 11.7 KB
/
Copy pathcheck-error-patterns.ts
File metadata and controls
389 lines (354 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env tsx
/**
* Check for Error Class Misuse Patterns
*
* Scans source files for common anti-patterns in error class usage:
*
* 1. `new ContextError(resource, command)` where command contains `\n`
* → Should use ResolutionError for resolution failures
*
* 2. `new CliError(... "Try:" ...)` — ad-hoc "Try:" strings
* → Should use ResolutionError with structured hint/suggestions
*
* 3. Silent catch blocks — `catch { ... }` whose body has no logging, no
* re-throw, and at most a bare `return`. Errors must be surfaced via
* `log.debug`/`log.warn` (or re-thrown) per AGENTS.md. Biome's
* `noEmptyBlockStatements` only catches syntactically empty `catch {}`;
* this catches comment-only and return-only blocks too.
*
* Usage:
* tsx script/check-error-patterns.ts
*
* Exit codes:
* 0 - No anti-patterns found
* 1 - Anti-patterns detected
*/
import { readFile } from "node:fs/promises";
import { glob } from "tinyglobby";
type Violation = { file: string; line: number; message: string };
const CONTEXT_ERROR_RE = /new ContextError\(/g;
const TRY_PATTERN_RE = /["'`]Try:/;
const files = await glob("src/**/*.ts");
/** Hard violations — these fail CI. */
const violations: Violation[] = [];
/**
* Advisory silent-catch findings. Reported as warnings but do NOT fail CI yet:
* the repo has a pre-existing backlog of intentional best-effort catches (e.g.
* UI teardown, cleanup paths). The check surfaces them for incremental cleanup
* and so new ones are visible in review. Set SENTRY_STRICT_SILENT_CATCH=1 to
* promote them to hard failures once the backlog is cleared.
*/
const silentCatchWarnings: Violation[] = [];
const STRICT_SILENT_CATCH = process.env.SENTRY_STRICT_SILENT_CATCH === "1";
/** Characters that open a nesting level in JavaScript source. */
function isOpener(ch: string): boolean {
return ch === "(" || ch === "[" || ch === "{";
}
/** Characters that close a nesting level in JavaScript source. */
function isCloser(ch: string): boolean {
return ch === ")" || ch === "]" || ch === "}";
}
/** Characters that start a string literal in JavaScript source. */
function isQuote(ch: string): boolean {
return ch === '"' || ch === "'" || ch === "`";
}
/**
* Skip past a `${...}` expression inside a template literal.
* @param content - Full source text
* @param start - Index right after the `{` in `${`
* @returns Index right after the closing `}`
*/
function skipTemplateExpression(content: string, start: number): number {
let braceDepth = 1;
let i = start;
while (i < content.length && braceDepth > 0) {
const ec = content[i];
if (ec === "\\") {
i += 2;
} else if (ec === "`") {
i = skipTemplateLiteral(content, i + 1);
} else if (ec === "{") {
braceDepth += 1;
i += 1;
} else if (ec === "}") {
braceDepth -= 1;
i += 1;
} else {
i += 1;
}
}
return i;
}
/**
* Skip past a template literal, handling nested `${...}` expressions.
* @param content - Full source text
* @param start - Index right after the opening backtick
* @returns Index right after the closing backtick
*/
function skipTemplateLiteral(content: string, start: number): number {
let i = start;
while (i < content.length) {
const ch = content[i];
if (ch === "\\") {
i += 2;
} else if (ch === "`") {
return i + 1;
} else if (ch === "$" && content[i + 1] === "{") {
i = skipTemplateExpression(content, i + 2);
} else {
i += 1;
}
}
return i;
}
/**
* Advance past a string literal (single-quoted, double-quoted, or template).
* @param content - Full source text
* @param start - Index of the opening quote character
* @returns Index right after the closing quote
*/
function skipString(content: string, start: number): number {
const quote = content[start];
if (quote === "`") {
return skipTemplateLiteral(content, start + 1);
}
let i = start + 1;
while (i < content.length) {
const ch = content[i];
if (ch === "\\") {
i += 2;
} else if (ch === quote) {
return i + 1;
} else {
i += 1;
}
}
return i;
}
/**
* Advance one token in JS source, skipping strings as atomic units.
* @returns The next index and the character at position `i` (or the string span's first char).
*/
function advanceToken(
content: string,
i: number
): { next: number; ch: string } {
const ch = content[i] ?? "";
if (isQuote(ch)) {
return { next: skipString(content, i), ch };
}
return { next: i + 1, ch };
}
/**
* Walk from `startIdx` (just inside the opening `(`) to find the matching `)`,
* tracking commas at depth 1.
* @returns The index of the first comma (between arg1 and arg2) and the closing paren index.
*/
function findCallBounds(
content: string,
startIdx: number
): { commaIdx: number; closingIdx: number } | null {
let depth = 1;
let commaCount = 0;
let commaIdx = -1;
let i = startIdx;
while (i < content.length && depth > 0) {
const { next, ch } = advanceToken(content, i);
if (isOpener(ch)) {
depth += 1;
} else if (isCloser(ch)) {
depth -= 1;
} else if (ch === "," && depth === 1) {
commaCount += 1;
if (commaCount === 1) {
commaIdx = i;
}
}
i = next;
}
if (commaIdx === -1) {
return null;
}
return { commaIdx, closingIdx: i - 1 };
}
/**
* Extract the second argument of a `new ContextError(...)` call from source text.
* Properly handles template literals so backticks don't break depth tracking.
* @returns The raw source text of the second argument, or null if not found.
*/
function extractSecondArg(content: string, startIdx: number): string | null {
const bounds = findCallBounds(content, startIdx);
if (!bounds) {
return null;
}
const { commaIdx, closingIdx } = bounds;
// Find end of second arg: next comma at depth 1 or closing paren
let endIdx = closingIdx;
let d = 1;
for (let j = commaIdx + 1; j < closingIdx; j += 1) {
const { next, ch } = advanceToken(content, j);
if (isOpener(ch)) {
d += 1;
} else if (isCloser(ch)) {
d -= 1;
} else if (ch === "," && d === 1) {
endIdx = j;
break;
}
// advanceToken may skip multiple chars (strings), adjust loop var
j = next - 1; // -1 because for-loop increments
}
return content.slice(commaIdx + 1, endIdx).trim();
}
/**
* Detect `new ContextError(` where the second argument contains `\n`.
* This catches resolution-failure prose stuffed into the command parameter.
*/
function checkContextErrorNewlines(content: string, filePath: string): void {
let match = CONTEXT_ERROR_RE.exec(content);
while (match !== null) {
const startIdx = match.index + match[0].length;
const secondArg = extractSecondArg(content, startIdx);
if (secondArg?.includes("\\n")) {
const line = content.slice(0, match.index).split("\n").length;
violations.push({
file: filePath,
line,
message:
"ContextError command contains '\\n'. Use ResolutionError for multi-line resolution failures.",
});
}
match = CONTEXT_ERROR_RE.exec(content);
}
}
/**
* Detect `new CliError(... "Try:" ...)` — ad-hoc "Try:" strings that bypass
* the structured ResolutionError pattern.
*/
function checkAdHocTryPatterns(content: string, filePath: string): void {
const lines = content.split("\n");
let inCliError = false;
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i] ?? "";
if (line.includes("new CliError(")) {
inCliError = true;
}
if (inCliError && TRY_PATTERN_RE.test(line)) {
violations.push({
file: filePath,
line: i + 1,
message:
'CliError contains "Try:" — use ResolutionError with structured hint/suggestions instead.',
});
inCliError = false;
}
// Reset after a reasonable window (closing paren)
if (inCliError && line.includes(");")) {
inCliError = false;
}
}
}
/** Matches the start of a catch block in both statement and promise form. */
const CATCH_RE =
/\bcatch\s*(?:\(\s*(\w+)[^)]*\)\s*)?\{|\.catch\(\s*(?:\(\s*(\w+)[^)]*\)|(\w+))\s*=>\s*\{/g;
/** Tokens inside a catch body that prove the error is surfaced (not silenced). */
const SURFACING_RE =
/\b(?:log|logger|console)\s*\.|[^.]\bthrow\b|captureException|reportError/;
/** A catch body consisting solely of a single `return ...;` statement. */
const RETURN_ONLY_RE = /^return\b[^;]*;?$/;
/**
* Return the source of a balanced `{...}` block given the index of its opening
* brace, skipping strings so braces inside literals don't break depth tracking.
*/
function readBlock(content: string, openBraceIdx: number): string {
let depth = 0;
let i = openBraceIdx;
while (i < content.length) {
const { next, ch } = advanceToken(content, i);
if (ch === "{") {
depth += 1;
} else if (ch === "}") {
depth -= 1;
if (depth === 0) {
return content.slice(openBraceIdx + 1, i);
}
}
i = next;
}
return content.slice(openBraceIdx + 1);
}
/**
* Strip line and block comments from a snippet so comment-only catch bodies are
* treated as empty.
*/
function stripComments(snippet: string): string {
return snippet.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
}
/**
* Detect silent catch blocks: catch bodies that, after removing comments, are
* empty or contain only a bare `return;`/`return <value>;` with no logging or
* re-throw. These hide errors and violate the AGENTS.md no-silent-catch rule.
*/
function checkSilentCatch(content: string, filePath: string): void {
let match = CATCH_RE.exec(content);
while (match !== null) {
const openBraceIdx = match.index + match[0].length - 1;
const errorParam = match[1] ?? match[2] ?? match[3];
const body = readBlock(content, openBraceIdx);
const code = stripComments(body).trim();
// A body that references the caught error identifier (forwarding it to a
// handler, attaching it, etc.) is not "silent" even if it lacks an explicit
// log/throw — avoids false positives like `return handleFetchError(error)`.
const usesError =
errorParam !== undefined && new RegExp(`\\b${errorParam}\\b`).test(code);
const returnOnly = RETURN_ONLY_RE.test(code);
const silent =
!(SURFACING_RE.test(code) || usesError) &&
(code.length === 0 || returnOnly);
if (silent) {
const line = content.slice(0, match.index).split("\n").length;
const target = STRICT_SILENT_CATCH ? violations : silentCatchWarnings;
target.push({
file: filePath,
line,
message:
"Silent catch block. Add log.debug()/log.warn() or re-throw — errors must not vanish (AGENTS.md).",
});
}
match = CATCH_RE.exec(content);
}
}
for (const filePath of files) {
const content = await readFile(filePath, "utf-8");
checkContextErrorNewlines(content, filePath);
checkAdHocTryPatterns(content, filePath);
checkSilentCatch(content, filePath);
}
if (silentCatchWarnings.length > 0) {
console.warn(
`⚠ ${silentCatchWarnings.length} silent catch block(s) found (advisory; not failing CI).`
);
console.warn(
" Add log.debug()/log.warn() or re-throw. Run with SENTRY_STRICT_SILENT_CATCH=1 to enforce.\n"
);
for (const v of silentCatchWarnings) {
console.warn(` ${v.file}:${v.line}`);
}
console.warn("");
}
if (violations.length === 0) {
console.log("✓ No error class anti-patterns found");
process.exit(0);
}
console.error(`✗ Found ${violations.length} error class anti-pattern(s):\n`);
for (const v of violations) {
console.error(` ${v.file}:${v.line}`);
console.error(` ${v.message}\n`);
}
console.error(
"Fix: Use ResolutionError for resolution failures, ValidationError for input errors."
);
console.error(
"See ContextError JSDoc in src/lib/errors.ts for usage guidance."
);
process.exit(1);