@bbcsoftwarefactory/cli 0.0.0-stage → 0.1.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.
package/dist/bbc.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bbc.js ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * LAYER: Interface
4
+ * Contains: CLI entry point.
5
+ * Rules: Write help to stdout and input errors to stderr.
6
+ * BigO: O(1) score:5
7
+ * keywords: [CliEntryPoint, CommandArguments]
8
+ * GOAL: Translate command-line arguments into process output and exit status.
9
+ */
10
+ import { classifyChangeLane, classifyChangeLaneUsage } from "./classify-change-lane.js";
11
+ import { extractDiffScope, extractDiffScopeUsage } from "./extract-diff-scope.js";
12
+ import { measureBigo, measureBigoUsage } from "./measure-bigo.js";
13
+ import { renderWorkflow, renderWorkflowUsage } from "./render-workflow.js";
14
+ const usage = 'Usage: bbc <command> [arguments]\n';
15
+ function main([command, ...args]) {
16
+ const [argument] = args;
17
+ if (command === undefined) {
18
+ process.stderr.write(usage);
19
+ return 1;
20
+ }
21
+ if (command === '--help' && argument !== undefined) {
22
+ process.stderr.write(`Unexpected argument after --help: ${JSON.stringify(argument)}\n${usage}`);
23
+ return 1;
24
+ }
25
+ if (command === '--help') {
26
+ process.stdout.write(`${usage}\nCommands:\n ${measureBigoUsage}\n ${classifyChangeLaneUsage}\n ${renderWorkflowUsage}\n ${extractDiffScopeUsage}\n`);
27
+ return 0;
28
+ }
29
+ if (command === 'measure-bigo')
30
+ return measureBigo(args);
31
+ if (command === 'classify-change-lane')
32
+ return classifyChangeLane(args);
33
+ if (command === 'render-workflow')
34
+ return renderWorkflow(args);
35
+ if (command === 'extract-diff-scope')
36
+ return extractDiffScope(args);
37
+ process.stderr.write(`Unknown command: ${JSON.stringify(command)}\n${usage}`);
38
+ return 1;
39
+ }
40
+ process.exitCode = main(process.argv.slice(2));
@@ -0,0 +1,18 @@
1
+ interface Counts {
2
+ loc: number;
3
+ codeLines: number;
4
+ loops: number;
5
+ maxNest: number;
6
+ lookup: number;
7
+ spread: number;
8
+ sorts: number;
9
+ binary: boolean;
10
+ }
11
+ export interface Complexity {
12
+ bigo: string;
13
+ score: number;
14
+ }
15
+ export declare function analyze(text: string): Counts;
16
+ export declare function decideBigo(c: Counts): Complexity;
17
+ export declare function signals(c: Counts): string[];
18
+ export {};
@@ -0,0 +1,139 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Big O counters, classifications, and ordered signals.
4
+ * Rules: Infer complexity from lexical evidence rather than parsed syntax.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [ComplexityCounters, LoopNesting, ComplexitySignals]
7
+ * GOAL: Score a file or function body using the legacy heuristic.
8
+ */
9
+ import { asciiSpace as ws, createStripper, records, withoutTrailingCR } from "./lexical.js";
10
+ const iter = 'forEach|map|filter|reduce|reduceRight|flatMap|some|every|find|findIndex';
11
+ const loop = new RegExp([
12
+ `for${ws}*(await${ws}*)?\\(`, `for${ws}+`, `while${ws}*\\(`, `do${ws}*\\{`,
13
+ ].map((pattern) => `(?:^|[^A-Za-z0-9_.$])${pattern}`).concat(`\\.(${iter}|sort)${ws}*\\(`).join('|'));
14
+ const colonEnd = new RegExp(`:${ws}*$`);
15
+ const pythonWhile = new RegExp(`(?:^|[^A-Za-z0-9_.$])while${ws}+`);
16
+ const reduce = new RegExp(`\\.reduce${ws}*\\(`);
17
+ const sort = new RegExp(`\\.sort${ws}*\\(`);
18
+ const lookup = new RegExp(`\\.(includes|indexOf)${ws}*\\(`);
19
+ const call = new RegExp(`\\.(${iter})${ws}*\\(`, 'g');
20
+ const inner = new RegExp(`\\.(${iter}|includes|indexOf)${ws}*\\(`);
21
+ const spread = /\.\.\.[A-Za-z_]/;
22
+ const mid = /(^|[^A-Za-z0-9_])mid([^A-Za-z0-9_]|$)/;
23
+ const bound = /(^|[^A-Za-z0-9_])(low|high|left|right)([^A-Za-z0-9_]|$)/;
24
+ function loopKind(line) {
25
+ if (reduce.test(line))
26
+ return 'reduce';
27
+ if (sort.test(line))
28
+ return 'sort';
29
+ if (loop.test(line) || (colonEnd.test(line) && pythonWhile.test(line)))
30
+ return 'loop';
31
+ }
32
+ function lineIndent(line) {
33
+ let width = 0;
34
+ for (const char of line) {
35
+ if (char === ' ')
36
+ width += 1;
37
+ else if (char === '\t')
38
+ width += 2;
39
+ else
40
+ break;
41
+ }
42
+ return width;
43
+ }
44
+ function callBodyEnd(line, start) {
45
+ let depth = 1;
46
+ for (let index = start; index < line.length; index += 1) {
47
+ if (line[index] === '(')
48
+ depth += 1;
49
+ if (line[index] === ')' && --depth === 0)
50
+ return index;
51
+ }
52
+ return line.length;
53
+ }
54
+ function inlineLookup(line) {
55
+ call.lastIndex = 0;
56
+ while (call.exec(line)) {
57
+ const start = call.lastIndex;
58
+ const end = callBodyEnd(line, start);
59
+ if (inner.test(line.slice(start, end)))
60
+ return true;
61
+ // All candidate calls inside this body are included in `inner`; a miss lets us skip the span.
62
+ call.lastIndex = Math.min(end + 1, line.length);
63
+ }
64
+ return false;
65
+ }
66
+ export function analyze(text) {
67
+ const lines = records(text);
68
+ const counts = { loc: lines.length, codeLines: 0, loops: 0, maxNest: 0, lookup: 0, spread: 0, sorts: 0, binary: false };
69
+ const strip = createStripper();
70
+ const stack = [];
71
+ let reduceDepth = 0;
72
+ let sawMid = false;
73
+ let sawBound = false;
74
+ for (const raw of lines) {
75
+ const line = strip(withoutTrailingCR(raw));
76
+ if (/^[ \t]*$/.test(line))
77
+ continue;
78
+ counts.codeLines += 1;
79
+ if (/^[ \t]*\{[ \t]*$/.test(line))
80
+ continue;
81
+ const indent = lineIndent(line);
82
+ for (let top = stack.at(-1); top && top.indent >= indent; top = stack.at(-1)) {
83
+ reduceDepth -= Number(top.kind === 'reduce');
84
+ stack.pop();
85
+ }
86
+ const kind = loopKind(line);
87
+ if (kind) {
88
+ stack.push({ indent, kind });
89
+ counts.loops += 1;
90
+ counts.maxNest = Math.max(counts.maxNest, stack.length);
91
+ reduceDepth += Number(kind === 'reduce');
92
+ counts.sorts += Number(sort.test(line));
93
+ }
94
+ if (stack.length === 0)
95
+ continue;
96
+ if (lookup.test(line) || inlineLookup(line))
97
+ counts.lookup += 1;
98
+ if (reduceDepth > 0 && spread.test(line))
99
+ counts.spread += 1;
100
+ sawMid ||= mid.test(line);
101
+ sawBound ||= bound.test(line);
102
+ counts.binary ||= sawMid && sawBound;
103
+ }
104
+ return counts;
105
+ }
106
+ export function decideBigo(c) {
107
+ if (c.maxNest >= 3)
108
+ return { bigo: 'O(n^3)', score: 1 };
109
+ if (c.maxNest >= 2 || c.lookup || c.spread)
110
+ return { bigo: 'O(n^2)', score: 1 };
111
+ if (c.sorts)
112
+ return { bigo: 'O(n log n)', score: 2 };
113
+ if (c.binary && c.loops)
114
+ return { bigo: 'O(log n)', score: 4 };
115
+ if (c.loops)
116
+ return { bigo: 'O(n)', score: 3 };
117
+ return { bigo: 'O(1)', score: 5 };
118
+ }
119
+ export function signals(c) {
120
+ const out = [];
121
+ const clean = c.maxNest < 2 && !c.lookup && !c.spread;
122
+ if (c.maxNest >= 3)
123
+ out.push('deep_nesting');
124
+ if (c.maxNest >= 2)
125
+ out.push('nested_loop');
126
+ if (c.lookup)
127
+ out.push('lookup_in_loop');
128
+ if (c.spread)
129
+ out.push('spread_in_reduce');
130
+ if (c.sorts)
131
+ out.push('sort');
132
+ if (c.binary && clean)
133
+ out.push('logarithmic');
134
+ if (c.loops && clean && !c.sorts && !c.binary)
135
+ out.push('single_pass');
136
+ if (!c.loops || out.length === 0)
137
+ out.push('constant');
138
+ return out;
139
+ }
@@ -0,0 +1,5 @@
1
+ import type { Complexity } from './complexity.ts';
2
+ export declare function functionReports(text: string, python: boolean): (Complexity & {
3
+ name: string;
4
+ line: number;
5
+ })[];
@@ -0,0 +1,174 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Heuristic function boundaries and scores.
4
+ * Rules: An inner named function owns its lines; anonymous callbacks do not.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [FunctionBoundary, FunctionScore]
7
+ * GOAL: Score the lines owned by each named declaration in source order.
8
+ */
9
+ import { analyze, decideBigo } from "./complexity.js";
10
+ import { createStripper, records, unicodeSpace, unicodeWord, withoutTrailingCR } from "./lexical.js";
11
+ const word = unicodeWord.slice(1, -1);
12
+ function declarationPattern(pattern) {
13
+ return new RegExp(pattern.replace('function\\b', `function(?!${unicodeWord})`)
14
+ .replaceAll('\\s', unicodeSpace).replaceAll('\\w', word), 'u');
15
+ }
16
+ const declarations = [
17
+ String.raw `^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(`,
18
+ String.raw `^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)`,
19
+ String.raw `^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w]*)\s*\(`,
20
+ ].map(declarationPattern);
21
+ const methodPrefix = declarationPattern(String.raw `^\s*(?:(?:public|private|protected|static|final|abstract|async|override|readonly|synchronized|function)\s+)*(?:[\w$<>\[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*\(`);
22
+ const whitespaceOnly = new RegExp(`^${unicodeSpace}*$`, 'u');
23
+ const methodTail = new RegExp(`^${unicodeSpace}*(?:throws${unicodeSpace}[${word}.,${unicodeSpace.slice(1, -1)}]+)?$`, 'u');
24
+ const returnType = new RegExp(`\\)${unicodeSpace}*:[^{;=]+$`, 'u');
25
+ const notFunctions = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'do', 'else', 'with',
26
+ 'typeof', 'new', 'await', 'super', 'constructor_call']);
27
+ const pyDef = new RegExp(`^([ \\t]*)(?:async${unicodeSpace}+)?def${unicodeSpace}+([A-Za-z_]${unicodeWord}*)${unicodeSpace}*\\(`, 'u');
28
+ const pyLeading = new RegExp(`^${unicodeSpace}*`);
29
+ function scanBraces(line, index, pairs, open) {
30
+ for (const char of line) {
31
+ if (char === '{') {
32
+ const pair = { start: index, end: -1 };
33
+ pairs.push(pair);
34
+ open.push(pair);
35
+ }
36
+ if (char !== '}')
37
+ continue;
38
+ const pair = open.pop();
39
+ if (pair)
40
+ pair.end = index;
41
+ }
42
+ }
43
+ function bracePairs(lines) {
44
+ const pairs = [];
45
+ const open = [];
46
+ for (const [index, line] of lines.entries())
47
+ scanBraces(line, index, pairs, open);
48
+ return pairs.filter((pair) => pair.end !== -1);
49
+ }
50
+ function methodName(line) {
51
+ const brace = line.lastIndexOf('{');
52
+ if (brace < 0 || !whitespaceOnly.test(line.slice(brace + 1)))
53
+ return undefined;
54
+ const prefix = methodPrefix.exec(line);
55
+ const name = prefix?.[1];
56
+ if (!prefix || !name || notFunctions.has(name) || prefix[0].length > brace)
57
+ return undefined;
58
+ const body = line.slice(prefix[0].length, brace);
59
+ const lastClose = body.lastIndexOf(')');
60
+ if (lastClose < 0 || body.includes(';'))
61
+ return undefined;
62
+ if (methodTail.test(body.slice(lastClose + 1)))
63
+ return name;
64
+ // An earlier ')' can still end the parameters when a return annotation contains ')'.
65
+ // Start after the last forbidden type character so failed candidates cannot rescan the suffix.
66
+ const typeStart = Math.max(body.lastIndexOf('{'), body.lastIndexOf('=')) + 1;
67
+ if (returnType.test(body.slice(typeStart)))
68
+ return name;
69
+ }
70
+ function braceDeclaration(line) {
71
+ for (const [index, pattern] of declarations.entries()) {
72
+ const name = pattern.exec(line)?.[1];
73
+ if (name && !notFunctions.has(name))
74
+ return { name, expression: index === 1 && !line.includes('{') };
75
+ }
76
+ const method = methodName(line);
77
+ if (method)
78
+ return { name: method, expression: false };
79
+ }
80
+ function braceFunctions(lines) {
81
+ const strip = createStripper();
82
+ const stripped = lines.map(strip);
83
+ const pairs = bracePairs(stripped);
84
+ const found = [];
85
+ let first = 0;
86
+ for (const [index, line] of stripped.entries()) {
87
+ while ((pairs[first]?.start ?? Infinity) < index)
88
+ first += 1;
89
+ const declaration = braceDeclaration(line);
90
+ if (!declaration)
91
+ continue;
92
+ const { name, expression } = declaration;
93
+ const pair = pairs[first];
94
+ if (expression)
95
+ found.push({ name, start: index, end: index });
96
+ else if (pair && pair.start <= index + 2)
97
+ found.push({ name, start: index, end: pair.end });
98
+ }
99
+ return found;
100
+ }
101
+ function expandTabWidth(indent) {
102
+ let width = 0;
103
+ for (const char of indent)
104
+ width += char === '\t' ? 8 - (width % 8) : 1;
105
+ return width;
106
+ }
107
+ function indexPythonLines(lines) {
108
+ let lastNonblank = -1;
109
+ const indexed = lines.map((text, index) => {
110
+ const indent = pyLeading.exec(text)?.[0].length ?? 0;
111
+ const previousNonblank = lastNonblank;
112
+ if (indent < text.length)
113
+ lastNonblank = index;
114
+ return { index, text, indent, previousNonblank };
115
+ });
116
+ return { indexed, lastNonblank };
117
+ }
118
+ function nearestDedent(candidates, width) {
119
+ let low = 0;
120
+ let high = candidates.length;
121
+ while (low < high) {
122
+ const mid = low + Math.floor((high - low) / 2);
123
+ if ((candidates[mid]?.indent ?? Infinity) <= width)
124
+ low = mid + 1;
125
+ else
126
+ high = mid;
127
+ }
128
+ return candidates[low - 1];
129
+ }
130
+ function pythonFunctions(lines) {
131
+ const { indexed, lastNonblank } = indexPythonLines(lines);
132
+ const found = [];
133
+ const candidates = [];
134
+ for (const line of indexed.reverse()) {
135
+ const { index, text, indent } = line;
136
+ const [, defIndent, name] = pyDef.exec(text) ?? [];
137
+ if (defIndent !== undefined && name !== undefined) {
138
+ // The legacy rule compares the expanded declaration indent with raw body whitespace.
139
+ const stop = nearestDedent(candidates, expandTabWidth(defIndent));
140
+ found.push({ name, start: index, end: stop?.previousNonblank ?? lastNonblank });
141
+ }
142
+ if (indent === text.length || text[indent] === '#')
143
+ continue;
144
+ // A closer candidate of equal or smaller indent hides every farther candidate it pops.
145
+ while ((candidates.at(-1)?.indent ?? -1) >= indent)
146
+ candidates.pop();
147
+ candidates.push(line);
148
+ }
149
+ return found.reverse();
150
+ }
151
+ export function functionReports(text, python) {
152
+ const lines = records(text).map(withoutTrailingCR);
153
+ const found = python ? pythonFunctions(lines) : braceFunctions(lines);
154
+ if (found.length === 0)
155
+ return [];
156
+ const open = [];
157
+ const bodies = found.map(() => []);
158
+ let next = 0;
159
+ for (const [index, line] of lines.entries()) {
160
+ const current = found[next];
161
+ const body = bodies[next];
162
+ // Discovery emits at most one declaration per line, in start order.
163
+ if (current?.start === index && body) {
164
+ open.push({ end: current.end, body });
165
+ next += 1;
166
+ }
167
+ while ((open.at(-1)?.end ?? Infinity) < index)
168
+ open.pop();
169
+ open.at(-1)?.body.push(line);
170
+ }
171
+ return found.map(({ name, start }, index) => ({
172
+ name, line: start + 1, ...decideBigo(analyze(`${bodies[index]?.join('\n') ?? ''}\n`)),
173
+ }));
174
+ }
@@ -0,0 +1 @@
1
+ export declare function suggestKeywords(text: string): string[];
@@ -0,0 +1,43 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Heuristic keyword suggestions from import and export lines.
4
+ * Rules: Prefer exported declarations, deduplicate within each group, and cap suggestions at twelve.
5
+ * BigO: O(n) score:3
6
+ * keywords: [KeywordSuggestions, LocalImportName]
7
+ * GOAL: Preserve the legacy keyword names and ordering for source headers.
8
+ */
9
+ import { asciiSpace as ws, records } from "./lexical.js";
10
+ const importLine = new RegExp(`^${ws}*import${ws}`);
11
+ const exportLine = new RegExp(`^${ws}*export${ws}`);
12
+ const exportDecl = new RegExp(`(?:class|interface|type|function|const|enum)${ws}+([A-Za-z_][A-Za-z0-9_]*)`);
13
+ const importType = new RegExp(`type${ws}+`, 'g');
14
+ const alias = new RegExp(`${ws}as${ws}+([A-Za-z_][A-Za-z0-9_]*)`);
15
+ const reserved = new Set(['type', 'typeof', 'as', 'from']);
16
+ function addImports(line, imports) {
17
+ const open = line.indexOf('{');
18
+ if (open < 0)
19
+ return;
20
+ const close = line.indexOf('}', open + 1);
21
+ if (close < 0)
22
+ return;
23
+ const names = line.slice(open + 1, close).replace(importType, '').split(',');
24
+ for (const item of names) {
25
+ const name = alias.exec(item)?.[1] ?? item.replace(/[^A-Za-z0-9_]/g, '');
26
+ if (name && !reserved.has(name))
27
+ imports.add(name);
28
+ }
29
+ }
30
+ export function suggestKeywords(text) {
31
+ const exports = new Set();
32
+ const imports = new Set();
33
+ for (const line of records(text)) {
34
+ if (importLine.test(line))
35
+ addImports(line, imports);
36
+ if (exportLine.test(line)) {
37
+ const name = exportDecl.exec(line)?.[1];
38
+ if (name && !reserved.has(name))
39
+ exports.add(name);
40
+ }
41
+ }
42
+ return [...exports, ...imports].slice(0, 12);
43
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Lexical preprocessing for the Big O heuristic.
4
+ * Rules: Keep legacy line boundaries and strip only the recognized tokens.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [SourceRecords, CommentStripper]
7
+ * GOAL: Expose the source lines used by the legacy heuristics.
8
+ */
9
+ export declare const asciiSpace = "[\\t-\\r ]";
10
+ export declare const unicodeSpace = "[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
11
+ export declare const unicodeWord = "[\\p{L}\\p{N}_]";
12
+ export declare function records(text: string): string[];
13
+ export declare function withoutTrailingCR(line: string): string;
14
+ export declare function createStripper(): (line: string) => string;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Lexical preprocessing for the Big O heuristic.
4
+ * Rules: Keep legacy line boundaries and strip only the recognized tokens.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [SourceRecords, CommentStripper]
7
+ * GOAL: Expose the source lines used by the legacy heuristics.
8
+ */
9
+ export const asciiSpace = '[\\t-\\r ]';
10
+ export const unicodeSpace = '[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
11
+ export const unicodeWord = '[\\p{L}\\p{N}_]';
12
+ export function records(text) {
13
+ const lines = text.split('\n');
14
+ if (lines.at(-1) === '')
15
+ lines.pop();
16
+ return lines;
17
+ }
18
+ export function withoutTrailingCR(line) {
19
+ return line.endsWith('\r') ? line.slice(0, -1) : line;
20
+ }
21
+ function afterString(line, start, quote) {
22
+ for (let cursor = start; cursor < line.length; cursor += 1) {
23
+ const char = line[cursor];
24
+ if (char === quote)
25
+ return cursor + 1;
26
+ if (char === '\\')
27
+ cursor += 1;
28
+ }
29
+ return line.length;
30
+ }
31
+ export function createStripper() {
32
+ let inBlock = false;
33
+ const special = /\/\/|\/\*|["'`]/g;
34
+ return (line) => {
35
+ let cursor = 0;
36
+ if (inBlock) {
37
+ const end = line.indexOf('*/');
38
+ if (end < 0)
39
+ return '';
40
+ inBlock = false;
41
+ cursor = end + 2;
42
+ }
43
+ const fragments = [];
44
+ while (cursor < line.length) {
45
+ special.lastIndex = cursor;
46
+ const token = special.exec(line);
47
+ if (!token) {
48
+ fragments.push(line.slice(cursor));
49
+ break;
50
+ }
51
+ fragments.push(line.slice(cursor, token.index));
52
+ const [mark] = token;
53
+ if (mark === '//')
54
+ break;
55
+ if (mark !== '/*') {
56
+ cursor = afterString(line, special.lastIndex, mark);
57
+ fragments.push(' ');
58
+ continue;
59
+ }
60
+ const end = line.indexOf('*/', special.lastIndex);
61
+ if (end < 0) {
62
+ inBlock = true;
63
+ break;
64
+ }
65
+ cursor = end + 2;
66
+ }
67
+ return fragments.join('');
68
+ };
69
+ }
@@ -0,0 +1 @@
1
+ export declare function targetFiles(target: string): string[] | undefined;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * LAYER: Infrastructure
3
+ * Contains: Filesystem discovery for the Big O CLI.
4
+ * Rules: Retain argument spelling and do not descend into discovered links or excluded trees.
5
+ * BigO: O(n log n) score:2
6
+ * keywords: [SourceDiscovery, DirectoryExclusions]
7
+ * GOAL: Collect regular source files in legacy path order without following discovered symlinks.
8
+ */
9
+ import { readdirSync, statSync } from 'node:fs';
10
+ import { sep } from 'node:path';
11
+ const extensions = /\.(ts|tsx|js|mjs|cjs|py|java|go|php)$/;
12
+ const excluded = /\/(node_modules|dist|\.git|coverage)\//;
13
+ const windows = sep === '\\';
14
+ function endsWithSeparator(path) {
15
+ return path.endsWith(sep) || (windows && path.endsWith('/'));
16
+ }
17
+ function childPath(parent, name) {
18
+ // path.join normalizes away caller-provided dots, redundant separators, and mixed separators.
19
+ const canAppend = endsWithSeparator(parent) || (windows && /^[A-Za-z]:$/.test(parent));
20
+ return canAppend ? parent + name : parent + sep + name;
21
+ }
22
+ function excludedPath(path) {
23
+ return excluded.test(windows ? path.replaceAll('\\', '/') : path);
24
+ }
25
+ function comparePaths(a, b) {
26
+ // Python sorts Unicode code points, not UTF-16 code units.
27
+ let offset = 0;
28
+ for (const char of a) {
29
+ const other = b.codePointAt(offset);
30
+ if (other === undefined)
31
+ return 1;
32
+ const point = char.codePointAt(0) ?? 0;
33
+ if (point !== other)
34
+ return point - other;
35
+ offset += char.length;
36
+ }
37
+ return offset - b.length;
38
+ }
39
+ function readDirectory(path) {
40
+ try {
41
+ return readdirSync(path, { withFileTypes: true });
42
+ }
43
+ catch {
44
+ // Like os.walk without an onerror handler, ignore inaccessible directories.
45
+ return [];
46
+ }
47
+ }
48
+ function targetStat(target) {
49
+ try {
50
+ return statSync(target, { throwIfNoEntry: false });
51
+ }
52
+ catch {
53
+ // Python's stat-based isfile/isdir predicates also reject inaccessible targets.
54
+ return undefined;
55
+ }
56
+ }
57
+ function scanDirectory(root, pending, found) {
58
+ if (excludedPath(childPath(root, '_')))
59
+ return;
60
+ for (const entry of readDirectory(root)) {
61
+ const path = childPath(root, entry.name);
62
+ if (entry.isDirectory())
63
+ pending.push(path);
64
+ else if (entry.isFile() && extensions.test(entry.name))
65
+ found.push(path);
66
+ }
67
+ }
68
+ export function targetFiles(target) {
69
+ const stat = targetStat(target);
70
+ // Node's Windows stat accepts a regular file even with a trailing separator; Python rejects it.
71
+ if (stat?.isFile())
72
+ return endsWithSeparator(target) ? undefined : [target];
73
+ if (!stat?.isDirectory())
74
+ return undefined;
75
+ const pending = [target];
76
+ const found = [];
77
+ for (let root = pending.pop(); root !== undefined; root = pending.pop())
78
+ scanDirectory(root, pending, found);
79
+ return found.sort(comparePaths);
80
+ }
@@ -0,0 +1,41 @@
1
+ declare const plans: {
2
+ trivial: {
3
+ test_mode: string;
4
+ required_stages: string[];
5
+ skipped_stages: string[];
6
+ extra_checks: string[];
7
+ };
8
+ standard: {
9
+ test_mode: string;
10
+ required_stages: string[];
11
+ skipped_stages: string[];
12
+ extra_checks: string[];
13
+ };
14
+ 'high-risk': {
15
+ test_mode: string;
16
+ required_stages: string[];
17
+ skipped_stages: never[];
18
+ extra_checks: string[];
19
+ };
20
+ };
21
+ type Lane = keyof typeof plans;
22
+ export interface ChangeSet {
23
+ files: readonly string[];
24
+ added: number;
25
+ removed: number;
26
+ }
27
+ export interface LaneReport {
28
+ lane: Lane;
29
+ reasons: readonly string[];
30
+ files_changed: number;
31
+ lines_added: number;
32
+ lines_removed: number;
33
+ lines_changed: number;
34
+ files: readonly string[];
35
+ test_mode: string;
36
+ required_stages: readonly string[];
37
+ skipped_stages: readonly string[];
38
+ extra_checks: readonly string[];
39
+ }
40
+ export declare function classify(change: ChangeSet, windows: boolean): LaneReport;
41
+ export {};