traceyard 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.
@@ -0,0 +1,118 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import { isAbsolute, join, relative } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { sanitizeDiagnostic } from "./test-report.mjs";
5
+
6
+ export const isPytestFile = (path) => /(?:^|\/)(?:test_[^/]+|[^/]+_test)\.py$/.test(path);
7
+ const casePattern = /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*(?:\[[^\p{Cc}]{0,150}\])?$/u;
8
+
9
+ export function validPytestCase(value) {
10
+ return typeof value === "string" && value.length <= 240 && casePattern.test(value);
11
+ }
12
+
13
+ export async function preparePytest(directory, file, test, plan) {
14
+ if (plan.replayRecording || plan.flakeCandidate)
15
+ return {
16
+ reason:
17
+ "This Pytest runner supports focused test execution. Replay and flakiness runs require Vitest.",
18
+ };
19
+ if (plan.testCase !== undefined && !validPytestCase(plan.testCase))
20
+ return { reason: "Provide a valid Pytest case selector, without the file path." };
21
+ for (const name of ["requirements-test.txt", "requirements.txt"]) {
22
+ const path = join(directory, name);
23
+ const stat = await lstat(path).catch(() => null);
24
+ if (!stat) continue;
25
+ const inside = relative(directory, await realpath(path));
26
+ if (!stat.isFile() || stat.size > 128000 || inside.startsWith("..") || isAbsolute(inside))
27
+ return { reason: "Pytest requires a regular requirements file in its package." };
28
+ return {
29
+ directory,
30
+ file,
31
+ requirements: path,
32
+ runner: "pytest",
33
+ command: {
34
+ directory: test.packageDirectory,
35
+ script: "pytest",
36
+ testPath: test.path,
37
+ ...(plan.testCase ? { testCase: plan.testCase } : {}),
38
+ },
39
+ };
40
+ }
41
+ return {
42
+ reason:
43
+ "Add requirements-test.txt or requirements.txt containing Pytest to this Python package.",
44
+ };
45
+ }
46
+
47
+ export function pytestEnvironment(env, install = false) {
48
+ return Object.fromEntries(
49
+ Object.entries(env).filter(
50
+ ([key]) =>
51
+ (install && /^(?:HTTPS?|NO|ALL)_PROXY$/i.test(key)) ||
52
+ /^(?:PATH|SYSTEMROOT|HOME|USERPROFILE|TMPDIR|TMP|TEMP|CI|LANG|LC_ALL|SSL_CERT_FILE|SSL_CERT_DIR)$/i.test(
53
+ key,
54
+ ),
55
+ ),
56
+ );
57
+ }
58
+
59
+ export const pytestArgs = (file, testCase, output) => [
60
+ "-I",
61
+ fileURLToPath(new URL("./pytest-runner.py", import.meta.url)),
62
+ file,
63
+ testCase ?? "",
64
+ output,
65
+ ];
66
+
67
+ export function normalizePytestEvidence(data, exitCode, command) {
68
+ if (data.reason) throw Error(sanitizeDiagnostic(data.reason, 500));
69
+ const results = data.results;
70
+ if (
71
+ ![0, 1].includes(exitCode) ||
72
+ !Array.isArray(results) ||
73
+ !results.length ||
74
+ (command.testCase && (results.length !== 1 || results[0]?.name !== command.testCase)) ||
75
+ results.some(
76
+ (item) =>
77
+ typeof item?.name !== "string" || !["passed", "failed", "skipped"].includes(item.status),
78
+ )
79
+ )
80
+ throw Error("Pytest did not report a complete outcome for the selected test.");
81
+ const counts = { passed: 0, failed: 0, skipped: 0 };
82
+ const failures = [];
83
+ let truncated = false;
84
+ for (const item of results) {
85
+ counts[item.status]++;
86
+ if (item.status !== "failed") continue;
87
+ if (failures.length >= 8) {
88
+ truncated = true;
89
+ continue;
90
+ }
91
+ const diagnostic =
92
+ typeof item.message === "string" ? item.message : "Pytest reported a failure.";
93
+ if (diagnostic.length > 1500) truncated = true;
94
+ failures.push({
95
+ file: command.testPath,
96
+ name: sanitizeDiagnostic(item.name, 250),
97
+ message: sanitizeDiagnostic(diagnostic),
98
+ });
99
+ }
100
+ if (counts.failed > 0 !== (exitCode === 1))
101
+ throw Error("The Pytest process and retained outcomes disagree.");
102
+ const status = counts.failed ? "FAILED" : counts.passed ? "SUCCEEDED" : "BLOCKED";
103
+ return {
104
+ status,
105
+ counts,
106
+ failures,
107
+ truncated,
108
+ message:
109
+ "Pytest: " +
110
+ counts.passed +
111
+ " passed, " +
112
+ counts.failed +
113
+ " failed, " +
114
+ counts.skipped +
115
+ " skipped." +
116
+ (status === "BLOCKED" ? " No passing executed case establishes success." : ""),
117
+ };
118
+ }
@@ -0,0 +1,310 @@
1
+ import { readdir, readFile, lstat, realpath } from "node:fs/promises";
2
+ import { posix, resolve, relative, join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { parse } from "@babel/parser";
5
+ import { isPytestFile } from "./pytest.mjs";
6
+
7
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
8
+ const isCode = (path) => /\.[cm]?[jt]sx?$/.test(path) && !/\.d\.[cm]?[jt]s$/.test(path);
9
+ const isTest = (path) =>
10
+ /(?:\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)(?:__tests__|tests?|specs?)\/)/.test(path);
11
+ const ignored = new Set([
12
+ "node_modules",
13
+ "vendor",
14
+ "dist",
15
+ "build",
16
+ "coverage",
17
+ ".git",
18
+ ".next",
19
+ ".traceyard-runner",
20
+ ".venv",
21
+ ]);
22
+ function visit(node, fn) {
23
+ if (!node || typeof node !== "object") return;
24
+ if (typeof node.type === "string") fn(node);
25
+ for (const [key, value] of Object.entries(node)) {
26
+ if (["loc", "start", "end", "comments", "tokens"].includes(key)) continue;
27
+ if (Array.isArray(value)) value.forEach((x) => visit(x, fn));
28
+ else if (value && typeof value === "object") visit(value, fn);
29
+ }
30
+ }
31
+ function callName(node) {
32
+ return node?.type === "Identifier"
33
+ ? node.name
34
+ : node?.type === "MemberExpression"
35
+ ? `${callName(node.object)}.${callName(node.property)}`
36
+ : "";
37
+ }
38
+ export function analyzeRepositoryFiles(input) {
39
+ const files = [...input].sort((a, b) => a.path.localeCompare(b.path));
40
+ const paths = new Set(files.map((f) => f.path)),
41
+ warnings = [],
42
+ packages = [],
43
+ aliases = [];
44
+ for (const f of files.filter((f) => /(?:^|\/)package.json$/.test(f.path))) {
45
+ try {
46
+ const p = JSON.parse(f.content),
47
+ lock =
48
+ files.find((l) => l.path === posix.join(posix.dirname(f.path), "package-lock.json")) ??
49
+ files.find((l) => l.path === "package-lock.json"),
50
+ script = String(p.scripts?.test ?? ""),
51
+ directory = posix.dirname(f.path);
52
+ const dependencies = { ...p.dependencies, ...p.devDependencies };
53
+ packages.push({
54
+ directory,
55
+ name: String(p.name ?? directory).slice(0, 150),
56
+ scripts: Object.keys(p.scripts ?? {})
57
+ .filter((n) => /^[A-Za-z0-9:_-]{1,80}$/.test(n))
58
+ .slice(0, 50),
59
+ testRunner: /vitest/.test(script)
60
+ ? "vitest"
61
+ : /jest/.test(script)
62
+ ? "jest"
63
+ : /node\s+--test/.test(script)
64
+ ? "node"
65
+ : dependencies.vitest
66
+ ? "vitest"
67
+ : "unknown",
68
+ manager: paths.has(posix.join(directory, "pnpm-lock.yaml"))
69
+ ? "pnpm"
70
+ : paths.has(posix.join(directory, "yarn.lock"))
71
+ ? "yarn"
72
+ : "npm",
73
+ hash: hash(f.content),
74
+ lockHash: lock ? hash(lock.content) : null,
75
+ });
76
+ } catch {
77
+ warnings.push(`Cannot parse manifest: ${f.path}`);
78
+ }
79
+ }
80
+ for (const f of files.filter((f) => /(?:^|\/)tsconfig[^/]*\.json$/.test(f.path))) {
81
+ try {
82
+ const config = JSON.parse(f.content),
83
+ base = posix.join(posix.dirname(f.path), config.compilerOptions?.baseUrl ?? ".");
84
+ for (const [key, values] of Object.entries(config.compilerOptions?.paths ?? {})) {
85
+ for (const value of Array.isArray(values) ? values : [])
86
+ if (typeof value === "string")
87
+ aliases.push({ key, value, base, root: posix.dirname(f.path) });
88
+ }
89
+ } catch {
90
+ warnings.push(`Alias configuration needs unsupported JSON syntax: ${f.path}`);
91
+ }
92
+ }
93
+ const find = (base) => {
94
+ const variants = [
95
+ base,
96
+ ...[".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", "/index.ts", "/index.tsx", "/index.js"].map(
97
+ (ext) => base + ext,
98
+ ),
99
+ ];
100
+ if (/\.[cm]?js$/.test(base)) variants.push(base.replace(/\.[cm]?js$/, ".ts"));
101
+ return variants.find((p) => paths.has(p)) ?? null;
102
+ };
103
+ const resolveImport = (from, specifier) => {
104
+ if (specifier.startsWith("."))
105
+ return find(posix.normalize(posix.join(posix.dirname(from), specifier)));
106
+ for (const a of aliases) {
107
+ // A package-specific configuration must never resolve imports in another workspace.
108
+ const configRoot = a.root === "." ? "" : a.root + "/";
109
+ if (configRoot && !from.startsWith(configRoot)) continue;
110
+ const [before, after = ""] = a.key.split("*");
111
+ if (
112
+ a.key.includes("*")
113
+ ? specifier.startsWith(before) && specifier.endsWith(after)
114
+ : specifier === a.key
115
+ ) {
116
+ const middle = a.key.includes("*")
117
+ ? specifier.slice(before.length, specifier.length - after.length)
118
+ : "";
119
+ const found = find(posix.join(a.base, a.value.replace("*", middle)));
120
+ if (found) return found;
121
+ }
122
+ }
123
+ for (const p of packages)
124
+ if (specifier === p.name) {
125
+ const found =
126
+ find(posix.join(p.directory, "src/index")) ?? find(posix.join(p.directory, "index"));
127
+ if (found) return found;
128
+ }
129
+ return null;
130
+ };
131
+ const pythonPackages = new Set(
132
+ files
133
+ .filter((f) => /(?:^|\/)(?:requirements-test\.txt|requirements\.txt)$/.test(f.path))
134
+ .map((f) => posix.dirname(f.path)),
135
+ );
136
+ const indexed = [];
137
+ for (const f of files.filter((f) => isCode(f.path))) {
138
+ const record = {
139
+ path: f.path,
140
+ hash: hash(f.content),
141
+ imports: [],
142
+ tests: [],
143
+ definitions: [],
144
+ isTest: isTest(f.path),
145
+ packageDirectory:
146
+ [...packages]
147
+ .sort((a, b) => b.directory.length - a.directory.length)
148
+ .find((p) => p.directory === "." || f.path.startsWith(p.directory + "/"))?.directory ??
149
+ ".",
150
+ };
151
+ try {
152
+ const ast = parse(f.content, {
153
+ sourceType: "unambiguous",
154
+ plugins: ["typescript", "jsx"],
155
+ errorRecovery: false,
156
+ });
157
+ const imports = new Set();
158
+ visit(ast.program, (node) => {
159
+ if (
160
+ ["ImportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"].includes(
161
+ node.type,
162
+ ) &&
163
+ node.source?.value
164
+ )
165
+ imports.add(node.source.value);
166
+ if (
167
+ node.type === "CallExpression" &&
168
+ node.callee?.name === "require" &&
169
+ node.arguments[0]?.type === "StringLiteral"
170
+ )
171
+ imports.add(node.arguments[0].value);
172
+ if (
173
+ record.isTest &&
174
+ node.type === "CallExpression" &&
175
+ /^(?:it|test|describe)(?:\.(?:only|skip|todo|concurrent|sequential|each))*$/.test(
176
+ callName(node.callee),
177
+ ) &&
178
+ node.arguments[0]?.type === "StringLiteral" &&
179
+ record.tests.length < 40
180
+ )
181
+ record.tests.push({
182
+ name: node.arguments[0].value.slice(0, 200),
183
+ line: node.loc?.start.line ?? 1,
184
+ });
185
+ if (
186
+ ["FunctionDeclaration", "ClassDeclaration"].includes(node.type) &&
187
+ node.id?.name &&
188
+ record.definitions.length < 40
189
+ )
190
+ record.definitions.push(node.id.name.slice(0, 100));
191
+ });
192
+ record.imports = [...imports].slice(0, 40).map((specifier) => ({
193
+ specifier: specifier.slice(0, 240),
194
+ resolved: resolveImport(f.path, specifier),
195
+ }));
196
+ if (imports.size > 40) warnings.push(`Import relationships truncated: ${f.path}`);
197
+ } catch {
198
+ warnings.push(`Cannot parse source: ${f.path}`);
199
+ }
200
+ record.isTest =
201
+ record.isTest &&
202
+ (/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(record.path) || record.tests.length > 0);
203
+ if (Buffer.byteLength(JSON.stringify(record)) > 20000) {
204
+ warnings.push(`File metadata truncated: ${f.path}`);
205
+ while (Buffer.byteLength(JSON.stringify(record)) > 20000) {
206
+ if (record.imports.length) record.imports.pop();
207
+ else if (record.tests.length) record.tests.pop();
208
+ else record.definitions.pop();
209
+ }
210
+ }
211
+ indexed.push(record);
212
+ }
213
+ for (const file of files.filter((f) => isPytestFile(f.path))) {
214
+ let directory = posix.dirname(file.path);
215
+ while (directory !== "." && !pythonPackages.has(directory))
216
+ directory = posix.dirname(directory);
217
+ const tests = [];
218
+ const lines = file.content.split("\n");
219
+ for (const [index, line] of lines.entries()) {
220
+ const match = /^\s*(?:async\s+)?def\s+(test_\w+)\s*\(/.exec(line);
221
+ if (match && tests.length < 40) tests.push({ name: match[1].slice(0, 200), line: index + 1 });
222
+ }
223
+ indexed.push({
224
+ path: file.path,
225
+ hash: hash(file.content),
226
+ imports: [],
227
+ tests,
228
+ definitions: [],
229
+ isTest: true,
230
+ packageDirectory: directory,
231
+ });
232
+ }
233
+ return {
234
+ schemaVersion: 1,
235
+ snapshotId: hash(JSON.stringify(files.map((f) => [f.path, hash(f.content)]))),
236
+ packages: packages.slice(0, 50),
237
+ files: indexed,
238
+ coverage: {
239
+ scanned: indexed.length,
240
+ skipped: 0,
241
+ truncated: packages.length > 50 || warnings.some((w) => w.includes("truncated")),
242
+ warnings: warnings.slice(0, 20),
243
+ },
244
+ };
245
+ }
246
+ export function relatedTests(index, sourcePath) {
247
+ const selected = new Set([sourcePath]);
248
+ for (let i = 0; i <= index.files.length; i++) {
249
+ let changed = false;
250
+ for (const file of index.files)
251
+ if (
252
+ !selected.has(file.path) &&
253
+ file.imports.some((x) => x.resolved && selected.has(x.resolved))
254
+ ) {
255
+ selected.add(file.path);
256
+ changed = true;
257
+ }
258
+ if (!changed) break;
259
+ }
260
+ return index.files
261
+ .filter((f) => f.isTest && selected.has(f.path))
262
+ .map((f) => ({ path: f.path, packageDirectory: f.packageDirectory, tests: f.tests }));
263
+ }
264
+ export async function indexRepository(directory) {
265
+ const root = await realpath(directory),
266
+ files = [],
267
+ warnings = [];
268
+ let bytes = 0,
269
+ skipped = 0;
270
+ async function walk(dir) {
271
+ for (const e of await readdir(dir, { withFileTypes: true })) {
272
+ if (e.isSymbolicLink() || ignored.has(e.name) || e.name.startsWith(".env")) continue;
273
+ const full = join(dir, e.name),
274
+ path = relative(root, full).split("\\").join("/");
275
+ if (e.isDirectory()) {
276
+ if (!e.name.startsWith(".")) await walk(full);
277
+ continue;
278
+ }
279
+ if (!(
280
+ isCode(path) ||
281
+ isPytestFile(path) ||
282
+ /(?:^|\/)(?:requirements-test\.txt|requirements\.txt)$/.test(path) ||
283
+ /(?:^|\/)(?:package\.json|tsconfig[^/]*\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$/.test(
284
+ path,
285
+ )
286
+ ))
287
+ continue;
288
+ if (
289
+ path.length > 240 ||
290
+ files.length >= 5000 ||
291
+ bytes >= 12_000_000 ||
292
+ (await lstat(full)).size > (/lock|yarn/.test(e.name) ? 2000000 : 128000)
293
+ ) {
294
+ skipped++;
295
+ continue;
296
+ }
297
+ const content = await readFile(resolve(root, path), "utf8");
298
+ bytes += Buffer.byteLength(content);
299
+ files.push({ path, content });
300
+ }
301
+ }
302
+ await walk(root);
303
+ const index = analyzeRepositoryFiles(files);
304
+ if (skipped)
305
+ warnings.push(`Repository index skipped ${skipped} file(s) because of size/count limits.`);
306
+ index.coverage.skipped = skipped;
307
+ index.coverage.truncated ||= skipped > 0;
308
+ index.coverage.warnings.push(...warnings);
309
+ return index;
310
+ }
@@ -0,0 +1,103 @@
1
+ import { relative, resolve } from "node:path";
2
+ import {
3
+ isPytestFile,
4
+ normalizePytestEvidence,
5
+ preparePytest,
6
+ pytestArgs,
7
+ pytestEnvironment,
8
+ } from "./pytest.mjs";
9
+ import { normalizeVitestReport } from "./test-report.mjs";
10
+
11
+ /**
12
+ * A runner adapter turns "run this one test file" into a process and turns that
13
+ * process's structured report into Traceyard's result shape.
14
+ *
15
+ * @typedef {object} RunnerAdapter
16
+ * @property {"vitest" | "jest" | "pytest"} name
17
+ * @property {"javascript" | "python"} language
18
+ * @property {{ replay: boolean, retryControl: boolean, caseSelector: boolean }} supports
19
+ * @property {(command: string) => boolean} [matchesScript] package.json script detection (JS only)
20
+ * @property {(path: string) => boolean} [matchesFile] test file detection (Python only)
21
+ * @property {(input: { testArgument: string, output: string, plan: object }) => string[]} args
22
+ * Arguments for the runner; JS adapters receive them after the package script.
23
+ * @property {(env: Record<string, string | undefined>) => Record<string, string | undefined>} [environment]
24
+ * @property {(data: unknown, exitCode: number | null, context: { root: string, directory: string, file: string, command: object }) => object} normalize
25
+ * Throws or returns `{ blocked }` when the report cannot be trusted.
26
+ */
27
+
28
+ const scriptPattern =
29
+ /^(?:vitest|jest)(?=\s|$)|^node\s+["']?[^\r\n]*?[\\/](vitest\.mjs|jest\.js)["']?(?=\s|$)/;
30
+
31
+ function scriptRunner(command) {
32
+ const match = String(command).trim().match(scriptPattern);
33
+ if (!match) return null;
34
+ return match[0] === "jest" || match[1] === "jest.js" ? "jest" : "vitest";
35
+ }
36
+
37
+ function normalizeJsReport(data, exitCode, { root, directory, file }) {
38
+ if (!Array.isArray(data?.testResults) || !data.testResults.length)
39
+ return { blocked: "The test runner did not report a result for the selected file." };
40
+ if (data.testResults.some(({ name }) => relative(file, resolve(directory, String(name)))))
41
+ return { blocked: "The test script reported files outside the selected test." };
42
+ return normalizeVitestReport(data, exitCode, root);
43
+ }
44
+
45
+ /** @type {Record<string, RunnerAdapter>} */
46
+ export const runnerAdapters = {
47
+ vitest: {
48
+ name: "vitest",
49
+ language: "javascript",
50
+ supports: { replay: true, retryControl: true, caseSelector: false },
51
+ matchesScript: (command) => scriptRunner(command) === "vitest",
52
+ args: ({ testArgument, output, plan }) => [
53
+ "--run",
54
+ "--reporter=json",
55
+ ...(plan.flakeCandidate ? ["--retry=0"] : []),
56
+ testArgument,
57
+ "--outputFile=" + output,
58
+ ],
59
+ normalize: normalizeJsReport,
60
+ },
61
+ jest: {
62
+ name: "jest",
63
+ language: "javascript",
64
+ supports: { replay: false, retryControl: false, caseSelector: false },
65
+ matchesScript: (command) => scriptRunner(command) === "jest",
66
+ args: ({ testArgument, output }) => [
67
+ "--ci",
68
+ "--watch=false",
69
+ "--watchAll=false",
70
+ "--runTestsByPath",
71
+ "--json",
72
+ testArgument,
73
+ "--outputFile=" + output,
74
+ ],
75
+ normalize: normalizeJsReport,
76
+ },
77
+ pytest: {
78
+ name: "pytest",
79
+ language: "python",
80
+ supports: { replay: false, retryControl: false, caseSelector: true },
81
+ matchesFile: isPytestFile,
82
+ prepare: preparePytest,
83
+ args: ({ testArgument, output, plan }) =>
84
+ pytestArgs(
85
+ testArgument.startsWith("./") ? testArgument : "./" + testArgument,
86
+ plan.testCase,
87
+ output,
88
+ ),
89
+ environment: (env) => pytestEnvironment(env),
90
+ normalize: (data, exitCode, { command }) => normalizePytestEvidence(data, exitCode, command),
91
+ },
92
+ };
93
+
94
+ /** The JS adapter for a package.json script, or null for unsupported scripts. */
95
+ export function adapterForScript(command) {
96
+ const name = scriptRunner(command);
97
+ return name ? runnerAdapters[name] : null;
98
+ }
99
+
100
+ /** The adapter that owns a test file by path alone, when the path decides it. */
101
+ export function adapterForFile(path) {
102
+ return Object.values(runnerAdapters).find((a) => a.matchesFile?.(path)) ?? null;
103
+ }
@@ -0,0 +1,135 @@
1
+ // Bounded, possible call relationships; never an observed execution timeline.
2
+ const ignored = new Set(["loc", "start", "end", "tokens", "comments"]);
3
+ const children = (node) => Object.entries(node).filter(([key]) => !ignored.has(key));
4
+ const callable = (node) =>
5
+ ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].includes(node?.type);
6
+ const nameOf = (node) =>
7
+ node?.type === "Identifier"
8
+ ? node.name
9
+ : node?.type === "ThisExpression"
10
+ ? "this"
11
+ : ["MemberExpression", "OptionalMemberExpression"].includes(node?.type) && !node.computed
12
+ ? [nameOf(node.object), nameOf(node.property)].filter(Boolean).join(".")
13
+ : "";
14
+
15
+ function boundNames(node, into) {
16
+ if (!node || typeof node !== "object") return;
17
+ if (node.type === "Identifier") into.add(node.name);
18
+ else if (node.type === "ObjectPattern")
19
+ node.properties.forEach((p) => boundNames(p.value ?? p.argument, into));
20
+ else if (node.type === "ArrayPattern") node.elements.forEach((p) => boundNames(p, into));
21
+ else if (node.type === "AssignmentPattern") boundNames(node.left, into);
22
+ else if (node.type === "RestElement") boundNames(node.argument, into);
23
+ }
24
+ const shadowCache = new WeakMap();
25
+ function shadows(fn) {
26
+ if (shadowCache.has(fn)) return shadowCache.get(fn);
27
+ const names = new Set();
28
+ fn.params?.forEach((p) => boundNames(p, names));
29
+ const walk = (node) => {
30
+ if (!node || typeof node !== "object") return;
31
+ if (node.type === "VariableDeclarator") boundNames(node.id, names);
32
+ if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration")
33
+ boundNames(node.id, names);
34
+ if (callable(node)) return;
35
+ for (const [, value] of children(node))
36
+ if (Array.isArray(value)) value.forEach(walk);
37
+ else walk(value);
38
+ };
39
+ walk(fn.body);
40
+ shadowCache.set(fn, names);
41
+ return names;
42
+ }
43
+ function scope(fn, parent) {
44
+ let names;
45
+ return () => (names ??= new Set([...(parent ? parent() : []), ...shadows(fn)]));
46
+ }
47
+ export function sourceDefinitions(program) {
48
+ const definitions = new Map();
49
+ const add = (name, node) => {
50
+ if (name) definitions.set(name, definitions.has(name) ? null : callable(node) ? node : null);
51
+ };
52
+ for (const statement of program.body) {
53
+ const node = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
54
+ if (node?.type === "FunctionDeclaration") add(node.id?.name, node);
55
+ for (const d of node?.declarations ?? [])
56
+ if (d.id.type === "Identifier") add(d.id.name, d.init);
57
+ }
58
+ return definitions;
59
+ }
60
+ export function sourceFlow(handler, definitions) {
61
+ const steps = [];
62
+ const calls = new Set();
63
+ let truncated = false;
64
+ if (!callable(handler)) return { flow: { steps, truncated }, calls: [] };
65
+ const walk = (node, parentId, context, depth, active, shadowed) => {
66
+ if (!node || typeof node !== "object") return;
67
+ if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") return;
68
+ if (callable(node)) {
69
+ walk(node.body, parentId, "callback", depth, active, scope(node, shadowed));
70
+ return;
71
+ }
72
+ if (node.type === "IfStatement" || node.type === "ConditionalExpression") {
73
+ walk(node.test, parentId, context, depth, active, shadowed);
74
+ walk(node.consequent, parentId, "conditional", depth, active, shadowed);
75
+ walk(node.alternate, parentId, "conditional", depth, active, shadowed);
76
+ return;
77
+ }
78
+ if (node.type === "LogicalExpression") {
79
+ walk(node.left, parentId, context, depth, active, shadowed);
80
+ walk(node.right, parentId, "conditional", depth, active, shadowed);
81
+ return;
82
+ }
83
+ if (node.type === "SwitchCase") context = "conditional";
84
+ if (node.type === "CatchClause") {
85
+ const caught = () => {
86
+ const names = new Set(shadowed());
87
+ boundNames(node.param, names);
88
+ return names;
89
+ };
90
+ walk(node.body, parentId, "error", depth, active, caught);
91
+ return;
92
+ }
93
+ if (/^(?:For|While|DoWhile)/.test(node.type)) context = "loop";
94
+ if (["CallExpression", "OptionalCallExpression"].includes(node.type)) {
95
+ const name = nameOf(node.callee) || "Dynamic call";
96
+ if (!name.startsWith("console.")) {
97
+ if (parentId === null && calls.size < 12) calls.add(name.slice(0, 150));
98
+ if (steps.length === 12) {
99
+ truncated = true;
100
+ return;
101
+ }
102
+ const definition = node.callee.type === "Identifier" ? definitions.get(name) : null;
103
+ const target = definition && !shadowed().has(name) ? definition : null;
104
+ const recursive = !!target && active.has(target);
105
+ const step = {
106
+ id: "c" + steps.length,
107
+ parentId,
108
+ name: name.slice(0, 150),
109
+ line: node.loc?.start.line ?? 1,
110
+ ...(context ? { context } : {}),
111
+ resolution: recursive ? "recursive" : target ? "local" : "unresolved",
112
+ };
113
+ steps.push(step);
114
+ if (target && !recursive) {
115
+ if (depth === 3) truncated = true;
116
+ else
117
+ walk(
118
+ target.body,
119
+ step.id,
120
+ context,
121
+ depth + 1,
122
+ new Set([...active, target]),
123
+ scope(target),
124
+ );
125
+ }
126
+ }
127
+ }
128
+ for (const [, value] of children(node))
129
+ if (Array.isArray(value))
130
+ value.forEach((child) => walk(child, parentId, context, depth, active, shadowed));
131
+ else walk(value, parentId, context, depth, active, shadowed);
132
+ };
133
+ walk(handler.body, null, undefined, 0, new Set([handler]), scope(handler));
134
+ return { flow: { steps, truncated }, calls: [...calls] };
135
+ }