weavatrix 0.1.1 → 0.1.3
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/README.md +117 -21
- package/SECURITY.md +31 -0
- package/package.json +16 -4
- package/skill/SKILL.md +69 -12
- package/src/analysis/coverage-reports.js +14 -11
- package/src/analysis/dead-check.js +87 -6
- package/src/analysis/dep-check.js +84 -8
- package/src/analysis/dep-rules.js +74 -8
- package/src/analysis/duplicates.compute.js +215 -215
- package/src/analysis/duplicates.js +15 -15
- package/src/analysis/duplicates.run.js +52 -51
- package/src/analysis/duplicates.tokenize.js +182 -182
- package/src/analysis/endpoints.js +50 -5
- package/src/analysis/graph-analysis.aggregate.js +16 -4
- package/src/analysis/internal-audit.collect.js +154 -31
- package/src/analysis/internal-audit.reach.js +52 -11
- package/src/analysis/internal-audit.run.js +72 -21
- package/src/build-graph.js +2 -1
- package/src/child-env.js +7 -0
- package/src/graph/builder/lang-js.js +66 -23
- package/src/graph/internal-builder.build.js +48 -10
- package/src/graph/internal-builder.langs.js +49 -3
- package/src/graph/internal-builder.resolvers.js +96 -20
- package/src/mcp/catalog.mjs +10 -8
- package/src/mcp/graph-context.mjs +107 -17
- package/src/mcp/sync-payload.mjs +110 -0
- package/src/mcp/tools-actions.mjs +42 -18
- package/src/mcp/tools-graph.mjs +46 -12
- package/src/mcp/tools-health.mjs +42 -18
- package/src/mcp/tools-impact.mjs +55 -43
- package/src/mcp-rg.mjs +2 -1
- package/src/mcp-server.mjs +25 -16
- package/src/mcp-source-tools.mjs +16 -5
- package/src/process.js +4 -3
- package/src/repo-path.js +53 -0
- package/src/security/advisory-store.js +51 -7
- package/src/security/installed.js +44 -31
- package/src/security/malware-heuristics.exclusions.js +134 -134
- package/src/security/malware-heuristics.js +15 -15
- package/src/security/malware-heuristics.roots.js +142 -142
- package/src/security/malware-heuristics.scan.js +85 -85
- package/src/security/malware-heuristics.sweep.js +122 -122
|
@@ -1,51 +1,52 @@
|
|
|
1
|
-
// duplicates.run.js — the repos:duplicates entry point (split from duplicates.js): worker-thread
|
|
2
|
-
// offload with in-process fallback, cached per (repo, graph.json mtime).
|
|
3
|
-
import { existsSync, statSync } from "node:fs";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { Worker } from "node:worker_threads";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
worker.once("
|
|
22
|
-
worker.once("
|
|
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
|
-
|
|
1
|
+
// duplicates.run.js — the repos:duplicates entry point (split from duplicates.js): worker-thread
|
|
2
|
+
// offload with in-process fallback, cached per (repo, graph.json mtime).
|
|
3
|
+
import { existsSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Worker } from "node:worker_threads";
|
|
6
|
+
import { childProcessEnv } from "../child-env.js";
|
|
7
|
+
import { graphOutDirForRepo } from "../graph/layout.js";
|
|
8
|
+
import { computeDuplicates } from "./duplicates.compute.js";
|
|
9
|
+
|
|
10
|
+
function computeInWorker(repoPath, graphJsonPath) {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
let worker;
|
|
13
|
+
try {
|
|
14
|
+
worker = new Worker(new URL("./duplicates-worker.js", import.meta.url), { workerData: { repoPath, graphJsonPath }, env: childProcessEnv() });
|
|
15
|
+
} catch (e) {
|
|
16
|
+
reject(Object.assign(e, { workerStartFailed: true }));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
let settled = false;
|
|
20
|
+
const done = (fn, v) => { if (!settled) { settled = true; fn(v); } };
|
|
21
|
+
worker.once("message", (msg) => done(resolve, msg));
|
|
22
|
+
worker.once("error", (e) => done(reject, Object.assign(e, { workerStartFailed: true })));
|
|
23
|
+
worker.once("exit", (code) => { if (code !== 0) done(reject, Object.assign(new Error(`duplicates worker exited with code ${code}`), { workerStartFailed: true })); });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// repos:duplicates entry — cached per (repo, graph.json mtime): re-running with an unchanged graph is
|
|
28
|
+
// free. `force` (the UI's ↻ rescan) bypasses the cache: fragment BODIES are read from live source, so a
|
|
29
|
+
// source edit that didn't rebuild the graph (same mtime) must still be re-scanned on demand.
|
|
30
|
+
const _cache = new Map();
|
|
31
|
+
export async function runDuplicates(repoPath, force = false) {
|
|
32
|
+
const repo = String(repoPath || "");
|
|
33
|
+
if (!repo || !existsSync(repo)) return { ok: false, error: "Repo path not found" };
|
|
34
|
+
const graphJsonPath = join(graphOutDirForRepo(repo), "graph.json");
|
|
35
|
+
if (!existsSync(graphJsonPath)) {
|
|
36
|
+
return { ok: false, needsGraph: true, error: "No graph yet — build the Relations graph first (↻ on the Relations tab)" };
|
|
37
|
+
}
|
|
38
|
+
let mtime = 0;
|
|
39
|
+
try { mtime = statSync(graphJsonPath).mtimeMs; } catch { /* treat as uncached */ }
|
|
40
|
+
const cached = _cache.get(repo);
|
|
41
|
+
if (!force && cached && cached.mtime === mtime) return cached.result;
|
|
42
|
+
let result;
|
|
43
|
+
try {
|
|
44
|
+
result = await computeInWorker(repo, graphJsonPath);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (!e || !e.workerStartFailed) return { ok: false, error: e.message || String(e) };
|
|
47
|
+
try { result = computeDuplicates(repo, graphJsonPath); } // in-process fallback (exotic packaging)
|
|
48
|
+
catch (e2) { return { ok: false, error: e2.message || String(e2) }; }
|
|
49
|
+
}
|
|
50
|
+
if (result && result.ok) _cache.set(repo, { mtime, result });
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
@@ -1,182 +1,182 @@
|
|
|
1
|
-
// duplicates.tokenize.js — lexical layer of the clone detector (split from duplicates.js): comment &
|
|
2
|
-
// string stripping, body-end detection, strict/renamed tokenization, and winnowing fingerprints.
|
|
3
|
-
|
|
4
|
-
const K = 8; // k-gram length (tokens)
|
|
5
|
-
const W = 4; // winnowing window → guaranteed detection of matches ≥ K+W-1 tokens
|
|
6
|
-
const STRLIT = String.fromCharCode(0); // opaque-literal sentinel for every string/regex body: a NUL
|
|
7
|
-
// its own class (never an identifier "I" nor a number "N"), so a literal can
|
|
8
|
-
// never masquerade as code in either mode
|
|
9
|
-
|
|
10
|
-
const KEYWORDS = new Set(("if else for while do switch case break continue return function const let var new class extends async await try catch finally throw import from export default typeof instanceof in of delete void yield static get set this super null undefined true false def elif except lambda pass raise with as is not and or None True False func go defer chan map range struct interface type package nil err string int bool byte float64 public private protected final void long double boolean").split(" "));
|
|
11
|
-
|
|
12
|
-
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
13
|
-
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
14
|
-
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
15
|
-
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
16
|
-
// regex and ate the rest of the line.
|
|
17
|
-
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
18
|
-
|
|
19
|
-
// Replace comments with nothing and string/regex BODIES with the sentinel, so their contents never
|
|
20
|
-
// count as code. Handles Python triple-quoted docstrings (embedded quotes no longer desync the scan)
|
|
21
|
-
// and JS regex literals (a quote inside /['"]/ no longer opens a phantom string).
|
|
22
|
-
export function stripNonCode(text, py) {
|
|
23
|
-
let out = "", i = 0, prevSig = "";
|
|
24
|
-
const s = String(text || "");
|
|
25
|
-
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
26
|
-
while (i < s.length) {
|
|
27
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
28
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
29
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
30
|
-
i += 3;
|
|
31
|
-
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
32
|
-
i += 3; push(` ${STRLIT} `); continue;
|
|
33
|
-
}
|
|
34
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
35
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
36
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
37
|
-
i++; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
38
|
-
while (i < s.length && s[i] !== "\n") {
|
|
39
|
-
const c = s[i];
|
|
40
|
-
if (c === "\\") { i += 2; continue; }
|
|
41
|
-
if (c === "[") inClass = true;
|
|
42
|
-
else if (c === "]") inClass = false;
|
|
43
|
-
else if (c === "/" && !inClass) { i++; break; }
|
|
44
|
-
i++;
|
|
45
|
-
}
|
|
46
|
-
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
47
|
-
push(` ${STRLIT} `); continue;
|
|
48
|
-
}
|
|
49
|
-
if (ch === '"' || ch === "'" || ch === "`") {
|
|
50
|
-
const q = ch; i++;
|
|
51
|
-
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
52
|
-
i++; push(` ${STRLIT} `); continue;
|
|
53
|
-
}
|
|
54
|
-
push(ch); i++;
|
|
55
|
-
}
|
|
56
|
-
return out;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
60
|
-
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
61
|
-
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
62
|
-
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
63
|
-
// when the construct never closes, so the caller's cap stands).
|
|
64
|
-
export function bodyEndLineCount(bodyLines, py) {
|
|
65
|
-
if (py) {
|
|
66
|
-
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
67
|
-
let last = 1;
|
|
68
|
-
for (let k = 1; k < bodyLines.length; k++) {
|
|
69
|
-
const ln = bodyLines[k];
|
|
70
|
-
if (!ln.trim()) continue; // blank lines never end a block
|
|
71
|
-
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
72
|
-
last = k + 1;
|
|
73
|
-
}
|
|
74
|
-
return bodyLines.length;
|
|
75
|
-
}
|
|
76
|
-
const text = bodyLines.join("\n");
|
|
77
|
-
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
78
|
-
while (i < text.length) {
|
|
79
|
-
const ch = text[i], two = text.slice(i, i + 2);
|
|
80
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
81
|
-
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
82
|
-
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
83
|
-
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
84
|
-
i++; let inClass = false;
|
|
85
|
-
while (i < text.length && text[i] !== "\n") { const c = text[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
86
|
-
prevSig = "/"; continue;
|
|
87
|
-
}
|
|
88
|
-
if (ch === '"' || ch === "'" || ch === "`") { const q = ch; i++; while (i < text.length && text[i] !== q) { if (text[i] === "\\") i++; else if (text[i] === "\n") line++; i++; } i++; prevSig = q; continue; }
|
|
89
|
-
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
90
|
-
// depth 0 must not be read as the construct closing on line 1
|
|
91
|
-
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
92
|
-
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
93
|
-
if (ch.trim()) prevSig = ch;
|
|
94
|
-
i++;
|
|
95
|
-
}
|
|
96
|
-
return bodyLines.length;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
100
|
-
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
101
|
-
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
102
|
-
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
103
|
-
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
104
|
-
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
105
|
-
const s = String(text || "");
|
|
106
|
-
const out = [];
|
|
107
|
-
let i = 0, line = 1, prevSig = "";
|
|
108
|
-
const capture = (from, to, startLine) => {
|
|
109
|
-
const content = s.slice(from, to);
|
|
110
|
-
const nl = (content.match(/\n/g) || []).length;
|
|
111
|
-
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
112
|
-
};
|
|
113
|
-
while (i < s.length) {
|
|
114
|
-
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
115
|
-
if (ch === "\n") { line++; i++; continue; }
|
|
116
|
-
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
117
|
-
if (py && (three === "'''" || three === '"""')) {
|
|
118
|
-
const startLine = line; i += 3; const from = i;
|
|
119
|
-
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
120
|
-
capture(from, i, startLine); i += 3; continue;
|
|
121
|
-
}
|
|
122
|
-
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
123
|
-
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
124
|
-
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
125
|
-
i++; let inClass = false;
|
|
126
|
-
while (i < s.length && s[i] !== "\n") { const c = s[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
127
|
-
prevSig = "/"; continue;
|
|
128
|
-
}
|
|
129
|
-
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
130
|
-
const startLine = line; i += 2; const from = i;
|
|
131
|
-
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
132
|
-
capture(from, i, startLine); i++; continue;
|
|
133
|
-
}
|
|
134
|
-
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
135
|
-
const startLine = line; i++; const from = i;
|
|
136
|
-
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
137
|
-
capture(from, i, startLine); i++; continue;
|
|
138
|
-
}
|
|
139
|
-
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
140
|
-
const q = ch; i++;
|
|
141
|
-
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
142
|
-
if (s[i] === q) i++; continue;
|
|
143
|
-
}
|
|
144
|
-
if (ch.trim()) prevSig = ch;
|
|
145
|
-
i++;
|
|
146
|
-
}
|
|
147
|
-
return out;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
151
|
-
export function tokenize(text) {
|
|
152
|
-
const raw = text.match(/[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s\w]/g) || [];
|
|
153
|
-
const strict = [];
|
|
154
|
-
const renamed = [];
|
|
155
|
-
for (const t of raw) {
|
|
156
|
-
if (/^\d/.test(t)) { strict.push("N"); renamed.push("N"); continue; }
|
|
157
|
-
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
158
|
-
strict.push(t); renamed.push(t);
|
|
159
|
-
}
|
|
160
|
-
return { strict, renamed };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
export function fingerprints(toks) {
|
|
164
|
-
if (toks.length < K + W - 1) return new Set();
|
|
165
|
-
const hashes = [];
|
|
166
|
-
for (let i = 0; i + K <= toks.length; i++) {
|
|
167
|
-
let h = 0;
|
|
168
|
-
for (let j = i; j < i + K; j++) {
|
|
169
|
-
const s = toks[j];
|
|
170
|
-
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
171
|
-
h = (h * 131) | 0;
|
|
172
|
-
}
|
|
173
|
-
hashes.push(h >>> 0);
|
|
174
|
-
}
|
|
175
|
-
const fp = new Set();
|
|
176
|
-
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
177
|
-
let min = Infinity;
|
|
178
|
-
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
179
|
-
fp.add(min);
|
|
180
|
-
}
|
|
181
|
-
return fp;
|
|
182
|
-
}
|
|
1
|
+
// duplicates.tokenize.js — lexical layer of the clone detector (split from duplicates.js): comment &
|
|
2
|
+
// string stripping, body-end detection, strict/renamed tokenization, and winnowing fingerprints.
|
|
3
|
+
|
|
4
|
+
const K = 8; // k-gram length (tokens)
|
|
5
|
+
const W = 4; // winnowing window → guaranteed detection of matches ≥ K+W-1 tokens
|
|
6
|
+
const STRLIT = String.fromCharCode(0); // opaque-literal sentinel for every string/regex body: a NUL
|
|
7
|
+
// its own class (never an identifier "I" nor a number "N"), so a literal can
|
|
8
|
+
// never masquerade as code in either mode
|
|
9
|
+
|
|
10
|
+
const KEYWORDS = new Set(("if else for while do switch case break continue return function const let var new class extends async await try catch finally throw import from export default typeof instanceof in of delete void yield static get set this super null undefined true false def elif except lambda pass raise with as is not and or None True False func go defer chan map range struct interface type package nil err string int bool byte float64 public private protected final void long double boolean").split(" "));
|
|
11
|
+
|
|
12
|
+
// A leading `/` is a REGEX literal (not division) when the previous significant char is one of these
|
|
13
|
+
// or the fragment start; after a word char / ) / ] it is division. Covers .match(/…/), = /…/, (/…/),
|
|
14
|
+
// and arrow `x => /…/`. NOTE: `+` and `-` are deliberately EXCLUDED — a regex never legitimately
|
|
15
|
+
// follows them, but `i++ / 2` and `a - b / c` do, and including them mis-scanned the division as a
|
|
16
|
+
// regex and ate the rest of the line.
|
|
17
|
+
const REGEX_PREV = new Set("(,=:[!&|?{};~*%^<>".split(""));
|
|
18
|
+
|
|
19
|
+
// Replace comments with nothing and string/regex BODIES with the sentinel, so their contents never
|
|
20
|
+
// count as code. Handles Python triple-quoted docstrings (embedded quotes no longer desync the scan)
|
|
21
|
+
// and JS regex literals (a quote inside /['"]/ no longer opens a phantom string).
|
|
22
|
+
export function stripNonCode(text, py) {
|
|
23
|
+
let out = "", i = 0, prevSig = "";
|
|
24
|
+
const s = String(text || "");
|
|
25
|
+
const push = (c) => { out += c; const t = c.trim(); if (t) prevSig = t[t.length - 1]; };
|
|
26
|
+
while (i < s.length) {
|
|
27
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
28
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
29
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
30
|
+
i += 3;
|
|
31
|
+
while (i < s.length && s.slice(i, i + 3) !== three) i++;
|
|
32
|
+
i += 3; push(` ${STRLIT} `); continue;
|
|
33
|
+
}
|
|
34
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
35
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") i++; i += 2; continue; }
|
|
36
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
37
|
+
i++; let inClass = false; // '/' inside a [...] char class is literal, not the terminator
|
|
38
|
+
while (i < s.length && s[i] !== "\n") {
|
|
39
|
+
const c = s[i];
|
|
40
|
+
if (c === "\\") { i += 2; continue; }
|
|
41
|
+
if (c === "[") inClass = true;
|
|
42
|
+
else if (c === "]") inClass = false;
|
|
43
|
+
else if (c === "/" && !inClass) { i++; break; }
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
while (i < s.length && /[a-z]/i.test(s[i])) i++; // regex flags (gimsuy)
|
|
47
|
+
push(` ${STRLIT} `); continue;
|
|
48
|
+
}
|
|
49
|
+
if (ch === '"' || ch === "'" || ch === "`") {
|
|
50
|
+
const q = ch; i++;
|
|
51
|
+
while (i < s.length && s[i] !== q) { if (s[i] === "\\") i++; i++; }
|
|
52
|
+
i++; push(` ${STRLIT} `); continue;
|
|
53
|
+
}
|
|
54
|
+
push(ch); i++;
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Where a symbol's body ends — so the LAST symbol in a file doesn't swallow trailing module-level code
|
|
60
|
+
// (module.exports tables, main() calls, handler registrations) up to EOF and dilute/misattribute
|
|
61
|
+
// clones. Brace/bracket depth for brace langs (body ends when {}()[] balance after first opening);
|
|
62
|
+
// indentation for Python. Returns a 1-based line count within bodyLines (≤ its length; = its length
|
|
63
|
+
// when the construct never closes, so the caller's cap stands).
|
|
64
|
+
export function bodyEndLineCount(bodyLines, py) {
|
|
65
|
+
if (py) {
|
|
66
|
+
const base = bodyLines[0].match(/^[ \t]*/)[0].length;
|
|
67
|
+
let last = 1;
|
|
68
|
+
for (let k = 1; k < bodyLines.length; k++) {
|
|
69
|
+
const ln = bodyLines[k];
|
|
70
|
+
if (!ln.trim()) continue; // blank lines never end a block
|
|
71
|
+
if (ln.match(/^[ \t]*/)[0].length <= base) return last; // dedent to ≤ the def → body ended above
|
|
72
|
+
last = k + 1;
|
|
73
|
+
}
|
|
74
|
+
return bodyLines.length;
|
|
75
|
+
}
|
|
76
|
+
const text = bodyLines.join("\n");
|
|
77
|
+
let depth = 0, opened = false, i = 0, line = 1, prevSig = "";
|
|
78
|
+
while (i < text.length) {
|
|
79
|
+
const ch = text[i], two = text.slice(i, i + 2);
|
|
80
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
81
|
+
if (two === "//") { while (i < text.length && text[i] !== "\n") i++; continue; }
|
|
82
|
+
if (two === "/*") { i += 2; while (i < text.length && text.slice(i, i + 2) !== "*/") { if (text[i] === "\n") line++; i++; } i += 2; continue; }
|
|
83
|
+
if (ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
84
|
+
i++; let inClass = false;
|
|
85
|
+
while (i < text.length && text[i] !== "\n") { const c = text[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
86
|
+
prevSig = "/"; continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '"' || ch === "'" || ch === "`") { const q = ch; i++; while (i < text.length && text[i] !== q) { if (text[i] === "\\") i++; else if (text[i] === "\n") line++; i++; } i++; prevSig = q; continue; }
|
|
89
|
+
// depth tracks all brackets, but only a { or [ opens the BODY — a bare (param list) returning to
|
|
90
|
+
// depth 0 must not be read as the construct closing on line 1
|
|
91
|
+
if (ch === "{" || ch === "(" || ch === "[") { depth++; if (ch === "{" || ch === "[") opened = true; }
|
|
92
|
+
else if (ch === "}" || ch === ")" || ch === "]") { depth--; if (opened && depth <= 0) return line; }
|
|
93
|
+
if (ch.trim()) prevSig = ch;
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
return bodyLines.length;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Large multi-line string literals — the OPPOSITE selection to stripNonCode: everything the code
|
|
100
|
+
// scan throws away. Embedded DSLs (inline C#/SQL/PowerShell templates) are invisible to the normal
|
|
101
|
+
// clone pass because their bodies are stripped; this extractor feeds them back in as their own
|
|
102
|
+
// fragments when the caller opts in (find_duplicates include_strings). Comment/regex handling
|
|
103
|
+
// mirrors stripNonCode so a quote inside a comment never opens a phantom literal.
|
|
104
|
+
export function extractLargeStrings(text, { py = false, cs = false, minLines = 6 } = {}) {
|
|
105
|
+
const s = String(text || "");
|
|
106
|
+
const out = [];
|
|
107
|
+
let i = 0, line = 1, prevSig = "";
|
|
108
|
+
const capture = (from, to, startLine) => {
|
|
109
|
+
const content = s.slice(from, to);
|
|
110
|
+
const nl = (content.match(/\n/g) || []).length;
|
|
111
|
+
if (nl + 1 >= minLines) out.push({ start: startLine, end: startLine + nl, content });
|
|
112
|
+
};
|
|
113
|
+
while (i < s.length) {
|
|
114
|
+
const ch = s[i], two = s.slice(i, i + 2), three = s.slice(i, i + 3);
|
|
115
|
+
if (ch === "\n") { line++; i++; continue; }
|
|
116
|
+
if (py && ch === "#") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
117
|
+
if (py && (three === "'''" || three === '"""')) {
|
|
118
|
+
const startLine = line; i += 3; const from = i;
|
|
119
|
+
while (i < s.length && s.slice(i, i + 3) !== three) { if (s[i] === "\n") line++; i++; }
|
|
120
|
+
capture(from, i, startLine); i += 3; continue;
|
|
121
|
+
}
|
|
122
|
+
if (!py && two === "//") { while (i < s.length && s[i] !== "\n") i++; continue; }
|
|
123
|
+
if (!py && two === "/*") { i += 2; while (i < s.length && s.slice(i, i + 2) !== "*/") { if (s[i] === "\n") line++; i++; } i += 2; continue; }
|
|
124
|
+
if (!py && ch === "/" && REGEX_PREV.has(prevSig)) {
|
|
125
|
+
i++; let inClass = false;
|
|
126
|
+
while (i < s.length && s[i] !== "\n") { const c = s[i]; if (c === "\\") { i += 2; continue; } if (c === "[") inClass = true; else if (c === "]") inClass = false; else if (c === "/" && !inClass) { i++; break; } i++; }
|
|
127
|
+
prevSig = "/"; continue;
|
|
128
|
+
}
|
|
129
|
+
if (cs && two === '@"') { // C# verbatim string; "" is the escaped quote
|
|
130
|
+
const startLine = line; i += 2; const from = i;
|
|
131
|
+
while (i < s.length) { if (s.slice(i, i + 2) === '""') { i += 2; continue; } if (s[i] === '"') break; if (s[i] === "\n") line++; i++; }
|
|
132
|
+
capture(from, i, startLine); i++; continue;
|
|
133
|
+
}
|
|
134
|
+
if (!py && ch === "`") { // JS/TS template literal — the main multi-line carrier
|
|
135
|
+
const startLine = line; i++; const from = i;
|
|
136
|
+
while (i < s.length && s[i] !== "`") { if (s[i] === "\\") { i++; if (s[i] === "\n") line++; i++; continue; } if (s[i] === "\n") line++; i++; }
|
|
137
|
+
capture(from, i, startLine); i++; continue;
|
|
138
|
+
}
|
|
139
|
+
if (ch === '"' || ch === "'") { // single-line strings can't span minLines — just skip past
|
|
140
|
+
const q = ch; i++;
|
|
141
|
+
while (i < s.length && s[i] !== q && s[i] !== "\n") { if (s[i] === "\\") i++; i++; }
|
|
142
|
+
if (s[i] === q) i++; continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch.trim()) prevSig = ch;
|
|
145
|
+
i++;
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// one raw token stream; the two modes differ only in identifier canonicalization
|
|
151
|
+
export function tokenize(text) {
|
|
152
|
+
const raw = text.match(/[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|[^\s\w]/g) || [];
|
|
153
|
+
const strict = [];
|
|
154
|
+
const renamed = [];
|
|
155
|
+
for (const t of raw) {
|
|
156
|
+
if (/^\d/.test(t)) { strict.push("N"); renamed.push("N"); continue; }
|
|
157
|
+
if (/^[A-Za-z_$]/.test(t) && !KEYWORDS.has(t)) { strict.push(t); renamed.push("I"); continue; }
|
|
158
|
+
strict.push(t); renamed.push(t);
|
|
159
|
+
}
|
|
160
|
+
return { strict, renamed };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function fingerprints(toks) {
|
|
164
|
+
if (toks.length < K + W - 1) return new Set();
|
|
165
|
+
const hashes = [];
|
|
166
|
+
for (let i = 0; i + K <= toks.length; i++) {
|
|
167
|
+
let h = 0;
|
|
168
|
+
for (let j = i; j < i + K; j++) {
|
|
169
|
+
const s = toks[j];
|
|
170
|
+
for (let c = 0; c < s.length; c++) h = (h * 31 + s.charCodeAt(c)) | 0;
|
|
171
|
+
h = (h * 131) | 0;
|
|
172
|
+
}
|
|
173
|
+
hashes.push(h >>> 0);
|
|
174
|
+
}
|
|
175
|
+
const fp = new Set();
|
|
176
|
+
for (let i = 0; i + W <= hashes.length + 1; i++) {
|
|
177
|
+
let min = Infinity;
|
|
178
|
+
for (let j = i; j < Math.min(i + W, hashes.length); j++) if (hashes[j] < min) min = hashes[j];
|
|
179
|
+
fp.add(min);
|
|
180
|
+
}
|
|
181
|
+
return fp;
|
|
182
|
+
}
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
// • method-call routes (Express/Fastify/Koa/Hono/gin/echo): app.get("/path", handler)
|
|
7
7
|
// • decorators (FastAPI/Flask/NestJS): @app.get("/path") / @Get("/path")
|
|
8
8
|
// • Go net/http: mux.HandleFunc("/path", handler)
|
|
9
|
-
import { join } from "node:path";
|
|
10
9
|
import { safeRead } from "../util.js";
|
|
10
|
+
import { createRepoBoundary } from "../repo-path.js";
|
|
11
11
|
|
|
12
12
|
const MAX_FILES = 3000;
|
|
13
13
|
const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ALL", "ANY"]);
|
|
@@ -44,9 +44,27 @@ function handlerName(expr) {
|
|
|
44
44
|
// endpoints (handler "operation", {id} params). These keys never appear in a real route/handler table.
|
|
45
45
|
const OPENAPI_BLOCK = /\boperationId\b|\bresponses\s*:|\brequestBody\b|\bschemaRef\b|\boperation\s*\(|\bsummary\s*:/;
|
|
46
46
|
|
|
47
|
-
const looksLikePath = (p) => typeof p === "string" && /^\/[\w\-./:{}
|
|
47
|
+
const looksLikePath = (p) => typeof p === "string" && /^\/[\w\-./:{}*$?]*$/.test(p) && !p.includes("://");
|
|
48
48
|
const cleanPath = (p) => String(p || "").replace(/\/+$/, "") || "/";
|
|
49
49
|
|
|
50
|
+
export function nextRoutePath(file) {
|
|
51
|
+
const parts = String(file || "").replace(/\\/g, "/").split("/").filter(Boolean);
|
|
52
|
+
if (!/^route\.[cm]?[jt]s$/i.test(parts.at(-1) || "")) return "";
|
|
53
|
+
const appAt = parts.lastIndexOf("app");
|
|
54
|
+
if (appAt < 0) return "";
|
|
55
|
+
const route = [];
|
|
56
|
+
for (let segment of parts.slice(appAt + 1, -1)) {
|
|
57
|
+
if (!segment || /^\([^)]*\)$/.test(segment) || segment.startsWith("@")) continue; // route groups / parallel slots
|
|
58
|
+
segment = segment.replace(/^\((?:\.{1,3})\)/, ""); // intercepting-route marker
|
|
59
|
+
let m;
|
|
60
|
+
if ((m = /^\[\[\.\.\.([^\]]+)\]\]$/.exec(segment))) segment = `*${m[1]}?`;
|
|
61
|
+
else if ((m = /^\[\.\.\.([^\]]+)\]$/.exec(segment))) segment = `*${m[1]}`;
|
|
62
|
+
else if ((m = /^\[([^\]]+)\]$/.exec(segment))) segment = `:${m[1]}`;
|
|
63
|
+
if (segment) route.push(segment);
|
|
64
|
+
}
|
|
65
|
+
return `/${route.join("/")}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
50
68
|
export function extractEndpointsFromText(text, file) {
|
|
51
69
|
const out = [];
|
|
52
70
|
const py = /\.py$/i.test(file);
|
|
@@ -58,6 +76,31 @@ export function extractEndpointsFromText(text, file) {
|
|
|
58
76
|
out.push({ method: m, path: p, handler: handlerName(expr), file, line: lineAt(text, idx) });
|
|
59
77
|
};
|
|
60
78
|
|
|
79
|
+
// Next.js App Router: the filesystem provides the path and exported HTTP-method functions provide the
|
|
80
|
+
// verbs. No literal route string exists in route.ts, so generic Express/FastAPI regexes cannot see it.
|
|
81
|
+
const nextPath = nextRoutePath(file);
|
|
82
|
+
if (nextPath) {
|
|
83
|
+
const seen = new Set();
|
|
84
|
+
const direct = /\bexport\s+(?:(?:async|declare)\s+)*(?:function\s+|(?:const|let|var)\s+)(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
|
|
85
|
+
let nm;
|
|
86
|
+
while ((nm = direct.exec(text))) {
|
|
87
|
+
const method = nm[1].toUpperCase();
|
|
88
|
+
if (!seen.has(method)) { seen.add(method); add(method, nextPath, method, nm.index); }
|
|
89
|
+
}
|
|
90
|
+
const lists = /\bexport\s*\{([^}]+)\}/g;
|
|
91
|
+
let lm;
|
|
92
|
+
while ((lm = lists.exec(text))) {
|
|
93
|
+
for (const item of lm[1].split(",")) {
|
|
94
|
+
const mm = /^\s*([A-Za-z_$][\w$]*)(?:\s+as\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS))?\s*$/.exec(item);
|
|
95
|
+
if (!mm) continue;
|
|
96
|
+
if (!mm[2] && !HTTP_METHODS.has(mm[1])) continue;
|
|
97
|
+
const method = String(mm[2] || mm[1]).toUpperCase();
|
|
98
|
+
if (!HTTP_METHODS.has(method)) continue;
|
|
99
|
+
if (!seen.has(method)) { seen.add(method); add(method, nextPath, mm[1], lm.index); }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
61
104
|
// ---- object routes: "/path": { GET: fn, POST: fn2 } or "/path": handler --------------------
|
|
62
105
|
// find each "…": { or "…": expr, where the key looks like a path
|
|
63
106
|
const objKeyRe = /(["'`])(\/[^"'`]*)\1\s*:\s*(\{)?/g;
|
|
@@ -125,12 +168,14 @@ const normParamKey = (p) => String(p).replace(/\{([^/}]+)\}/g, ":$1");
|
|
|
125
168
|
export function detectEndpoints(repoPath, codeFiles) {
|
|
126
169
|
const files = (codeFiles || []).slice(0, MAX_FILES);
|
|
127
170
|
const byKey = new Map();
|
|
171
|
+
const boundary = createRepoBoundary(repoPath);
|
|
128
172
|
for (const f of files) {
|
|
129
173
|
const rel = f.path || f;
|
|
130
|
-
const full = f.full || join(repoPath, rel);
|
|
131
174
|
if (!/\.(js|ts|tsx|jsx|cjs|mjs|py|go)$/i.test(rel)) continue;
|
|
132
|
-
const
|
|
133
|
-
if (!
|
|
175
|
+
const resolved = boundary.resolve(rel);
|
|
176
|
+
if (!resolved.ok) continue;
|
|
177
|
+
const text = safeRead(resolved.path);
|
|
178
|
+
if (!text || (!nextRoutePath(rel) && !/["'`]\/|\.(get|post|put|patch|delete)\s*\(|HandleFunc|@\w*\.?(get|post|put|patch|delete)/i.test(text))) continue;
|
|
134
179
|
for (const e of extractEndpointsFromText(text, rel.replace(/\\/g, "/"))) {
|
|
135
180
|
const key = `${e.method} ${normParamKey(e.path)}`;
|
|
136
181
|
const prev = byKey.get(key);
|