@skillstech/thunderlang 0.5.10 → 0.5.12
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/CHANGELOG.md +450 -0
- package/dist/core.cjs +30434 -7577
- package/dist/index.cjs +28576 -5328
- package/dist/learn.cjs +24201 -5367
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +49 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +65 -14
- package/src/model.mjs +496 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1017 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
package/src/system.mjs
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
// The whole system: calls across files and services. Browser-safe, zero dependencies.
|
|
2
|
+
//
|
|
3
|
+
// After every file is read into the model, each step's call (from its meaning tree, `expr`) is followed through the
|
|
4
|
+
// file's imports to the member it calls in another file: JS/TS ES modules and CommonJS, Python imports (relative
|
|
5
|
+
// too), Go packages (and other files of the same package), Java/Kotlin/C#/PHP imports by class, Ruby constants, and
|
|
6
|
+
// Rust `use crate::…` paths. A step that sends an HTTP request the library catalog recognizes ("Sends a POST request
|
|
7
|
+
// to /api/orders/…") is linked to the route in this repo that handles that method and path; an event or queue
|
|
8
|
+
// message is linked to the code that listens for the same name.
|
|
9
|
+
//
|
|
10
|
+
// Never a guess: a call is linked only when the import (or the declared type, or a unique class name where the
|
|
11
|
+
// language makes class names global) says exactly which member it is. Everything else stays unlinked, and what was
|
|
12
|
+
// worth linking but could not be is listed in `model.notLinked` with the reason (dynamic import, computed URL,
|
|
13
|
+
// external package, two routes match, an interface whose implementation is chosen when it runs).
|
|
14
|
+
|
|
15
|
+
const JS = new Set(['typescript', 'javascript']);
|
|
16
|
+
const JVM = new Set(['java', 'kotlin']);
|
|
17
|
+
const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
|
|
18
|
+
const join = (...parts) => {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const seg of parts.join('/').split('/')) {
|
|
21
|
+
if (!seg || seg === '.') continue;
|
|
22
|
+
if (seg === '..') { if (out.length && out.at(-1) !== '..') out.pop(); else out.push('..'); } else out.push(seg);
|
|
23
|
+
}
|
|
24
|
+
return out.join('/');
|
|
25
|
+
};
|
|
26
|
+
const stripStrings = (s) => s.replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`/g, (m) => m.replace(/[^\n]/g, ' '));
|
|
27
|
+
const lineAt = (src, idx) => { let n = 1; for (let i = src.indexOf('\n'); i >= 0 && i < idx; i = src.indexOf('\n', i + 1)) n++; return n; };
|
|
28
|
+
|
|
29
|
+
// ── The calls in a step: callee paths from its meaning tree ──────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
/** `a.b.c` -> ['a', 'b', 'c']; null when the callee is not a plain path (a call's result, an index). */
|
|
32
|
+
export function calleePath(e) {
|
|
33
|
+
if (!e) return null;
|
|
34
|
+
if (e.kind === 'name') return [e.name];
|
|
35
|
+
if (e.kind === 'member') { const o = calleePath(e.object); return o ? [...o, e.property] : null; }
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every call in an expression, outside the bodies of functions written in it (those are their own steps). */
|
|
40
|
+
export function callsIn(expr, out = []) {
|
|
41
|
+
if (!expr || typeof expr !== 'object') return out;
|
|
42
|
+
if (Array.isArray(expr)) { for (const x of expr) callsIn(x, out); return out; }
|
|
43
|
+
if (expr.kind === 'block' || expr.kind === 'function' || (expr.kind === 'lambda' && expr.body?.kind === 'block')) return out;
|
|
44
|
+
if (expr.kind === 'call') out.push(expr);
|
|
45
|
+
for (const k in expr) { const v = expr[k]; if (v && typeof v === 'object' && k !== 'kind') callsIn(v, out); }
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── Imports, per language ────────────────────────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
/** A binding: a local name bound to a module (files) and, optionally, one symbol in it. */
|
|
52
|
+
const bind = (files, symbol = null, extra = {}) => ({ files, symbol, ...extra });
|
|
53
|
+
|
|
54
|
+
function jsImports(src, file, ctx, out) {
|
|
55
|
+
const clean = stripComments(src);
|
|
56
|
+
const resolve = (spec) => ctx.jsFile(file, spec);
|
|
57
|
+
const add = (local, spec, symbol, line) => {
|
|
58
|
+
const r = resolve(spec);
|
|
59
|
+
if (r.file) out.bindings.set(local, bind([r.file], symbol, { line, spec }));
|
|
60
|
+
else out.unresolved.push({ file, line, import: spec, why: r.why });
|
|
61
|
+
};
|
|
62
|
+
for (const m of clean.matchAll(/\bimport\s+(?:type\s+)?([\w$*{}\s,]+?)\s+from\s+(['"])([^'"]+)\2/g)) {
|
|
63
|
+
const line = lineAt(clean, m.index);
|
|
64
|
+
let clause = m[1].trim();
|
|
65
|
+
const named = clause.match(/\{([^}]*)\}/);
|
|
66
|
+
if (named) {
|
|
67
|
+
for (const part of named[1].split(',')) {
|
|
68
|
+
const p = part.trim().replace(/^type\s+/, '').match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);
|
|
69
|
+
if (p) add(p[2] || p[1], m[3], p[1], line);
|
|
70
|
+
}
|
|
71
|
+
clause = clause.replace(named[0], '').replace(/,\s*$/, '').replace(/^\s*,/, '').trim();
|
|
72
|
+
}
|
|
73
|
+
const ns = clause.match(/\*\s+as\s+([\w$]+)/);
|
|
74
|
+
if (ns) { add(ns[1], m[3], null, line); clause = clause.replace(ns[0], '').replace(/,/g, '').trim(); }
|
|
75
|
+
if (/^[\w$]+$/.test(clause)) add(clause, m[3], 'default', line);
|
|
76
|
+
}
|
|
77
|
+
for (const m of clean.matchAll(/\b(?:const|let|var)\s+([\w$]+)\s*=\s*require\(\s*(['"])([^'"]+)\2\s*\)(?:\s*\.\s*([\w$]+))?/g)) add(m[1], m[3], m[4] ?? 'module.exports', lineAt(clean, m.index));
|
|
78
|
+
for (const m of clean.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*(['"])([^'"]+)\2\s*\)/g)) {
|
|
79
|
+
for (const part of m[1].split(',')) { const p = part.trim().match(/^([\w$]+)(?:\s*:\s*([\w$]+))?$/); if (p) add(p[2] || p[1], m[3], p[1], lineAt(clean, m.index)); }
|
|
80
|
+
}
|
|
81
|
+
for (const m of clean.matchAll(/\b(?:import|require)\s*\(\s*([^'"`\s)][^)]*)\)/g)) {
|
|
82
|
+
if (/^\s*$/.test(m[1])) continue;
|
|
83
|
+
out.unresolved.push({ file, line: lineAt(clean, m.index), import: m[1].trim().slice(0, 60), why: 'dynamic import: the module is worked out when it runs' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:\\])\/\/.*$/gm, '$1');
|
|
87
|
+
|
|
88
|
+
/** A JS/TS file's exports: default (a local name), named (exported -> local), and re-exports. */
|
|
89
|
+
function jsExports(src) {
|
|
90
|
+
const clean = stripComments(src);
|
|
91
|
+
const named = new Map(), re = [];
|
|
92
|
+
let def = null;
|
|
93
|
+
let m;
|
|
94
|
+
if ((m = clean.match(/\bexport\s+default\s+(?:async\s+)?(?:function\s*\*?\s*|class\s+)?([\w$]+)/))) def = m[1];
|
|
95
|
+
if ((m = clean.match(/\bmodule\.exports\s*=\s*([\w$]+)\s*;?\s*(?:\n|$)/))) def = m[1];
|
|
96
|
+
if ((m = clean.match(/\bmodule\.exports\s*=\s*\{([^}]*)\}/))) for (const part of m[1].split(',')) { const p = part.trim().match(/^([\w$]+)(?:\s*:\s*([\w$]+))?/); if (p) named.set(p[1], p[2] || p[1]); }
|
|
97
|
+
for (const x of clean.matchAll(/\bexport\s*\{([^}]*)\}(?:\s*from\s*(['"])([^'"]+)\2)?/g)) {
|
|
98
|
+
const names = new Map();
|
|
99
|
+
for (const part of x[1].split(',')) { const p = part.trim().replace(/^type\s+/, '').match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/); if (p) names.set(p[2] || p[1], p[1]); }
|
|
100
|
+
if (x[3]) re.push({ spec: x[3], names }); else for (const [k, v] of names) named.set(k, v);
|
|
101
|
+
}
|
|
102
|
+
for (const x of clean.matchAll(/\bexport\s*\*\s*(?:as\s+([\w$]+)\s+)?from\s*(['"])([^'"]+)\2/g)) re.push({ spec: x[3], all: !x[1], as: x[1] });
|
|
103
|
+
return { def, named, re };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function pythonImports(src, file, ctx, out) {
|
|
107
|
+
const lines = src.split('\n');
|
|
108
|
+
for (let i = 0; i < lines.length; i++) {
|
|
109
|
+
const l = lines[i].replace(/#.*$/, '');
|
|
110
|
+
let m;
|
|
111
|
+
if ((m = l.match(/^\s*import\s+(.+)$/))) {
|
|
112
|
+
for (const part of m[1].split(',')) {
|
|
113
|
+
const p = part.trim().match(/^([\w.]+)(?:\s+as\s+(\w+))?$/);
|
|
114
|
+
if (!p) continue;
|
|
115
|
+
const r = ctx.pyModule(file, p[1]);
|
|
116
|
+
// `import a.b.c` binds `a.b.c` (used as a.b.c.f); `import a.b as x` binds x.
|
|
117
|
+
if (r.files) out.bindings.set(p[2] || p[1], bind(r.files, null, { line: i + 1, spec: p[1] }));
|
|
118
|
+
else out.unresolved.push({ file, line: i + 1, import: p[1], why: r.why });
|
|
119
|
+
}
|
|
120
|
+
} else if ((m = l.match(/^\s*from\s+(\.*)([\w.]*)\s+import\s+(.+)$/))) {
|
|
121
|
+
let names = m[3].trim();
|
|
122
|
+
if (names.startsWith('(') && !names.includes(')')) { for (let j = i + 1; j < lines.length; j++) { names += ' ' + lines[j].replace(/#.*$/, ''); if (lines[j].includes(')')) { i = j; break; } } }
|
|
123
|
+
names = names.replace(/[()\\]/g, ' ');
|
|
124
|
+
const spec = m[1] + m[2];
|
|
125
|
+
const r = ctx.pyModule(file, spec);
|
|
126
|
+
for (const part of names.split(',')) {
|
|
127
|
+
const p = part.trim().match(/^(\*|\w+)(?:\s+as\s+(\w+))?$/);
|
|
128
|
+
if (!p) continue;
|
|
129
|
+
if (p[1] === '*') { if (r.files) out.star.push(r.files); continue; }
|
|
130
|
+
// `from pkg import name`: a name in pkg/__init__.py, or the submodule pkg/name.py.
|
|
131
|
+
const sub = ctx.pyModule(file, `${spec}${spec.endsWith('.') || !spec ? '' : '.'}${p[1]}`);
|
|
132
|
+
if (r.files && ctx.hasSymbol(r.files, p[1])) out.bindings.set(p[2] || p[1], bind(r.files, p[1], { line: i + 1, spec }));
|
|
133
|
+
else if (sub.files) out.bindings.set(p[2] || p[1], bind(sub.files, null, { line: i + 1, spec: `${spec}.${p[1]}` }));
|
|
134
|
+
else if (r.files) out.bindings.set(p[2] || p[1], bind(r.files, p[1], { line: i + 1, spec }));
|
|
135
|
+
else { out.unresolved.push({ file, line: i + 1, import: spec || '.', why: r.why }); break; }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function goImports(src, file, ctx, out) {
|
|
142
|
+
const block = [...src.matchAll(/^\s*import\s*\(([\s\S]*?)\)/gm)].map((m) => ({ text: m[1], at: m.index }));
|
|
143
|
+
const singles = [...src.matchAll(/^\s*import\s+((?:[\w.]+\s+)?"[^"]+")/gm)].map((m) => ({ text: m[1], at: m.index }));
|
|
144
|
+
for (const b of [...block, ...singles]) {
|
|
145
|
+
for (const m of b.text.matchAll(/(?:^|\n)\s*([\w.]+\s+)?"([^"]+)"/g)) {
|
|
146
|
+
const alias = m[1]?.trim();
|
|
147
|
+
const r = ctx.goPackage(m[2]);
|
|
148
|
+
const line = lineAt(src, b.at);
|
|
149
|
+
if (!r.files) { out.unresolved.push({ file, line, import: m[2], why: r.why }); continue; }
|
|
150
|
+
if (alias === '_') continue;
|
|
151
|
+
if (alias === '.') { out.star.push(r.files); continue; }
|
|
152
|
+
out.bindings.set(alias || r.name, bind(r.files, null, { line, spec: m[2] }));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function jvmImports(src, file, ctx, out, language) {
|
|
158
|
+
for (const m of src.matchAll(/^\s*import\s+(static\s+)?([\w.]+)(\.\*)?\s*(?:as\s+(\w+))?\s*;?\s*$/gm)) {
|
|
159
|
+
const line = lineAt(src, m.index);
|
|
160
|
+
const parts = m[2].split('.');
|
|
161
|
+
if (m[3]) { out.packages.push(m[2]); continue; }
|
|
162
|
+
if (m[1]) {
|
|
163
|
+
// `import static a.b.C.m`: m is C's member.
|
|
164
|
+
const cls = parts.at(-2), pkg = parts.slice(0, -2).join('.');
|
|
165
|
+
const t = ctx.classIn(pkg, cls, language);
|
|
166
|
+
if (t.thing) out.bindings.set(m[4] || parts.at(-1), bind([t.thing.file], parts.at(-1), { line, spec: m[2], thing: t.thing }));
|
|
167
|
+
else out.unresolved.push({ file, line, import: m[2], why: t.why });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const name = parts.at(-1), pkg = parts.slice(0, -1).join('.');
|
|
171
|
+
const t = ctx.classIn(pkg, name, language);
|
|
172
|
+
if (t.thing) out.bindings.set(m[4] || name, bind([t.thing.file], name, { line, spec: m[2], thing: t.thing }));
|
|
173
|
+
else if (language === 'kotlin' && ctx.pkgFiles(pkg).length) out.bindings.set(m[4] || name, bind(ctx.pkgFiles(pkg), name, { line, spec: m[2] }));
|
|
174
|
+
else out.unresolved.push({ file, line, import: m[2], why: t.why });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function csharpImports(src, file, ctx, out) {
|
|
179
|
+
for (const m of src.matchAll(/^\s*(?:global\s+)?using\s+(?:static\s+)?(?:(\w+)\s*=\s*)?([\w.]+)\s*;/gm)) {
|
|
180
|
+
if (m[1]) { const parts = m[2].split('.'); const t = ctx.classIn(parts.slice(0, -1).join('.'), parts.at(-1), 'csharp'); if (t.thing) out.bindings.set(m[1], bind([t.thing.file], parts.at(-1), { thing: t.thing, line: lineAt(src, m.index) })); continue; }
|
|
181
|
+
out.packages.push(m[2]);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function phpImports(src, file, ctx, out) {
|
|
186
|
+
for (const m of src.matchAll(/^\s*use\s+([\w\\]+)(?:\s+as\s+(\w+))?\s*;/gm)) {
|
|
187
|
+
const parts = m[1].replace(/^\\/, '').split('\\');
|
|
188
|
+
const t = ctx.classIn(parts.slice(0, -1).join('\\'), parts.at(-1), 'php');
|
|
189
|
+
if (t.thing) out.bindings.set(m[2] || parts.at(-1), bind([t.thing.file], parts.at(-1), { thing: t.thing, line: lineAt(src, m.index) }));
|
|
190
|
+
else out.unresolved.push({ file, line: lineAt(src, m.index), import: m[1], why: t.why });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function rustImports(src, file, ctx, out) {
|
|
195
|
+
for (const m of src.matchAll(/^\s*(?:pub\s+)?use\s+((?:crate|super|self)(?:::\w+)*)(?:::\{([^}]*)\}|::(\w+)(?:\s+as\s+(\w+))?)?\s*;/gm)) {
|
|
196
|
+
const line = lineAt(src, m.index);
|
|
197
|
+
const names = m[2] ? m[2].split(',').map((x) => x.trim().match(/^(\w+)(?:\s+as\s+(\w+))?$/)).filter(Boolean).map((x) => [x[1], x[2] || x[1]]) : m[3] ? [[m[3], m[4] || m[3]]] : [];
|
|
198
|
+
for (const [name, local] of names) {
|
|
199
|
+
const asMod = ctx.rustModule(file, `${m[1]}::${name}`);
|
|
200
|
+
if (asMod.files) { out.bindings.set(local, bind(asMod.files, null, { line })); continue; }
|
|
201
|
+
const r = ctx.rustModule(file, m[1]);
|
|
202
|
+
if (r.files) out.bindings.set(local, bind(r.files, name, { line }));
|
|
203
|
+
else out.unresolved.push({ file, line, import: `${m[1]}::${name}`, why: r.why });
|
|
204
|
+
}
|
|
205
|
+
if (!names.length) {
|
|
206
|
+
// `use crate::orders;` (a module) or `use crate::orders::place;` (an item in one).
|
|
207
|
+
const segs = m[1].split('::');
|
|
208
|
+
const r = ctx.rustModule(file, m[1]);
|
|
209
|
+
if (r.files?.length) { out.bindings.set(segs.at(-1), bind(r.files, null, { line })); continue; }
|
|
210
|
+
const parent = ctx.rustModule(file, segs.slice(0, -1).join('::'));
|
|
211
|
+
if (parent.files?.length) out.bindings.set(segs.at(-1), bind(parent.files, segs.at(-1), { line }));
|
|
212
|
+
else out.unresolved.push({ file, line, import: m[1], why: r.why });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Names declared with a type in a file: `private repo: OrderRepo`, `OrderRepo repo;`, `self.repo = OrderRepo()`. */
|
|
218
|
+
function typesOf(src, language, inMember = false) {
|
|
219
|
+
const types = new Map(), clash = new Set();
|
|
220
|
+
const put = (name, type) => { if (!name || !type || clash.has(name)) return; if (types.has(name) && types.get(name) !== type) { types.delete(name); clash.add(name); } else types.set(name, type); };
|
|
221
|
+
const code = stripStrings(src);
|
|
222
|
+
const each = (re, ni, ti) => { for (const m of code.matchAll(re)) put(m[ni], m[ti]); };
|
|
223
|
+
if (JS.has(language)) {
|
|
224
|
+
each(/(?:\b(?:private|public|protected|readonly)\s+)+([\w$]+)\s*[?!]?\s*:\s*([A-Z][\w$]*)\b(?!\s*[<[.])/g, 1, 2);
|
|
225
|
+
each(/\b(?:const|let|var)\s+([\w$]+)\s*(?::\s*[\w$<>]+\s*)?=\s*new\s+([A-Z][\w$]*)\s*\(/g, 1, 2);
|
|
226
|
+
each(/\bthis\.([\w$]+)\s*=\s*new\s+([A-Z][\w$]*)\s*\(/g, 1, 2);
|
|
227
|
+
} else if (language === 'python') {
|
|
228
|
+
each(/\bself\.(\w+)\s*(?::\s*\w+\s*)?=\s*([A-Z]\w*)\(/g, 1, 2);
|
|
229
|
+
each(/\b(\w+)\s*:\s*([A-Z]\w*)\s*(?=[,)=\n])/g, 1, 2);
|
|
230
|
+
each(/^\s*(\w+)\s*=\s*((?:\w+\.)*[A-Z]\w*)\(/gm, 1, 2);
|
|
231
|
+
} else if (language === 'java' || language === 'csharp') {
|
|
232
|
+
for (const m of code.matchAll(/\b([A-Z]\w*)(?:<[^<>;()]*>)?\s+(\w+)\s*(?=[;=,)])/g)) if (!/^(return|new|throw|else|case)$/.test(m[2])) put(m[2], m[1]);
|
|
233
|
+
} else if (language === 'kotlin') {
|
|
234
|
+
each(/\b(?:val|var)?\s*(\w+)\s*:\s*([A-Z]\w*)\b(?!\s*[<.])/g, 1, 2);
|
|
235
|
+
each(/\b(?:val|var)\s+(\w+)\s*=\s*([A-Z]\w*)\(/g, 1, 2);
|
|
236
|
+
} else if (language === 'php') {
|
|
237
|
+
each(/\b([A-Z]\w*)\s+\$(\w+)/g, 2, 1);
|
|
238
|
+
each(/\$this->(\w+)\s*=\s*new\s+([A-Z]\w*)/g, 1, 2);
|
|
239
|
+
each(/\$(\w+)\s*=\s*new\s+([A-Z]\w*)/g, 1, 2);
|
|
240
|
+
} else if (language === 'ruby') {
|
|
241
|
+
each(/@?(\w+)\s*=\s*([A-Z][\w:]*)\.new\b/g, 1, 2);
|
|
242
|
+
} else if (language === 'go') {
|
|
243
|
+
// Struct fields (`repo *store.Repo`), at file level only.
|
|
244
|
+
if (!inMember) for (const m of code.matchAll(/^[ \t]*(\w+)[ \t]+\*?((?:\w+\.)?[A-Z]\w*)[ \t]*$/gm)) put(m[1], m[2]);
|
|
245
|
+
for (const m of code.matchAll(/\b(\w+)\s*:?=\s*&?((?:\w+\.)?[A-Z]\w*)\{/g)) put(m[1], m[2]);
|
|
246
|
+
// Receivers and parameters: `func (c *Command) Run(cmd *Command, args []string)`.
|
|
247
|
+
for (const sig of code.matchAll(/\bfunc\s*(\([^)]*\))?\s*\w*\s*\(([^)]*)\)/g)) for (const m of `${sig[1] ?? ''},${sig[2]}`.matchAll(/(\w+)\s+\*?((?:\w+\.)?[A-Z]\w*)\s*(?=[,)]|$)/g)) put(m[1], m[2]);
|
|
248
|
+
}
|
|
249
|
+
return types;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ── Services: HTTP requests to routes, events and queues to listeners ─────────────────────────────────
|
|
253
|
+
|
|
254
|
+
const PLACEHOLDER = '\u0000';
|
|
255
|
+
/** The path an HTTP call goes to, from its URL argument. null with a reason when it is worked out at run time. */
|
|
256
|
+
function urlOf(e) {
|
|
257
|
+
if (!e) return { why: 'the address is not written in the code' };
|
|
258
|
+
let text = null;
|
|
259
|
+
if (e.kind === 'literal' && e.type === 'text') text = String(e.value);
|
|
260
|
+
else if (e.kind === 'template') text = e.parts.map((p) => (typeof p === 'string' ? p : PLACEHOLDER)).join('');
|
|
261
|
+
else if (e.kind === 'literal' && e.interpolated) text = String(e.value).replace(/\$\{[^}]*\}|\$\w+|#\{[^}]*\}|\{[^}]*\}/g, PLACEHOLDER);
|
|
262
|
+
else if (e.kind === 'binary' && e.op === '+') {
|
|
263
|
+
const parts = [];
|
|
264
|
+
const flat = (x) => { if (x.kind === 'binary' && x.op === '+') { flat(x.left); flat(x.right); } else parts.push(x); };
|
|
265
|
+
flat(e);
|
|
266
|
+
text = parts.map((x) => (x.kind === 'literal' && x.type === 'text' ? String(x.value) : PLACEHOLDER)).join('');
|
|
267
|
+
}
|
|
268
|
+
if (text == null) return { why: 'computed URL: the address is worked out when it runs' };
|
|
269
|
+
if (text.startsWith(PLACEHOLDER)) return { why: 'computed URL: the address starts with a value worked out when it runs' };
|
|
270
|
+
let host = null;
|
|
271
|
+
const abs = text.match(/^[a-z][a-z0-9+.-]*:\/\/([^/]*)(.*)$/i);
|
|
272
|
+
if (abs) { host = abs[1]; text = abs[2] || '/'; }
|
|
273
|
+
if (host && !/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:\d+)?$/.test(host)) return { why: `calls another service at ${host.replace(new RegExp(PLACEHOLDER, 'g'), '…')}`, external: true };
|
|
274
|
+
if (!text.startsWith('/')) return { why: 'computed URL: not a path from the root of this app' };
|
|
275
|
+
const path = text.replace(/[?#].*$/s, '');
|
|
276
|
+
const segs = path.split('/').filter(Boolean).map((s) => (s.includes(PLACEHOLDER) ? '*' : s));
|
|
277
|
+
return { path: '/' + segs.map((s) => (s === '*' ? ':value' : s)).join('/'), segs };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** A route's path as segments; parameters (`:id`, `{id}`, `<int:id>`, `[id]`, `*`) are wildcards. */
|
|
281
|
+
const routeSegs = (p) => String(p).split('/').filter(Boolean).map((s) => (/^(:\w+\??|\{[^}]+\}|<[^>]+>|\[[^\]]+\]|\*+|\(\.\*\))$/.test(s) ? '*' : s));
|
|
282
|
+
function segsMatch(a, b) {
|
|
283
|
+
if (a.length !== b.length) return -1;
|
|
284
|
+
let exact = 0;
|
|
285
|
+
for (let i = 0; i < a.length; i++) { if (a[i] === b[i] && a[i] !== '*') exact++; else if (a[i] !== '*' && b[i] !== '*') return -1; }
|
|
286
|
+
return exact;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const HTTP_SAYS = /^Sends an? ([A-Z]+) request to /;
|
|
290
|
+
/** The URL argument of an HTTP call. */
|
|
291
|
+
function urlArg(call) {
|
|
292
|
+
const args = call.args || [];
|
|
293
|
+
const path = calleePath(call.callee) || [];
|
|
294
|
+
const last = path.at(-1) || '';
|
|
295
|
+
if (/^NewRequest(WithContext)?$/.test(last)) return args[last.endsWith('Context') ? 2 : 1];
|
|
296
|
+
if (args[0]?.kind === 'object') { const u = args[0].entries?.find((x) => x.key && /^(url|uri)$/.test(x.key.value ?? x.key.name ?? '')); return u?.value ?? null; }
|
|
297
|
+
if (/^(request|Request|exchange|send)$/.test(last) && args[0]?.kind === 'literal' && /^[A-Z]+$/.test(String(args[0].value))) return args[1];
|
|
298
|
+
return args[0];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const EVENT_PUBLISH = /^(emit|publish|publishEvent|sendToQueue|enqueue|basic_publish|produce|dispatch)$/;
|
|
302
|
+
const EVENT_SUBSCRIBE = /\.(on|once|addListener|subscribe|consume|listen|handle)\(\s*(['"`])([^'"`]+)\2\s*,\s*(?:(?:async\s*)?(?:function\b|\(|[\w$]+\s*=>)|((?:this\.|self\.)?[\w$]+)\s*[,)])/g;
|
|
303
|
+
const EVENT_DECORATOR = /@(OnEvent|EventPattern|MessagePattern|KafkaListener|RabbitListener|SqsListener|JmsListener|StreamListener|Subscribe|EventHandler|Consumer)\s*\(\s*(?:\{?\s*)?(?:(?:topics|queues|destination|value|pattern|event)\s*[:=]\s*)?(?:\[\s*)?(['"])([^'"]+)\2/g;
|
|
304
|
+
/** Names any emitter uses (a stream's 'error', a socket's 'close'): matching them across files would be a guess. */
|
|
305
|
+
const GENERIC_EVENTS = new Set(['error', 'close', 'end', 'data', 'finish', 'open', 'message', 'connect', 'connection', 'request', 'response', 'listening', 'drain', 'pipe', 'unpipe', 'readable', 'timeout', 'abort', 'change', 'click', 'input', 'submit', 'load', 'ready', 'exit', 'mount', 'start', 'stop', 'done', 'update', 'success', 'fail', 'progress', 'headers', 'upgrade', 'secureConnection', 'disconnect', 'reconnect']);
|
|
306
|
+
|
|
307
|
+
// ── Linking ──────────────────────────────────────────────────────────────────────────────────────────
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Add the whole system's links to a model: `links[]` entries with `crossFile: true` (kind 'uses', with the target's
|
|
311
|
+
* file and the calling step's line) and `kind: 'sends-to'` (an HTTP request to a route; an event or message to its
|
|
312
|
+
* listener), and `model.notLinked` for what was worth linking and could not be. Mutates and returns the model.
|
|
313
|
+
*/
|
|
314
|
+
export function linkSystem(model, files) {
|
|
315
|
+
const sources = new Map(files.map((f) => [f.path, String(f.source ?? '')]));
|
|
316
|
+
const langOf = new Map(model.files.map((f) => [f.path, f.language]));
|
|
317
|
+
const paths = new Set(model.files.map((f) => f.path));
|
|
318
|
+
const membersOf = new Map(), thingsOf = new Map();
|
|
319
|
+
for (const m of model.members) (membersOf.get(m.file) ?? membersOf.set(m.file, []).get(m.file)).push(m);
|
|
320
|
+
for (const t of model.things) (thingsOf.get(t.file) ?? thingsOf.set(t.file, []).get(t.file)).push(t);
|
|
321
|
+
const memberById = new Map(model.members.map((m) => [m.id, m]));
|
|
322
|
+
const notLinked = [];
|
|
323
|
+
// (One file with no routes and no Things has nothing to link: no other files, services, or instances.)
|
|
324
|
+
if (model.files.length < 2 && !model.members.some((m) => m.route) && !model.things.length) { model.notLinked = notLinked; return model; }
|
|
325
|
+
|
|
326
|
+
// Top-level members of a file by name: not a method of a Thing, not written inside another function.
|
|
327
|
+
const topCache = new Map();
|
|
328
|
+
const topOf = (file) => {
|
|
329
|
+
let t = topCache.get(file);
|
|
330
|
+
if (t) return t;
|
|
331
|
+
t = new Map();
|
|
332
|
+
const ms = (membersOf.get(file) || []).filter((m) => !m.callback);
|
|
333
|
+
const lang = langOf.get(file);
|
|
334
|
+
const src = lang === 'go' ? sources.get(file)?.split('\n') : null;
|
|
335
|
+
for (const m of ms) {
|
|
336
|
+
if (m.owner && !(m.kind === 'setup')) continue;
|
|
337
|
+
if (ms.some((o) => o !== m && o.lines[0] < m.lines[0] && m.lines[1] <= o.lines[1] && !o.owner)) continue;
|
|
338
|
+
if (src && /^\s*func\s*\(/.test(src[m.lines[0] - 1] || '')) continue; // a Go method (it has a receiver)
|
|
339
|
+
if (m.owner) continue;
|
|
340
|
+
(t.get(m.name) ?? t.set(m.name, []).get(m.name)).push(m);
|
|
341
|
+
}
|
|
342
|
+
topCache.set(file, t);
|
|
343
|
+
return t;
|
|
344
|
+
};
|
|
345
|
+
const thingNamed = (file, name) => (thingsOf.get(file) || []).find((t) => t.name === name);
|
|
346
|
+
// Overloads (Java, C#, Kotlin): the one that takes as many values as the call gives, when only one does.
|
|
347
|
+
let argc = null;
|
|
348
|
+
const pick = (ms) => (ms.length <= 1 || argc == null ? ms : ms.filter((m) => m.arity === argc).length === 1 ? ms.filter((m) => m.arity === argc) : ms);
|
|
349
|
+
const setupOf = (thing) => { const ms = pick(thing.can.map((id) => memberById.get(id)).filter((m) => m?.kind === 'setup')); return ms.length === 1 ? ms[0] : null; };
|
|
350
|
+
const methodOf = (thing, name) => pick(thing.can.map((id) => memberById.get(id)).filter((m) => m && m.name === name));
|
|
351
|
+
|
|
352
|
+
// ── Where things live: JS files, Python modules, Go packages, JVM/C#/PHP packages, Rust modules ──
|
|
353
|
+
const JS_EXT = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
|
|
354
|
+
// Manifests, when given with the files: go.mod (module paths), package.json (workspace packages), tsconfig.json /
|
|
355
|
+
// jsconfig.json (path aliases). They are what make a non-relative import this repo's own, not a guess.
|
|
356
|
+
const manifests = files.filter((f) => /(^|\/)(go\.mod|package\.json|[tj]sconfig\.json)$/.test(f.path) && f.source);
|
|
357
|
+
const json = (text) => { try { return JSON.parse(String(text).replace(/\/\*[\s\S]*?\*\/|(^|[^:"])\/\/.*$/gm, '$1').replace(/,(\s*[}\]])/g, '$1')); } catch { return null; } };
|
|
358
|
+
const goModules = manifests.filter((f) => /(^|\/)go\.mod$/.test(f.path)).map((f) => ({ dir: dirOf(f.path), module: (f.source.match(/^\s*module\s+(\S+)/m) || [])[1] })).filter((x) => x.module);
|
|
359
|
+
const jsPackages = new Map();
|
|
360
|
+
const aliases = [];
|
|
361
|
+
for (const f of manifests) {
|
|
362
|
+
if (/(^|\/)package\.json$/.test(f.path)) { const j = json(f.source); if (j?.name) jsPackages.set(j.name, { dir: dirOf(f.path), entry: j.source || j.module || j.main || null }); }
|
|
363
|
+
else if (/(^|\/)[tj]sconfig\.json$/.test(f.path)) {
|
|
364
|
+
const o = json(f.source)?.compilerOptions;
|
|
365
|
+
const base = join(dirOf(f.path), o?.baseUrl || '.');
|
|
366
|
+
for (const [k, v] of Object.entries(o?.paths || {})) for (const to of [].concat(v)) aliases.push({ from: k, to: join(base, String(to)), dir: dirOf(f.path) });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const jsFile = (from, spec) => {
|
|
370
|
+
const rel = spec.startsWith('.') || spec.startsWith('/');
|
|
371
|
+
const bases = [];
|
|
372
|
+
// A tsconfig path alias (`@/*` -> `./src/*`) for files under that tsconfig.
|
|
373
|
+
const alias = rel ? [] : aliases.filter((a) => (!a.dir || from.startsWith(a.dir + '/')) && (a.from.endsWith('*') ? spec.startsWith(a.from.slice(0, -1)) : spec === a.from));
|
|
374
|
+
const pkgName = !rel && (spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0]);
|
|
375
|
+
if (rel) bases.push(spec.startsWith('/') ? join(spec) : join(dirOf(from), spec));
|
|
376
|
+
bases.push(...alias.map((a) => (a.from.endsWith('*') ? a.to.replace('*', spec.slice(a.from.length - 1)) : a.to)));
|
|
377
|
+
if (!rel && jsPackages.has(pkgName)) {
|
|
378
|
+
// This repo's own package (a workspace, or examples importing the package they sit in).
|
|
379
|
+
const pk = jsPackages.get(pkgName);
|
|
380
|
+
const sub = spec.slice(pkgName.length + 1);
|
|
381
|
+
if (sub) bases.push(join(pk.dir, sub), join(pk.dir, 'src', sub));
|
|
382
|
+
else {
|
|
383
|
+
const entry = pk.entry ? join(pk.dir, pk.entry) : null;
|
|
384
|
+
// A built entry (`dist/index.js`) is not in the repo; its source is the package's src/index when that exists.
|
|
385
|
+
bases.push(...[entry, join(pk.dir, 'index'), ...(!entry || /^(dist|build|lib|out)\//.test(pk.entry || '') ? [join(pk.dir, 'src/index')] : [])].filter((x) => x != null));
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// (`@/lib/x` with no tsconfig saying where `@` points is not guessed.)
|
|
389
|
+
if (!bases.length) return /^[@~#]\//.test(spec) ? { why: `path alias ${spec}: no tsconfig paths say where it points` } : { why: `external package (${pkgName})`, external: true };
|
|
390
|
+
for (const b of bases) { const f = tryJs(b); if (f) return { file: f }; }
|
|
391
|
+
if (alias.length) return { why: `path alias ${spec}: no file in this repo` };
|
|
392
|
+
return { why: `no file ${spec} in this repo` };
|
|
393
|
+
};
|
|
394
|
+
function tryJs(base) {
|
|
395
|
+
if (paths.has(base) && JS.has(langOf.get(base))) return base;
|
|
396
|
+
const noExt = base.replace(/\.(m|c)?js$/, '');
|
|
397
|
+
for (const e of JS_EXT) if (paths.has(noExt + e)) return noExt + e;
|
|
398
|
+
for (const e of JS_EXT) if (paths.has(`${base}/index${e}`)) return `${base}/index${e}`;
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const pyIndex = new Map();
|
|
403
|
+
for (const f of model.files) {
|
|
404
|
+
if (f.language !== 'python') continue;
|
|
405
|
+
const segs = f.path.replace(/\.pyi?$/, '').replace(/\/__init__$/, '').split('/');
|
|
406
|
+
for (let i = 0; i < segs.length; i++) { const k = segs.slice(i).join('.'); (pyIndex.get(k) ?? pyIndex.set(k, []).get(k)).push({ file: f.path, prefix: segs.slice(0, i).join('/') }); }
|
|
407
|
+
}
|
|
408
|
+
const pyModule = (from, spec) => {
|
|
409
|
+
const dots = spec.match(/^\.*/)[0].length;
|
|
410
|
+
if (dots) {
|
|
411
|
+
let dir = dirOf(from);
|
|
412
|
+
for (let i = 1; i < dots; i++) dir = dirOf(dir);
|
|
413
|
+
const rest = spec.slice(dots).replace(/\./g, '/');
|
|
414
|
+
const base = join(dir, rest);
|
|
415
|
+
for (const c of [`${base}.py`, `${base}/__init__.py`]) if (paths.has(c)) return { files: [c] };
|
|
416
|
+
if (!rest && [...paths].some((p) => dirOf(p) === dir)) return { files: [] , why: 'a package with no __init__.py' };
|
|
417
|
+
return { why: `no module ${spec} next to this file` };
|
|
418
|
+
}
|
|
419
|
+
const cands = pyIndex.get(spec) || [];
|
|
420
|
+
if (!cands.length) return { why: `external package (${spec.split('.')[0]})`, external: true };
|
|
421
|
+
const home = dirOf(from);
|
|
422
|
+
const near = cands.filter((c) => !c.prefix || home === c.prefix || home.startsWith(c.prefix + '/'));
|
|
423
|
+
const pick = near.length ? near : cands.filter((c) => !c.prefix || /^(src|lib|python)$/.test(c.prefix));
|
|
424
|
+
if (pick.length === 1) return { files: [pick[0].file] };
|
|
425
|
+
// The same module name under two roots: which one Python loads depends on how it is run.
|
|
426
|
+
return { why: pick.length ? `${pick.length} modules in this repo are named ${spec}` : `module ${spec} is not under this file's folder`, ambiguous: true };
|
|
427
|
+
};
|
|
428
|
+
const hasSymbol = (fs, name) => fs.some((f) => topOf(f).has(name) || thingNamed(f, name) || modules.get(f)?.bindings.has(name));
|
|
429
|
+
|
|
430
|
+
const goDirs = new Map();
|
|
431
|
+
for (const f of model.files) if (f.language === 'go') { const d = dirOf(f.path); (goDirs.get(d) ?? goDirs.set(d, []).get(d)).push(f.path); }
|
|
432
|
+
const goPkgName = (fs) => (sources.get(fs.find((f) => !/_test\.go$/.test(f)) ?? fs[0])?.match(/^\s*package\s+(\w+)/m) || [])[1];
|
|
433
|
+
const goPackage = (imp) => {
|
|
434
|
+
let best = null;
|
|
435
|
+
const mod = goModules.filter((g) => imp === g.module || imp.startsWith(g.module + '/')).sort((a, b) => b.module.length - a.module.length)[0];
|
|
436
|
+
if (mod) {
|
|
437
|
+
best = join(mod.dir, imp.slice(mod.module.length));
|
|
438
|
+
if (!goDirs.has(best)) return { why: `no package ${imp} in this repo` };
|
|
439
|
+
} else {
|
|
440
|
+
if (!/\./.test(imp.split('/')[0])) return { why: `standard library (${imp})`, external: true };
|
|
441
|
+
// With no go.mod, a folder of this repo whose path ends the import path (two folders deep or more).
|
|
442
|
+
if (!goModules.length) for (const d of goDirs.keys()) if (d.includes('/') && (imp === d || imp.endsWith('/' + d)) && (!best || d.length > best.length)) best = d;
|
|
443
|
+
if (best == null) return { why: `external package (${imp})`, external: true };
|
|
444
|
+
}
|
|
445
|
+
const fs = goDirs.get(best).filter((f) => !/_test\.go$/.test(f));
|
|
446
|
+
return { files: fs, name: goPkgName(fs) || best.split('/').pop() };
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
// Packages and namespaces (Java/Kotlin package, C# namespace, PHP namespace).
|
|
450
|
+
const pkgOf = new Map();
|
|
451
|
+
for (const f of model.files) {
|
|
452
|
+
const s = sources.get(f.path) || '';
|
|
453
|
+
if (JVM.has(f.language)) pkgOf.set(f.path, [(s.match(/^\s*package\s+([\w.]+)/m) || [])[1] ?? '']);
|
|
454
|
+
else if (f.language === 'csharp') pkgOf.set(f.path, [...s.matchAll(/^\s*namespace\s+([\w.]+)/gm)].map((m) => m[1]).concat(s.match(/^\s*namespace\s/m) ? [] : ['']));
|
|
455
|
+
else if (f.language === 'php') pkgOf.set(f.path, [(s.match(/^\s*namespace\s+([\w\\]+)\s*;/m) || [])[1] ?? '']);
|
|
456
|
+
}
|
|
457
|
+
const family = (l) => (JVM.has(l) ? 'jvm' : l);
|
|
458
|
+
const classesNamed = new Map();
|
|
459
|
+
for (const t of model.things) { const k = `${family(langOf.get(t.file))}|${t.name}`; (classesNamed.get(k) ?? classesNamed.set(k, []).get(k)).push(t); }
|
|
460
|
+
const classIn = (pkg, name, language) => {
|
|
461
|
+
const all = classesNamed.get(`${family(language)}|${name}`) || [];
|
|
462
|
+
const hit = all.filter((t) => (pkgOf.get(t.file) || ['']).includes(pkg));
|
|
463
|
+
if (hit.length === 1) return { thing: hit[0] };
|
|
464
|
+
if (hit.length > 1) return { why: `${hit.length} classes named ${name} in ${pkg}` };
|
|
465
|
+
return { why: all.length ? `no class ${name} in ${pkg || 'this package'}` : `external package (${pkg || name})`, external: !all.length };
|
|
466
|
+
};
|
|
467
|
+
const pkgFiles = (pkg) => model.files.filter((f) => (pkgOf.get(f.path) || []).includes(pkg)).map((f) => f.path);
|
|
468
|
+
|
|
469
|
+
const rustModule = (from, spec) => {
|
|
470
|
+
const segs = spec.split('::');
|
|
471
|
+
let root = from.match(/^(.*?\/?src)\//)?.[1] ?? dirOf(from);
|
|
472
|
+
let dir;
|
|
473
|
+
if (segs[0] === 'crate') dir = root;
|
|
474
|
+
else if (segs[0] === 'self') dir = /\/(mod|lib|main)\.rs$/.test(from) || !from.includes('/') ? dirOf(from) : from.replace(/\.rs$/, '');
|
|
475
|
+
else if (segs[0] === 'super') dir = dirOf(/\/(mod)\.rs$/.test(from) ? dirOf(from) : from.replace(/\.rs$/, ''));
|
|
476
|
+
else return { why: `external crate (${segs[0]})`, external: true };
|
|
477
|
+
const rest = segs.slice(1);
|
|
478
|
+
if (!rest.length) return { files: [] };
|
|
479
|
+
const base = join(dir, ...rest);
|
|
480
|
+
for (const c of [`${base}.rs`, `${base}/mod.rs`]) if (paths.has(c)) return { files: [c] };
|
|
481
|
+
return { why: `no module ${spec} in this crate` };
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
const ctx = { jsFile, pyModule, hasSymbol, goPackage, classIn, pkgFiles, rustModule };
|
|
485
|
+
|
|
486
|
+
// ── Every file's imports and declared types ──
|
|
487
|
+
const modules = new Map();
|
|
488
|
+
const external = new Map();
|
|
489
|
+
for (const f of model.files) {
|
|
490
|
+
const src = sources.get(f.path);
|
|
491
|
+
if (src == null) continue;
|
|
492
|
+
const out = { bindings: new Map(), unresolved: [], star: [], packages: [], types: null, language: f.language };
|
|
493
|
+
try {
|
|
494
|
+
if (JS.has(f.language)) jsImports(src, f.path, ctx, out);
|
|
495
|
+
else if (f.language === 'go') goImports(src, f.path, ctx, out);
|
|
496
|
+
else if (JVM.has(f.language)) jvmImports(src, f.path, ctx, out, f.language);
|
|
497
|
+
else if (f.language === 'csharp') csharpImports(src, f.path, ctx, out);
|
|
498
|
+
else if (f.language === 'php') phpImports(src, f.path, ctx, out);
|
|
499
|
+
else if (f.language === 'rust') rustImports(src, f.path, ctx, out);
|
|
500
|
+
} catch { /* one file's imports never stop the whole app */ }
|
|
501
|
+
modules.set(f.path, out);
|
|
502
|
+
}
|
|
503
|
+
// Python second: `from pkg import name` looks at names pkg/__init__.py itself imports.
|
|
504
|
+
for (const f of model.files) if (f.language === 'python' && sources.has(f.path)) { try { pythonImports(sources.get(f.path), f.path, ctx, modules.get(f.path)); } catch { /* keep going */ } }
|
|
505
|
+
const once = new Set();
|
|
506
|
+
for (const [file, mod] of modules) {
|
|
507
|
+
for (const u of mod.unresolved) {
|
|
508
|
+
const k = `${file}|${u.line}|${u.import}|${u.why}`;
|
|
509
|
+
if (once.has(k)) continue; // one import statement with several names is listed once
|
|
510
|
+
once.add(k);
|
|
511
|
+
if (/^(external|standard library)/.test(u.why)) {
|
|
512
|
+
const key = u.why;
|
|
513
|
+
const e = external.get(key);
|
|
514
|
+
if (e) e.files++; else external.set(key, { file, line: u.line, import: u.import, why: u.why, files: 1 });
|
|
515
|
+
} else notLinked.push(u);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
notLinked.push(...external.values());
|
|
519
|
+
const typesFor = (file) => { const m = modules.get(file); if (m && !m.types) m.types = typesOf(sources.get(file) || '', m.language); return m?.types ?? new Map(); };
|
|
520
|
+
|
|
521
|
+
// ── Resolving one callee path in one file ──
|
|
522
|
+
const jsExportCache = new Map();
|
|
523
|
+
const jsExp = (f) => { let e = jsExportCache.get(f); if (!e) { e = jsExports(sources.get(f) || ''); jsExportCache.set(f, e); } return e; };
|
|
524
|
+
/** A symbol in a module: { member } or { thing }, following JS re-exports and Python re-imports. */
|
|
525
|
+
const symbolIn = (fs, symbol, depth = 0) => {
|
|
526
|
+
if (depth > 6) return null;
|
|
527
|
+
for (const f of fs) {
|
|
528
|
+
let name = symbol;
|
|
529
|
+
const lang = langOf.get(f);
|
|
530
|
+
if (JS.has(lang)) {
|
|
531
|
+
const ex = jsExp(f);
|
|
532
|
+
if (symbol === 'default' || symbol === 'module.exports') name = ex.def ?? (symbol === 'module.exports' ? null : 'default');
|
|
533
|
+
else if (ex.named.has(symbol)) name = ex.named.get(symbol);
|
|
534
|
+
if (name == null) {
|
|
535
|
+
// `require('./x')` of a file that only sets `exports.a = …`: the module itself, as a namespace.
|
|
536
|
+
return { module: [f] };
|
|
537
|
+
}
|
|
538
|
+
// `exports.place = function`, `module.exports.place =`.
|
|
539
|
+
const assigned = (membersOf.get(f) || []).filter((m) => /^(?:module\.)?exports\.([\w$]+)$/.test(m.assignedTo || '') && m.assignedTo.split('.').pop() === name);
|
|
540
|
+
if (assigned.length === 1) return { member: assigned[0] };
|
|
541
|
+
}
|
|
542
|
+
const top = topOf(f).get(name);
|
|
543
|
+
if (top?.length === 1) return { member: top[0] };
|
|
544
|
+
const th = thingNamed(f, name);
|
|
545
|
+
if (th) return { thing: th };
|
|
546
|
+
if (JS.has(lang)) {
|
|
547
|
+
for (const r of jsExp(f).re) {
|
|
548
|
+
if (r.names && !r.names.has(symbol)) continue;
|
|
549
|
+
if (r.as && r.as !== symbol) continue;
|
|
550
|
+
const t = jsFile(f, r.spec);
|
|
551
|
+
if (!t.file) continue;
|
|
552
|
+
if (r.as) return { module: [t.file] };
|
|
553
|
+
const got = symbolIn([t.file], r.names ? r.names.get(symbol) : symbol, depth + 1);
|
|
554
|
+
if (got) return got;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
const b = modules.get(f)?.bindings.get(name);
|
|
558
|
+
if (b && depth < 6) { const got = b.symbol ? symbolIn(b.files, b.symbol, depth + 1) : { module: b.files }; if (got) return got; }
|
|
559
|
+
}
|
|
560
|
+
return null;
|
|
561
|
+
};
|
|
562
|
+
const classByName = (file, name) => {
|
|
563
|
+
const lang = langOf.get(file);
|
|
564
|
+
const mod = modules.get(file);
|
|
565
|
+
const b = mod?.bindings.get(name);
|
|
566
|
+
if (b) { const got = b.thing ? { thing: b.thing } : b.symbol ? symbolIn(b.files, b.symbol) : null; return got?.thing ? got : { why: got ? null : `${name} is not a class in ${b.spec ?? 'its module'}` }; }
|
|
567
|
+
if (JVM.has(lang) || lang === 'csharp' || lang === 'php') {
|
|
568
|
+
const own = pkgOf.get(file) || [''];
|
|
569
|
+
const spaces = new Set([...own, ...(mod?.packages ?? [])]);
|
|
570
|
+
// C#: a namespace also sees its parent namespaces.
|
|
571
|
+
if (lang === 'csharp') for (const n of own) { const parts = n.split('.'); for (let i = 1; i < parts.length; i++) spaces.add(parts.slice(0, i).join('.')); }
|
|
572
|
+
const all = (classesNamed.get(`${family(lang)}|${name}`) || []).filter((t) => (pkgOf.get(t.file) || ['']).some((p) => spaces.has(p)));
|
|
573
|
+
if (all.length === 1) return { thing: all[0] };
|
|
574
|
+
return { why: all.length > 1 ? `${all.length} classes named ${name} are visible here` : null };
|
|
575
|
+
}
|
|
576
|
+
if (lang === 'ruby') {
|
|
577
|
+
// Ruby constants are global: a class name is that class when exactly one is defined in the repo.
|
|
578
|
+
const all = classesNamed.get(`ruby|${name}`) || [];
|
|
579
|
+
if (all.length === 1) return { thing: all[0] };
|
|
580
|
+
return { why: all.length > 1 ? `${all.length} classes named ${name} in this repo` : null };
|
|
581
|
+
}
|
|
582
|
+
if (lang !== 'go' && name.includes('.')) {
|
|
583
|
+
const parts = name.split('.');
|
|
584
|
+
for (let k = parts.length - 1; k >= 1; k--) {
|
|
585
|
+
const pb = mod?.bindings.get(parts.slice(0, k).join('.'));
|
|
586
|
+
if (!pb) continue;
|
|
587
|
+
const target = pb.thing ? { thing: pb.thing } : pb.symbol ? symbolIn(pb.files, pb.symbol) : { module: pb.files };
|
|
588
|
+
let cur = target;
|
|
589
|
+
for (const seg of parts.slice(k)) { if (!cur?.module) { cur = null; break; } cur = symbolIn(cur.module, seg); }
|
|
590
|
+
return cur?.thing ? { thing: cur.thing } : { why: null };
|
|
591
|
+
}
|
|
592
|
+
return { why: null };
|
|
593
|
+
}
|
|
594
|
+
if (lang === 'go' && name.includes('.')) {
|
|
595
|
+
const [pkg, type] = name.split('.');
|
|
596
|
+
const pb = mod?.bindings.get(pkg);
|
|
597
|
+
if (pb) { const th = pb.files.map((f) => thingNamed(f, type)).find(Boolean); if (th) return { thing: th }; }
|
|
598
|
+
return { why: null };
|
|
599
|
+
}
|
|
600
|
+
if (lang === 'go') {
|
|
601
|
+
const th = (goDirs.get(dirOf(file)) || []).map((f) => thingNamed(f, name)).find(Boolean);
|
|
602
|
+
return th ? { thing: th } : { why: null };
|
|
603
|
+
}
|
|
604
|
+
if (JS.has(lang) || lang === 'python') { const th = thingNamed(file, name); return th ? { thing: th } : { why: null }; }
|
|
605
|
+
return { why: null };
|
|
606
|
+
};
|
|
607
|
+
const viaThing = (thing, rest, isNew) => {
|
|
608
|
+
if (!rest.length) {
|
|
609
|
+
const s = setupOf(thing);
|
|
610
|
+
return s ? { member: s } : { why: thing.can.some((id) => memberById.get(id)?.kind === 'setup') ? `${thing.name} has several ways to start; which one depends on the values given` : null };
|
|
611
|
+
}
|
|
612
|
+
if (rest.length > 1) return { why: null };
|
|
613
|
+
const ms = methodOf(thing, rest[0]);
|
|
614
|
+
// Ruby `Order.new(…)`, Rust `Order::new(…)` with no method of that name: how a new one starts.
|
|
615
|
+
if (!ms.length && rest[0] === 'new') return viaThing(thing, [], true);
|
|
616
|
+
if (ms.length === 1) return { member: ms[0] };
|
|
617
|
+
if (thing.kind !== 'thing' && !thing.can.length) return { why: `${thing.name} is an interface: which code runs is chosen when it runs`, worth: true };
|
|
618
|
+
return { why: ms.length > 1 ? `${ms.length} methods named ${rest[0]} in ${thing.name}` : null };
|
|
619
|
+
};
|
|
620
|
+
/** From a module, Thing, or member, follow the rest of a path: `utils.rewind_body`, `models.Order.create`. */
|
|
621
|
+
const walkTail = (target, tail, isNew, spec) => {
|
|
622
|
+
let cur = target;
|
|
623
|
+
for (let i = 0; i < tail.length; i++) {
|
|
624
|
+
if (cur.module) { const got = symbolIn(cur.module, tail[i]); if (!got) return { why: `${spec ?? 'the module'} has no ${tail.slice(0, i + 1).join('.')}`, worth: true }; cur = got; continue; }
|
|
625
|
+
if (cur.thing) return viaThing(cur.thing, tail.slice(i), isNew);
|
|
626
|
+
return { why: null };
|
|
627
|
+
}
|
|
628
|
+
if (cur.member) return { member: cur.member };
|
|
629
|
+
if (cur.thing) return viaThing(cur.thing, [], isNew);
|
|
630
|
+
return { why: null };
|
|
631
|
+
};
|
|
632
|
+
// A name's declared type: in the member's own code first (`s = requests.Session()` in one test), then the file's.
|
|
633
|
+
const memberTypes = new Map(), fileLines = new Map();
|
|
634
|
+
const typeOf = (file, member, name) => {
|
|
635
|
+
if (member) {
|
|
636
|
+
let t = memberTypes.get(member.id);
|
|
637
|
+
if (!t) {
|
|
638
|
+
let lines = fileLines.get(file);
|
|
639
|
+
if (!lines) { lines = (sources.get(file) || '').split('\n'); fileLines.set(file, lines); }
|
|
640
|
+
// (A Go receiver or a typed parameter sits on the signature line, which belongs to the member.)
|
|
641
|
+
t = typesOf(lines.slice(member.lines[0] - 1, member.lines[1]).join('\n'), langOf.get(file), true);
|
|
642
|
+
memberTypes.set(member.id, t);
|
|
643
|
+
}
|
|
644
|
+
if (t.has(name)) return t.get(name);
|
|
645
|
+
}
|
|
646
|
+
return typesFor(file).get(name);
|
|
647
|
+
};
|
|
648
|
+
const resolve = (file, path, isNew, member) => {
|
|
649
|
+
const lang = langOf.get(file);
|
|
650
|
+
const mod = modules.get(file);
|
|
651
|
+
if (!mod) return { why: null };
|
|
652
|
+
const [head, ...rest] = path;
|
|
653
|
+
// `this.repo.find()`, `self.repo.find()`, `s.repo.Find()` (a Go receiver): the field's declared type.
|
|
654
|
+
if (rest.length === 2 && (/^(this|self|@)$/.test(head) || lang === 'go')) {
|
|
655
|
+
const type = typeOf(file, member, rest[0]);
|
|
656
|
+
if (type) { const c = classByName(file, type); if (c.thing) return viaThing(c.thing, [rest[1]]); return { why: c.why ?? null }; }
|
|
657
|
+
}
|
|
658
|
+
// A module or namespace bound by an import, with the longest prefix first (`a.b.f` for Python's `import a.b`).
|
|
659
|
+
for (let k = Math.min(path.length - 1, 4); k >= 1; k--) {
|
|
660
|
+
const b = mod.bindings.get(path.slice(0, k).join('.'));
|
|
661
|
+
if (!b) continue;
|
|
662
|
+
const target = b.thing ? { thing: b.thing } : b.symbol ? symbolIn(b.files, b.symbol) : { module: b.files };
|
|
663
|
+
if (!target) return { why: `${path.slice(0, k).join('.')} was not found in ${b.spec ?? 'its module'}`, worth: true };
|
|
664
|
+
return walkTail(target, path.slice(k), isNew, b.spec ?? path.slice(0, k).join('.'));
|
|
665
|
+
}
|
|
666
|
+
if (!rest.length) {
|
|
667
|
+
const b = mod.bindings.get(head);
|
|
668
|
+
if (b) {
|
|
669
|
+
const target = b.thing ? { thing: b.thing } : b.symbol ? symbolIn(b.files, b.symbol) : null;
|
|
670
|
+
if (!target) return { why: b.symbol ? `${b.spec ?? 'its module'} has no ${b.symbol}` : null, worth: !!b.symbol };
|
|
671
|
+
return walkTail(target, [], isNew);
|
|
672
|
+
}
|
|
673
|
+
// Go: another file of the same package. Python/Go: names a star import brings in.
|
|
674
|
+
if (lang === 'go') {
|
|
675
|
+
// (A test file sees the package's other files; a non-test file never sees a test file.)
|
|
676
|
+
const same = (goDirs.get(dirOf(file)) || []).filter((f) => f !== file && (/_test\.go$/.test(file) || !/_test\.go$/.test(f)));
|
|
677
|
+
const hit = same.map((f) => topOf(f).get(head)).filter((x) => x?.length === 1).map((x) => x[0]);
|
|
678
|
+
if (hit.length === 1) return { member: hit[0] };
|
|
679
|
+
const th = same.map((f) => thingNamed(f, head)).find(Boolean);
|
|
680
|
+
if (th) return { why: null };
|
|
681
|
+
}
|
|
682
|
+
for (const fs of mod.star) { const got = symbolIn(fs, head); if (got?.member) return { member: got.member }; if (got?.thing) return viaThing(got.thing, [], isNew); }
|
|
683
|
+
// Kotlin/Java: a class's constructor written `OrderService(…)` / `new OrderService(…)`; a Kotlin top-level function in the same package.
|
|
684
|
+
if (/^[A-Z]/.test(head) && (isNew || lang === 'kotlin' || lang === 'python' || lang === 'php' || lang === 'csharp' || lang === 'java')) {
|
|
685
|
+
const c = classByName(file, head);
|
|
686
|
+
if (c.thing) return viaThing(c.thing, [], true);
|
|
687
|
+
}
|
|
688
|
+
if (lang === 'kotlin') {
|
|
689
|
+
const hit = pkgFiles((pkgOf.get(file) || [''])[0]).filter((f) => f !== file && langOf.get(f) === 'kotlin').map((f) => topOf(f).get(head)).filter((x) => x?.length === 1).map((x) => x[0]);
|
|
690
|
+
if (hit.length === 1) return { member: hit[0] };
|
|
691
|
+
}
|
|
692
|
+
return { why: null };
|
|
693
|
+
}
|
|
694
|
+
// `OrderService.find(…)`: a class's own method; `orders.place(…)`: a name with a declared type.
|
|
695
|
+
if (rest.length === 1) {
|
|
696
|
+
if (/^[A-Z]/.test(head)) { const c = classByName(file, head); if (c.thing) return viaThing(c.thing, rest); if (c.why) return { why: c.why }; }
|
|
697
|
+
const type = typeOf(file, member, head);
|
|
698
|
+
if (type) { const c = classByName(file, type); if (c.thing) return viaThing(c.thing, rest); return { why: c.why ?? null }; }
|
|
699
|
+
}
|
|
700
|
+
// Ruby `Billing::Charge.run`, PHP `\App\Services\Orders::find`: the last class name in the path.
|
|
701
|
+
if (rest.length >= 2 && (lang === 'ruby' || lang === 'php')) {
|
|
702
|
+
const cls = path.at(-2);
|
|
703
|
+
if (/^[A-Z]/.test(cls)) { const c = classByName(file, cls); if (c.thing) return viaThing(c.thing, [path.at(-1)]); }
|
|
704
|
+
}
|
|
705
|
+
// Rust: `crate::orders::place(…)`.
|
|
706
|
+
if (lang === 'rust' && /^(crate|super|self)$/.test(head) && rest.length >= 2) {
|
|
707
|
+
const r = rustModule(file, path.slice(0, -1).join('::'));
|
|
708
|
+
if (r.files?.length) { const got = symbolIn(r.files, path.at(-1)); if (got?.member) return { member: got.member }; return { why: `${path.slice(0, -1).join('::')} has no ${path.at(-1)}`, worth: true }; }
|
|
709
|
+
}
|
|
710
|
+
return { why: null };
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
// ── Routes and listeners ──
|
|
714
|
+
const routes = [];
|
|
715
|
+
for (const m of model.members) {
|
|
716
|
+
if (!m.route) continue;
|
|
717
|
+
const r = m.route.match(/^(\w+)\s+(.*)$/);
|
|
718
|
+
if (r) routes.push({ member: m, method: r[1].toUpperCase(), segs: routeSegs(r[2]), path: r[2] });
|
|
719
|
+
}
|
|
720
|
+
// Next.js route files: app/api/orders/[id]/route.ts exports GET, POST, …; pages/api/orders.ts handles any method.
|
|
721
|
+
for (const m of model.members) {
|
|
722
|
+
if (m.route || m.owner) continue;
|
|
723
|
+
const app = m.file.match(/(?:^|\/)app\/(.*?)\/?route\.(?:ts|js|tsx|jsx|mjs)$/);
|
|
724
|
+
if (app && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(m.name)) routes.push({ member: m, method: m.name, segs: routeSegs('/' + app[1].replace(/\([^)]*\)\/?/g, '')), path: '/' + app[1] });
|
|
725
|
+
const pages = m.file.match(/(?:^|\/)pages\/(api\/.*?)(?:\/index)?\.(?:ts|js|tsx|jsx)$/);
|
|
726
|
+
if (pages && topOf(m.file).get(m.name)?.[0] === m && jsExp(m.file).def === m.name) routes.push({ member: m, method: 'ANY', segs: routeSegs('/' + pages[1]), path: '/' + pages[1] });
|
|
727
|
+
}
|
|
728
|
+
const listeners = new Map();
|
|
729
|
+
const addListener = (name, member, how) => { if (!member) return; const l = listeners.get(name) ?? listeners.set(name, []).get(name); if (!l.some((x) => x.member === member)) l.push({ member, how }); };
|
|
730
|
+
for (const f of model.files) {
|
|
731
|
+
const src = sources.get(f.path);
|
|
732
|
+
if (!src || !/\.(on|once|addListener|subscribe|consume|listen|handle)\(|@\w+(Listener|Pattern|Event|Handler)\b|@Subscribe|@Consumer|new\s+Worker\(/.test(src)) continue;
|
|
733
|
+
const ms = membersOf.get(f.path) || [];
|
|
734
|
+
for (const m of src.matchAll(EVENT_SUBSCRIBE)) {
|
|
735
|
+
if (GENERIC_EVENTS.has(m[3])) continue;
|
|
736
|
+
const line = lineAt(src, m.index);
|
|
737
|
+
// The handler: a function written right there (an item since it has no name of its own), or one named.
|
|
738
|
+
const handler = m[4] ? (ms.find((x) => x.name === m[4].replace(/^(this|self)\./, '') && !x.callback) ?? null) : ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0];
|
|
739
|
+
addListener(m[3], handler, m[1]);
|
|
740
|
+
}
|
|
741
|
+
for (const m of src.matchAll(/new\s+Worker\(\s*(['"`])([^'"`]+)\1\s*,/g)) {
|
|
742
|
+
const line = lineAt(src, m.index);
|
|
743
|
+
addListener(m[2], ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0], 'worker');
|
|
744
|
+
}
|
|
745
|
+
for (const m of src.matchAll(EVENT_DECORATOR)) {
|
|
746
|
+
const line = lineAt(src, m.index);
|
|
747
|
+
addListener(m[3], ms.filter((x) => x.lines[0] > line && x.lines[0] <= line + 6).sort((a, b) => a.lines[0] - b.lines[0])[0], m[1]);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
// `const emails = new Queue('emails')` then `emails.add(…)`: the queue's name.
|
|
751
|
+
const queueNames = new Map();
|
|
752
|
+
for (const f of model.files) {
|
|
753
|
+
const src = sources.get(f.path);
|
|
754
|
+
if (!src || !/new\s+Queue\(/.test(src)) continue;
|
|
755
|
+
for (const m of src.matchAll(/(?:\b(?:const|let|var)\s+|this\.)([\w$]+)\s*=\s*new\s+Queue\(\s*(['"`])([^'"`]+)\2/g)) queueNames.set(`${f.path}|${m[1]}`, m[3]);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// ── Walk every step of every member ──
|
|
759
|
+
const seen = new Set();
|
|
760
|
+
const link = (l) => { const k = `${l.from}|${l.to}|${l.node}|${l.kind}`; if (seen.has(k)) return; seen.add(k); model.links.push(l); };
|
|
761
|
+
for (const l of model.links) seen.add(`${l.from}|${l.to}|${l.node}|${l.kind}`);
|
|
762
|
+
const stats = { calls: 0, crossFile: 0, services: 0 };
|
|
763
|
+
for (const m of model.members) {
|
|
764
|
+
for (const nd of m.flow.nodes) {
|
|
765
|
+
if (!nd.expr) continue;
|
|
766
|
+
const calls = callsIn(nd.expr);
|
|
767
|
+
if (!calls.length) continue;
|
|
768
|
+
const http = HTTP_SAYS.exec(nd.text || '');
|
|
769
|
+
let httpDone = false;
|
|
770
|
+
for (const call of calls) {
|
|
771
|
+
const path = calleePath(call.callee);
|
|
772
|
+
if (!path) continue;
|
|
773
|
+
stats.calls++;
|
|
774
|
+
// An HTTP request the library catalog recognized: link it to the route that handles it.
|
|
775
|
+
if (http && !httpDone && /^(fetch|get|post|put|patch|delete|head|request|Get|Post|Put|Patch|Delete|Head|NewRequest|NewRequestWithContext|\w+Async|\w+ForObject|\w+ForEntity|exchange)$/.test(path.at(-1))) {
|
|
776
|
+
httpDone = true;
|
|
777
|
+
const method = http[1];
|
|
778
|
+
const u = urlOf(urlArg(call));
|
|
779
|
+
const service = u.path ? `${method} ${u.path}` : `${method} request`;
|
|
780
|
+
if (!u.segs) { notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: service, why: u.why }); continue; }
|
|
781
|
+
const matches = routes.map((r) => ({ r, score: (r.method === method || r.method === 'ANY' || r.method === 'ALL') ? segsMatch(r.segs, u.segs) : -1 })).filter((x) => x.score >= 0);
|
|
782
|
+
const best = Math.max(-1, ...matches.map((x) => x.score));
|
|
783
|
+
const top = matches.filter((x) => x.score === best);
|
|
784
|
+
if (top.length === 1) {
|
|
785
|
+
const r = top[0].r;
|
|
786
|
+
link({ from: m.id, to: r.member.id, kind: 'sends-to', node: nd.id, file: r.member.file, line: nd.line ?? null, method, path: u.path, route: r.member.route ?? `${r.method} ${r.path}`, ...(r.member.file !== m.file ? { crossFile: true } : {}) });
|
|
787
|
+
stats.services++;
|
|
788
|
+
} else notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: service, why: top.length ? `${top.length} routes in this repo match ${method} ${u.path}` : `no route in this repo handles ${method} ${u.path}` });
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
// An event or a message: link it to the code that listens for the same name.
|
|
792
|
+
const last = path.at(-1);
|
|
793
|
+
const queue = path.length === 2 && /^(add|addBulk)$/.test(last) ? queueNames.get(`${m.file}|${path[0]}`) : null;
|
|
794
|
+
if (queue || (EVENT_PUBLISH.test(last) && call.args?.[0]?.kind === 'literal' && call.args[0].type === 'text')) {
|
|
795
|
+
const name = queue ?? String(call.args[0].value);
|
|
796
|
+
if (GENERIC_EVENTS.has(name)) continue;
|
|
797
|
+
const ls = (listeners.get(name) || []).filter((x) => x.member.id !== m.id);
|
|
798
|
+
for (const x of ls) { link({ from: m.id, to: x.member.id, kind: 'sends-to', node: nd.id, file: x.member.file, line: nd.line ?? null, event: name, ...(x.member.file !== m.file ? { crossFile: true } : {}) }); stats.services++; }
|
|
799
|
+
if (!ls.length && (queue || /^(publish|publishEvent|sendToQueue|enqueue|basic_publish|produce)$/.test(last))) notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: `${queue ? 'message on' : 'event'} ${name}`, why: `nothing in this repo listens for ${name}` });
|
|
800
|
+
if (ls.length) continue;
|
|
801
|
+
}
|
|
802
|
+
// A task sent to a worker: `send_email.delay(…)` (Celery) runs send_email.
|
|
803
|
+
let p = path, isNew = !!call.new, task = false;
|
|
804
|
+
if (p.length >= 2 && /^(delay|apply_async|send|enqueue|perform_async|perform_later)$/.test(last) && langOf.get(m.file) !== 'go') { p = p.slice(0, -1); task = /^(delay|apply_async|perform_async|perform_later)$/.test(last); }
|
|
805
|
+
argc = (call.args || []).length;
|
|
806
|
+
const r = resolve(m.file, p, isNew, m);
|
|
807
|
+
// (Same-file calls the name match missed, such as `library.can_borrow()` through `library = Library()`,
|
|
808
|
+
// link the same way, without `crossFile`.)
|
|
809
|
+
if (r.member && r.member.id !== m.id) {
|
|
810
|
+
const cross = r.member.file !== m.file;
|
|
811
|
+
link({ from: m.id, to: r.member.id, kind: task ? 'sends-to' : 'uses', node: nd.id, file: r.member.file, line: nd.line ?? null, ...(cross ? { crossFile: true } : {}), ...(task ? { task: r.member.name } : {}) });
|
|
812
|
+
if (!nd.uses) { nd.uses = r.member.id; if (cross) nd.usesFile = r.member.file; }
|
|
813
|
+
if (cross) stats.crossFile++;
|
|
814
|
+
} else if (!r.member && r.worth) notLinked.push({ from: m.id, node: nd.id, file: m.file, line: nd.line ?? null, call: path.join('.'), why: r.why });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
model.notLinked = notLinked;
|
|
819
|
+
return model;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// ── The app's map: which areas call which ────────────────────────────────────────────────────────────
|
|
823
|
+
|
|
824
|
+
/** An area: a file's folder, at most two levels deep ("src/orders"), or "(top)" for files at the top. */
|
|
825
|
+
export function areaOf(file) {
|
|
826
|
+
const d = dirOf(file).split('/').filter(Boolean);
|
|
827
|
+
return d.length ? d.slice(0, 2).join('/') : '(top)';
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** Which areas call which: [{ from, to, calls, sends, examples }] from the model's cross-file and service links. */
|
|
831
|
+
export function callsSummary(model) {
|
|
832
|
+
const byId = new Map(model.members.map((m) => [m.id, m]));
|
|
833
|
+
const pairs = new Map();
|
|
834
|
+
for (const l of model.links) {
|
|
835
|
+
if (!l.crossFile && l.kind !== 'sends-to') continue;
|
|
836
|
+
const a = byId.get(l.from), b = byId.get(l.to);
|
|
837
|
+
if (!a || !b) continue;
|
|
838
|
+
const from = areaOf(a.file), to = areaOf(b.file);
|
|
839
|
+
const k = `${from}\u0000${to}`;
|
|
840
|
+
const p = pairs.get(k) ?? pairs.set(k, { from, to, calls: 0, sends: 0, examples: [] }).get(k);
|
|
841
|
+
if (l.kind === 'sends-to') p.sends++; else p.calls++;
|
|
842
|
+
if (p.examples.length < 3) p.examples.push({ from: a.id, to: b.id, says: l.kind === 'sends-to' ? `${a.label} sends ${l.method ? `${l.method} ${l.path}` : l.event ? `the event ${l.event}` : `a task`} to ${b.label}` : `${a.label} calls ${b.label}` });
|
|
843
|
+
}
|
|
844
|
+
return [...pairs.values()].sort((x, y) => (y.calls + y.sends) - (x.calls + x.sends) || x.from.localeCompare(y.from) || x.to.localeCompare(y.to));
|
|
845
|
+
}
|