@voidh4x0r/slopgate 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/LICENSE +21 -0
  3. package/README.md +266 -2
  4. package/dist/ast.d.ts +29 -0
  5. package/dist/ast.js +3 -0
  6. package/dist/baseline.d.ts +33 -0
  7. package/dist/baseline.js +104 -0
  8. package/dist/cli.d.ts +9 -0
  9. package/dist/cli.js +481 -0
  10. package/dist/config.d.ts +25 -0
  11. package/dist/config.js +90 -0
  12. package/dist/data/python-stdlib.d.ts +19 -0
  13. package/dist/data/python-stdlib.js +75 -0
  14. package/dist/deps.d.ts +8 -0
  15. package/dist/deps.js +379 -0
  16. package/dist/diff.d.ts +30 -0
  17. package/dist/diff.js +179 -0
  18. package/dist/engine.d.ts +15 -0
  19. package/dist/engine.js +179 -0
  20. package/dist/files.d.ts +32 -0
  21. package/dist/files.js +168 -0
  22. package/dist/mcp.d.ts +41 -0
  23. package/dist/mcp.js +226 -0
  24. package/dist/parser.d.ts +3 -0
  25. package/dist/parser.js +41 -0
  26. package/dist/reporters/github.d.ts +2 -0
  27. package/dist/reporters/github.js +44 -0
  28. package/dist/reporters/json.d.ts +10 -0
  29. package/dist/reporters/json.js +36 -0
  30. package/dist/reporters/pretty.d.ts +12 -0
  31. package/dist/reporters/pretty.js +103 -0
  32. package/dist/reporters/sarif.d.ts +2 -0
  33. package/dist/reporters/sarif.js +70 -0
  34. package/dist/rules/helpers.d.ts +43 -0
  35. package/dist/rules/helpers.js +163 -0
  36. package/dist/rules/index.d.ts +3 -0
  37. package/dist/rules/index.js +4 -0
  38. package/dist/rules/python.d.ts +2 -0
  39. package/dist/rules/python.js +591 -0
  40. package/dist/rules/typescript.d.ts +2 -0
  41. package/dist/rules/typescript.js +497 -0
  42. package/dist/suppress.d.ts +12 -0
  43. package/dist/suppress.js +52 -0
  44. package/dist/types.d.ts +88 -0
  45. package/dist/types.js +1 -0
  46. package/grammars/README.md +28 -0
  47. package/grammars/tree-sitter-python.wasm +0 -0
  48. package/grammars/tree-sitter-tsx.wasm +0 -0
  49. package/grammars/tree-sitter-typescript.wasm +0 -0
  50. package/package.json +61 -4
package/dist/parser.js ADDED
@@ -0,0 +1,41 @@
1
+ import * as path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { Language, Parser } from 'web-tree-sitter';
4
+ const PACKAGE_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
5
+ const GRAMMARS = {
6
+ python: 'tree-sitter-python.wasm',
7
+ typescript: 'tree-sitter-typescript.wasm',
8
+ tsx: 'tree-sitter-tsx.wasm',
9
+ };
10
+ let initPromise;
11
+ const parserCache = new Map();
12
+ async function ensureRuntime() {
13
+ initPromise ??= Parser.init();
14
+ await initPromise;
15
+ }
16
+ function grammarPath(language) {
17
+ return path.join(PACKAGE_ROOT, 'grammars', GRAMMARS[language]);
18
+ }
19
+ export async function getParser(language) {
20
+ const cached = parserCache.get(language);
21
+ if (cached)
22
+ return cached;
23
+ const created = (async () => {
24
+ await ensureRuntime();
25
+ const wasm = grammarPath(language);
26
+ let lang;
27
+ try {
28
+ lang = await Language.load(wasm);
29
+ }
30
+ catch (error) {
31
+ throw new Error(`could not load grammar for ${language} (${wasm}). ` +
32
+ 'If you installed from source, run `npm install` first. ' +
33
+ `Underlying error: ${error.message}`);
34
+ }
35
+ const parser = new Parser();
36
+ parser.setLanguage(lang);
37
+ return parser;
38
+ })();
39
+ parserCache.set(language, created);
40
+ return created;
41
+ }
@@ -0,0 +1,2 @@
1
+ import type { Finding, ScanStats } from '../types.ts';
2
+ export declare function renderGithub(findings: readonly Finding[], stats: ScanStats): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * GitHub Actions workflow commands: annotations show up inline on the pull
3
+ * request diff without any extra setup (unlike SARIF, which needs code scanning).
4
+ *
5
+ * Escaping rules:
6
+ * property values: % \r \n : ,
7
+ * message data: % \r \n
8
+ */
9
+ function escapeProperty(value) {
10
+ return value
11
+ .replace(/%/g, '%25')
12
+ .replace(/\r/g, '%0D')
13
+ .replace(/\n/g, '%0A')
14
+ .replace(/:/g, '%3A')
15
+ .replace(/,/g, '%2C');
16
+ }
17
+ function escapeData(value) {
18
+ return value.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
19
+ }
20
+ const ANNOTATION_LEVEL = {
21
+ error: 'error',
22
+ warning: 'warning',
23
+ info: 'notice',
24
+ };
25
+ export function renderGithub(findings, stats) {
26
+ const lines = [];
27
+ for (const finding of findings) {
28
+ const properties = [
29
+ `file=${escapeProperty(finding.file)}`,
30
+ `line=${finding.start.line}`,
31
+ `col=${finding.start.column}`,
32
+ `endLine=${finding.end.line}`,
33
+ `endColumn=${finding.end.column}`,
34
+ `title=${escapeProperty(finding.ruleId)}`,
35
+ ].join(',');
36
+ // The message is shown as the annotation body; keep it to one line.
37
+ const message = finding.help ? `${finding.message} — ${finding.help}` : finding.message;
38
+ lines.push(`::${ANNOTATION_LEVEL[finding.severity]} ${properties}::${escapeData(message)}`);
39
+ }
40
+ const errors = findings.filter((finding) => finding.severity === 'error').length;
41
+ const warnings = findings.filter((finding) => finding.severity === 'warning').length;
42
+ lines.push(`::notice title=slopgate::${findings.length} finding(s) (${errors} error, ${warnings} warning) · ${stats.files} files scanned in ${stats.durationMs}ms`);
43
+ return lines.join('\n') + '\n';
44
+ }
@@ -0,0 +1,10 @@
1
+ import type { Finding, ScanStats } from '../types.ts';
2
+ export interface JsonInput {
3
+ findings: readonly Finding[];
4
+ stats: ScanStats;
5
+ version: string;
6
+ suppressedByComment: number;
7
+ baselined: number;
8
+ hiddenByConfidence: number;
9
+ }
10
+ export declare function renderJson(input: JsonInput): string;
@@ -0,0 +1,36 @@
1
+ import { findingFingerprint } from "../baseline.js";
2
+ export function renderJson(input) {
3
+ const bySeverity = { error: 0, warning: 0, info: 0 };
4
+ const byConfidence = { high: 0, medium: 0, low: 0 };
5
+ for (const finding of input.findings) {
6
+ bySeverity[finding.severity] += 1;
7
+ byConfidence[finding.confidence] += 1;
8
+ }
9
+ const payload = {
10
+ tool: 'slopgate',
11
+ version: input.version,
12
+ stats: input.stats,
13
+ summary: {
14
+ findings: input.findings.length,
15
+ bySeverity,
16
+ byConfidence,
17
+ suppressedByComment: input.suppressedByComment,
18
+ baselined: input.baselined,
19
+ hiddenByConfidence: input.hiddenByConfidence,
20
+ },
21
+ findings: input.findings.map((finding) => ({
22
+ ruleId: finding.ruleId,
23
+ severity: finding.severity,
24
+ confidence: finding.confidence,
25
+ file: finding.file,
26
+ start: finding.start,
27
+ end: finding.end,
28
+ message: finding.message,
29
+ snippet: finding.snippet,
30
+ evidence: finding.evidence,
31
+ ...(finding.help ? { help: finding.help } : {}),
32
+ fingerprint: findingFingerprint(finding),
33
+ })),
34
+ };
35
+ return JSON.stringify(payload, null, 2) + '\n';
36
+ }
@@ -0,0 +1,12 @@
1
+ import type { Finding, ScanStats } from '../types.ts';
2
+ export interface PrettyInput {
3
+ findings: readonly Finding[];
4
+ stats: ScanStats;
5
+ suppressedByComment: number;
6
+ baselined: number;
7
+ hiddenByConfidence: number;
8
+ version: string;
9
+ color: boolean;
10
+ quiet?: boolean;
11
+ }
12
+ export declare function renderPretty(input: PrettyInput): string;
@@ -0,0 +1,103 @@
1
+ function ansi(enabled, code) {
2
+ return (text) => (enabled ? `\u001b[${code}m${text}\u001b[0m` : text);
3
+ }
4
+ function wrap(text, width) {
5
+ const words = text.split(/\s+/).filter((word) => word.length > 0);
6
+ const lines = [];
7
+ let current = '';
8
+ for (const word of words) {
9
+ if (current.length === 0) {
10
+ current = word;
11
+ }
12
+ else if (current.length + 1 + word.length <= width) {
13
+ current += ' ' + word;
14
+ }
15
+ else {
16
+ lines.push(current);
17
+ current = word;
18
+ }
19
+ }
20
+ if (current.length > 0)
21
+ lines.push(current);
22
+ return lines.length > 0 ? lines : [''];
23
+ }
24
+ const LOC_WIDTH = 8;
25
+ const SEV_WIDTH = 7;
26
+ const CONF_WIDTH = 6;
27
+ const RULE_WIDTH = 23;
28
+ const GUTTER = ' '.repeat(LOC_WIDTH + 2);
29
+ export function renderPretty(input) {
30
+ const { findings, stats, version, color } = input;
31
+ const bold = ansi(color, '1');
32
+ const dim = ansi(color, '2');
33
+ const red = ansi(color, '31');
34
+ const yellow = ansi(color, '33');
35
+ const cyan = ansi(color, '36');
36
+ const green = ansi(color, '32');
37
+ const out = [];
38
+ out.push('');
39
+ out.push(`${bold('slopgate')} ${dim(version)} ${dim('·')} ${stats.files} files ${dim('·')} ${stats.durationMs}ms`);
40
+ out.push('');
41
+ if (findings.length === 0) {
42
+ out.push(` ${green('✓')} no findings above the confidence threshold`);
43
+ out.push('');
44
+ }
45
+ let currentFile;
46
+ if (!input.quiet) {
47
+ for (const finding of findings) {
48
+ if (finding.file !== currentFile) {
49
+ if (currentFile !== undefined)
50
+ out.push('');
51
+ out.push(cyan(finding.file));
52
+ currentFile = finding.file;
53
+ }
54
+ const location = `${finding.start.line}:${finding.start.column}`.padStart(LOC_WIDTH);
55
+ const severity = finding.severity === 'error'
56
+ ? red(finding.severity.padEnd(SEV_WIDTH))
57
+ : finding.severity === 'warning'
58
+ ? yellow(finding.severity.padEnd(SEV_WIDTH))
59
+ : dim(finding.severity.padEnd(SEV_WIDTH));
60
+ const confidence = dim(finding.confidence.padEnd(CONF_WIDTH));
61
+ const rule = dim(finding.ruleId.padEnd(RULE_WIDTH));
62
+ out.push(` ${location} ${severity} ${confidence} ${rule} ${finding.message}`);
63
+ if (finding.snippet) {
64
+ out.push(`${GUTTER} ${dim('│ ' + finding.snippet)}`);
65
+ }
66
+ for (const item of finding.evidence.slice(0, 2)) {
67
+ out.push(`${GUTTER} ${dim('· ' + item)}`);
68
+ }
69
+ if (finding.help) {
70
+ const lines = wrap(finding.help, 92);
71
+ lines.forEach((line, index) => {
72
+ const marker = index === 0 ? '↳ ' : ' ';
73
+ out.push(dim(`${GUTTER} ${marker}${line}`));
74
+ });
75
+ }
76
+ }
77
+ }
78
+ if (findings.length > 0 && !input.quiet)
79
+ out.push('');
80
+ const bySeverity = { error: 0, warning: 0, info: 0 };
81
+ const byConfidence = { high: 0, medium: 0, low: 0 };
82
+ for (const finding of findings) {
83
+ bySeverity[finding.severity] += 1;
84
+ byConfidence[finding.confidence] += 1;
85
+ }
86
+ const fileCount = new Set(findings.map((finding) => finding.file)).size;
87
+ out.push(` ${bold(String(findings.length))} ${findings.length === 1 ? 'finding' : 'findings'} in ${fileCount} ${fileCount === 1 ? 'file' : 'files'} ${dim('·')} ${stats.files} files scanned in ${stats.durationMs}ms`);
88
+ out.push(dim(` ${bySeverity.error} error · ${bySeverity.warning} warning · ${bySeverity.info} info (${byConfidence.high} high · ${byConfidence.medium} medium · ${byConfidence.low} low confidence)`));
89
+ const extras = [];
90
+ if (input.hiddenByConfidence > 0)
91
+ extras.push(`${input.hiddenByConfidence} below confidence threshold`);
92
+ if (input.suppressedByComment > 0)
93
+ extras.push(`${input.suppressedByComment} suppressed by comment`);
94
+ if (input.baselined > 0)
95
+ extras.push(`${input.baselined} in baseline`);
96
+ if (extras.length > 0)
97
+ out.push(dim(` hidden: ${extras.join(' · ')}`));
98
+ if (stats.parseErrors > 0) {
99
+ out.push(yellow(` ${stats.parseErrors} file(s) had syntax errors and may be partially analysed`));
100
+ }
101
+ out.push('');
102
+ return out.join('\n');
103
+ }
@@ -0,0 +1,2 @@
1
+ import type { Finding } from '../types.ts';
2
+ export declare function renderSarif(findings: readonly Finding[], version: string): string;
@@ -0,0 +1,70 @@
1
+ import { findingFingerprint } from "../baseline.js";
2
+ import { RULE_BY_ID } from "../rules/index.js";
3
+ const SARIF_LEVEL = {
4
+ error: 'error',
5
+ warning: 'warning',
6
+ info: 'note',
7
+ };
8
+ export function renderSarif(findings, version) {
9
+ const usedRules = new Map();
10
+ for (const finding of findings) {
11
+ if (!usedRules.has(finding.ruleId))
12
+ usedRules.set(finding.ruleId, finding);
13
+ }
14
+ const rules = [...usedRules.entries()].map(([ruleId, finding]) => {
15
+ const meta = RULE_BY_ID.get(ruleId)?.meta;
16
+ return {
17
+ id: ruleId,
18
+ name: meta?.title ?? ruleId,
19
+ shortDescription: { text: meta?.title ?? ruleId },
20
+ fullDescription: { text: meta?.summary ?? '' },
21
+ defaultConfiguration: { level: SARIF_LEVEL[finding.severity] },
22
+ properties: {
23
+ confidence: meta?.confidence ?? finding.confidence,
24
+ tags: meta?.tags ?? [],
25
+ },
26
+ };
27
+ });
28
+ const payload = {
29
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
30
+ version: '2.1.0',
31
+ runs: [
32
+ {
33
+ tool: {
34
+ driver: {
35
+ name: 'slopgate',
36
+ version,
37
+ informationUri: 'https://github.com/VoidH4x0r/slopgate',
38
+ rules,
39
+ },
40
+ },
41
+ results: findings.map((finding) => ({
42
+ ruleId: finding.ruleId,
43
+ level: SARIF_LEVEL[finding.severity],
44
+ message: { text: finding.message },
45
+ locations: [
46
+ {
47
+ physicalLocation: {
48
+ artifactLocation: { uri: finding.file },
49
+ region: {
50
+ startLine: finding.start.line,
51
+ startColumn: finding.start.column,
52
+ endLine: finding.end.line,
53
+ endColumn: finding.end.column,
54
+ },
55
+ },
56
+ },
57
+ ],
58
+ partialFingerprints: {
59
+ primaryLocationLineHash: findingFingerprint(finding),
60
+ },
61
+ properties: {
62
+ confidence: finding.confidence,
63
+ evidence: finding.evidence,
64
+ },
65
+ })),
66
+ },
67
+ ],
68
+ };
69
+ return JSON.stringify(payload, null, 2) + '\n';
70
+ }
@@ -0,0 +1,43 @@
1
+ import type { AstNode } from '../ast.ts';
2
+ import type { Position, RuleContext } from '../types.ts';
3
+ export declare function startOf(node: AstNode): Position;
4
+ export declare function endOf(node: AstNode): Position;
5
+ /** Trimmed first line of a node, capped for display. */
6
+ export declare function snippetOf(_ctx: RuleContext, node: AstNode): string;
7
+ export declare function isComment(node: AstNode): boolean;
8
+ /** Named children that are actual statements (comments excluded). */
9
+ export declare function statementsOf(block: AstNode): AstNode[];
10
+ /** Depth-limited, allocation-light walk over named children. */
11
+ export declare function walk(node: AstNode, visit: (node: AstNode, depth: number) => boolean | void, maxDepth?: number): void;
12
+ export declare function descendantsOfType(root: AstNode, types: readonly string[]): AstNode[];
13
+ /** Nearest ancestor whose type is in `types` (excluding the node itself). */
14
+ export declare function ancestorOfType(node: AstNode, types: readonly string[]): AstNode | undefined;
15
+ /**
16
+ * Comments before the first statement of a block are often attached to the
17
+ * parent node instead of the block, so fall back to scanning the source lines.
18
+ */
19
+ export declare function hasCommentBetween(ctx: RuleContext, fromLine: number, toLine: number): boolean;
20
+ export declare function collapseWhitespace(value: string): string;
21
+ /**
22
+ * Callee name of a call expression, normalised to the final segment:
23
+ * `foo.bar.baz(...)` -> `baz`, `expect(...)` -> `expect`.
24
+ */
25
+ export declare function calleeName(callNode: AstNode): string | undefined;
26
+ export declare function truncate(value: string, max: number): string;
27
+ /**
28
+ * Test files and fixtures are full of intentional stubs, dead branches and
29
+ * swallowed errors (they are testing those behaviours). Rules that are not
30
+ * test-specific skip them; `py/noop-test` and `ts/noop-test` are the rules
31
+ * that look at tests themselves.
32
+ */
33
+ export declare function isTestPath(file: string): boolean;
34
+ /** True when the file name follows a test-module convention. */
35
+ export declare function looksLikeTestModule(file: string): boolean;
36
+ /** Text of the function's leading docstring, if it has one. */
37
+ export declare function docstringOf(fn: AstNode): string | undefined;
38
+ /** True when the function's body starts with a docstring. */
39
+ export declare function hasDocstring(fn: AstNode): boolean;
40
+ /** True when the node sits inside `if __name__ == "__main__":`. */
41
+ export declare function insideMainGuard(node: AstNode): boolean;
42
+ /** Cleanup/finaliser code swallows errors on purpose; treat it as medium. */
43
+ export declare function insideCleanupFunction(node: AstNode): boolean;
@@ -0,0 +1,163 @@
1
+ export function startOf(node) {
2
+ return { line: node.startPosition.row + 1, column: node.startPosition.column + 1 };
3
+ }
4
+ export function endOf(node) {
5
+ return { line: node.endPosition.row + 1, column: node.endPosition.column + 1 };
6
+ }
7
+ /** Trimmed first line of a node, capped for display. */
8
+ export function snippetOf(_ctx, node) {
9
+ const firstLine = node.text.split(/\r?\n/, 1)[0] ?? '';
10
+ const trimmed = firstLine.trim();
11
+ if (trimmed.length <= 160)
12
+ return trimmed;
13
+ return trimmed.slice(0, 157) + '...';
14
+ }
15
+ export function isComment(node) {
16
+ return node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment';
17
+ }
18
+ /** Named children that are actual statements (comments excluded). */
19
+ export function statementsOf(block) {
20
+ return block.namedChildren.filter((child) => !isComment(child));
21
+ }
22
+ /** Depth-limited, allocation-light walk over named children. */
23
+ export function walk(node, visit, maxDepth = 400) {
24
+ const stack = [{ node, depth: 0 }];
25
+ while (stack.length > 0) {
26
+ const entry = stack.pop();
27
+ if (!entry)
28
+ break;
29
+ const { node: current, depth } = entry;
30
+ const descend = visit(current, depth);
31
+ if (descend === false || depth >= maxDepth)
32
+ continue;
33
+ const children = current.namedChildren;
34
+ for (let i = children.length - 1; i >= 0; i -= 1) {
35
+ const child = children[i];
36
+ if (child)
37
+ stack.push({ node: child, depth: depth + 1 });
38
+ }
39
+ }
40
+ }
41
+ export function descendantsOfType(root, types) {
42
+ const wanted = new Set(types);
43
+ const found = [];
44
+ walk(root, (node) => {
45
+ if (wanted.has(node.type))
46
+ found.push(node);
47
+ });
48
+ return found;
49
+ }
50
+ /** Nearest ancestor whose type is in `types` (excluding the node itself). */
51
+ export function ancestorOfType(node, types) {
52
+ const wanted = new Set(types);
53
+ let current = node.parent;
54
+ while (current) {
55
+ if (wanted.has(current.type))
56
+ return current;
57
+ current = current.parent;
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Comments before the first statement of a block are often attached to the
63
+ * parent node instead of the block, so fall back to scanning the source lines.
64
+ */
65
+ export function hasCommentBetween(ctx, fromLine, toLine) {
66
+ for (let line = fromLine; line <= toLine; line += 1) {
67
+ const text = ctx.lines[line - 1] ?? '';
68
+ if (/(^|\s)#/.test(text) || text.includes('//') || text.trimStart().startsWith('/*')) {
69
+ return true;
70
+ }
71
+ }
72
+ return false;
73
+ }
74
+ export function collapseWhitespace(value) {
75
+ return value.replace(/\s+/g, ' ').trim();
76
+ }
77
+ /**
78
+ * Callee name of a call expression, normalised to the final segment:
79
+ * `foo.bar.baz(...)` -> `baz`, `expect(...)` -> `expect`.
80
+ */
81
+ export function calleeName(callNode) {
82
+ const fn = callNode.childForFieldName('function') ?? callNode.namedChildren[0];
83
+ if (!fn)
84
+ return undefined;
85
+ const text = collapseWhitespace(fn.text);
86
+ const segments = text.split('.');
87
+ return segments[segments.length - 1];
88
+ }
89
+ export function truncate(value, max) {
90
+ const single = collapseWhitespace(value);
91
+ return single.length <= max ? single : single.slice(0, max - 3) + '...';
92
+ }
93
+ /**
94
+ * Test files and fixtures are full of intentional stubs, dead branches and
95
+ * swallowed errors (they are testing those behaviours). Rules that are not
96
+ * test-specific skip them; `py/noop-test` and `ts/noop-test` are the rules
97
+ * that look at tests themselves.
98
+ */
99
+ export function isTestPath(file) {
100
+ const parts = file.toLowerCase().split('/');
101
+ const base = parts[parts.length - 1] ?? '';
102
+ if (/^test_.*\.pyi?$/.test(base) || /_tests?\.pyi?$/.test(base))
103
+ return true;
104
+ if (/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(base))
105
+ return true;
106
+ return parts.some((part) => part === 'test' || part === 'tests' || part === '__tests__');
107
+ }
108
+ /** True when the file name follows a test-module convention. */
109
+ export function looksLikeTestModule(file) {
110
+ const base = (file.split('/').pop() ?? '').toLowerCase();
111
+ return (/^test_.*\.pyi?$/.test(base) ||
112
+ /_tests?\.pyi?$/.test(base) ||
113
+ /\.(test|spec)\.(ts|tsx|js|jsx|mts|cts|mjs|cjs)$/.test(base));
114
+ }
115
+ /** Text of the function's leading docstring, if it has one. */
116
+ export function docstringOf(fn) {
117
+ const body = fn.childForFieldName('body');
118
+ const first = body?.namedChildren.find((child) => !isComment(child));
119
+ if (first?.type !== 'expression_statement')
120
+ return undefined;
121
+ const value = first.namedChildren[0];
122
+ return value?.type === 'string' ? value.text : undefined;
123
+ }
124
+ /** True when the function's body starts with a docstring. */
125
+ export function hasDocstring(fn) {
126
+ const body = fn.childForFieldName('body');
127
+ const first = body?.namedChildren.find((child) => !isComment(child));
128
+ return first?.type === 'expression_statement' && first.namedChildren[0]?.type === 'string';
129
+ }
130
+ /** True when the node sits inside `if __name__ == "__main__":`. */
131
+ export function insideMainGuard(node) {
132
+ let current = node.parent;
133
+ while (current) {
134
+ if (current.type === 'if_statement') {
135
+ const condition = current.childForFieldName('condition');
136
+ if (condition && /__name__/.test(condition.text))
137
+ return true;
138
+ }
139
+ current = current.parent;
140
+ }
141
+ return false;
142
+ }
143
+ const CLEANUP_NAMES = new Set([
144
+ 'close',
145
+ '__del__',
146
+ '__exit__',
147
+ 'cleanup',
148
+ '_cleanup',
149
+ 'shutdown',
150
+ 'stop',
151
+ 'cancel',
152
+ 'dispose',
153
+ 'finalize',
154
+ 'teardown',
155
+ 'tearDown',
156
+ 'reset',
157
+ ]);
158
+ /** Cleanup/finaliser code swallows errors on purpose; treat it as medium. */
159
+ export function insideCleanupFunction(node) {
160
+ const fn = ancestorOfType(node, ['function_definition', 'method_definition', 'function_declaration']);
161
+ const name = fn?.childForFieldName('name')?.text;
162
+ return name !== undefined && name !== null && CLEANUP_NAMES.has(name);
163
+ }
@@ -0,0 +1,3 @@
1
+ import type { Rule } from '../types.ts';
2
+ export declare const ALL_RULES: readonly Rule[];
3
+ export declare const RULE_BY_ID: ReadonlyMap<string, Rule>;
@@ -0,0 +1,4 @@
1
+ import { pythonRules } from "./python.js";
2
+ import { typescriptRules } from "./typescript.js";
3
+ export const ALL_RULES = [...pythonRules, ...typescriptRules];
4
+ export const RULE_BY_ID = new Map(ALL_RULES.map((rule) => [rule.meta.id, rule]));
@@ -0,0 +1,2 @@
1
+ import type { Rule } from '../types.ts';
2
+ export declare const pythonRules: Rule[];