changeguard 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +440 -0
- package/LICENSE +202 -0
- package/LICENSE-PROPRIETARY +94 -0
- package/README.md +317 -2
- package/SECURITY.md +40 -0
- package/data/changes/openai.seed.json +87 -0
- package/data/changes/shopify.seed.json +42 -0
- package/data/changes/stripe.seed.json +60 -0
- package/data/changes/supabase.seed.json +56 -0
- package/data/changes/twilio.seed.json +63 -0
- package/data/openapi/openai/meta.json +9 -0
- package/data/openapi/openai/new.json +24 -0
- package/data/openapi/openai/old.json +68 -0
- package/data/providers/openai.json +60 -0
- package/data/providers/shopify.json +52 -0
- package/data/providers/stripe.json +57 -0
- package/data/providers/supabase.json +56 -0
- package/data/providers/twilio.json +57 -0
- package/dist/analyze/go-analyzer.js +343 -0
- package/dist/analyze/index.js +77 -0
- package/dist/analyze/js-analyzer.js +380 -0
- package/dist/analyze/parser.js +78 -0
- package/dist/analyze/py-analyzer.js +313 -0
- package/dist/analyze/rules.js +1 -0
- package/dist/analyze/ts-utils.js +62 -0
- package/dist/cli.js +335 -0
- package/dist/codemod/apply.js +159 -0
- package/dist/config.js +121 -0
- package/dist/deps/manifests.js +145 -0
- package/dist/github/api.js +136 -0
- package/dist/github/auth.js +54 -0
- package/dist/impact/engine.js +384 -0
- package/dist/ingest/canonical.js +52 -0
- package/dist/ingest/changelog-html.js +63 -0
- package/dist/ingest/feed-client.js +99 -0
- package/dist/ingest/feed-keys.js +198 -0
- package/dist/ingest/feed.js +178 -0
- package/dist/ingest/github-releases.js +59 -0
- package/dist/ingest/note-parser.js +274 -0
- package/dist/ingest/openapi-diff.js +217 -0
- package/dist/ingest/store.js +181 -0
- package/dist/llm/explanation.js +273 -0
- package/dist/mcp/format.js +116 -0
- package/dist/mcp/index.js +29 -0
- package/dist/mcp/protocol.js +36 -0
- package/dist/mcp/server.js +110 -0
- package/dist/mcp/standalone.js +12 -0
- package/dist/mcp/tools.js +189 -0
- package/dist/notify/index.js +174 -0
- package/dist/providers/registry.js +215 -0
- package/dist/report/html.js +194 -0
- package/dist/report/markdown.js +90 -0
- package/dist/report/pr-draft.js +37 -0
- package/dist/scan.js +168 -0
- package/dist/source/repo-source.js +100 -0
- package/dist/types.js +6 -0
- package/dist/util/http.js +40 -0
- package/dist/util/logger.js +61 -0
- package/dist/util/metrics.js +99 -0
- package/dist/util/request-context.js +22 -0
- package/dist/util/task-queue.js +69 -0
- package/dist/util/versions.js +52 -0
- package/fixtures/sample-repo/cmd/billing/main.go +47 -0
- package/fixtures/sample-repo/go.mod +12 -0
- package/fixtures/sample-repo/package.json +17 -0
- package/fixtures/sample-repo/requirements.txt +7 -0
- package/fixtures/sample-repo/services/ai.py +65 -0
- package/fixtures/sample-repo/src/billing.ts +68 -0
- package/package.json +84 -4
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { providerForPackage } from '../providers/registry.js';
|
|
2
|
+
import { chainSegments, isStringLiteral, sameNode, siteId, snippet, stringValue, walk, } from './ts-utils.js';
|
|
3
|
+
function objectKeys(node, prefix = '') {
|
|
4
|
+
const keys = [];
|
|
5
|
+
const literals = new Map();
|
|
6
|
+
if (!node)
|
|
7
|
+
return { keys, literals };
|
|
8
|
+
const pushLit = (key, value) => {
|
|
9
|
+
if (isStringLiteral(value)) {
|
|
10
|
+
const list = literals.get(key) ?? [];
|
|
11
|
+
list.push(stringValue(value));
|
|
12
|
+
literals.set(key, list);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
for (const pair of node.children.filter((c) => c.type === 'pair' ||
|
|
16
|
+
c.type === 'shorthand_property_identifier' ||
|
|
17
|
+
c.type === 'shorthand_property_identifier_pattern')) {
|
|
18
|
+
let key;
|
|
19
|
+
let value;
|
|
20
|
+
if (pair.type === 'pair') {
|
|
21
|
+
key = pair.childForFieldName('key')?.text;
|
|
22
|
+
value = pair.childForFieldName('value') ?? undefined;
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
key = pair.text;
|
|
26
|
+
}
|
|
27
|
+
if (!key)
|
|
28
|
+
continue;
|
|
29
|
+
const dotted = prefix ? `${prefix}.${key}` : key;
|
|
30
|
+
keys.push(dotted);
|
|
31
|
+
if (value)
|
|
32
|
+
pushLit(dotted, value);
|
|
33
|
+
if (value?.type === 'object') {
|
|
34
|
+
const nested = objectKeys(value, dotted);
|
|
35
|
+
keys.push(...nested.keys);
|
|
36
|
+
for (const [k, vals] of nested.literals)
|
|
37
|
+
literals.set(k, vals);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { keys, literals };
|
|
41
|
+
}
|
|
42
|
+
function callArguments(n) {
|
|
43
|
+
const list = n.childForFieldName('arguments');
|
|
44
|
+
if (!list)
|
|
45
|
+
return [];
|
|
46
|
+
return list.children.filter((c) => !['(', ')', ',', 'comment'].includes(c.type));
|
|
47
|
+
}
|
|
48
|
+
function mergeArgs(callNodes) {
|
|
49
|
+
const keys = [];
|
|
50
|
+
const lit = new Map();
|
|
51
|
+
for (const c of callNodes) {
|
|
52
|
+
const args = callArguments(c);
|
|
53
|
+
const ok = objectKeys(args.find((a) => a.type === 'object'));
|
|
54
|
+
keys.push(...ok.keys);
|
|
55
|
+
for (const [k, vals] of ok.literals)
|
|
56
|
+
lit.set(k, vals);
|
|
57
|
+
args.forEach((a, i) => {
|
|
58
|
+
if (isStringLiteral(a)) {
|
|
59
|
+
const k = `$${i}`;
|
|
60
|
+
lit.set(k, [...(lit.get(k) ?? []), stringValue(a)]);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return { keys: [...new Set(keys)], literals: Object.fromEntries(lit) };
|
|
65
|
+
}
|
|
66
|
+
function unwrapAwait(node) {
|
|
67
|
+
return node.type === 'await_expression' ? (node.childForFieldName('argument') ?? node) : node;
|
|
68
|
+
}
|
|
69
|
+
export function analyzeJavaScript(root, code, file, language, index) {
|
|
70
|
+
const rules = index.rules.javascript;
|
|
71
|
+
const active = new Set();
|
|
72
|
+
const bindings = new Map();
|
|
73
|
+
const instances = new Map();
|
|
74
|
+
const sites = [];
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
const ruleForModule = (source) => {
|
|
77
|
+
const pid = providerForPackage('npm', source);
|
|
78
|
+
if (!pid)
|
|
79
|
+
return undefined;
|
|
80
|
+
active.add(pid);
|
|
81
|
+
return rules.find((r) => r.providerId === pid);
|
|
82
|
+
};
|
|
83
|
+
const bind = (local, rule, factory) => {
|
|
84
|
+
bindings.set(local, {
|
|
85
|
+
providerId: rule.providerId,
|
|
86
|
+
factory: factory || rule.factories.includes(local),
|
|
87
|
+
});
|
|
88
|
+
};
|
|
89
|
+
const bindImport = (source, clause) => {
|
|
90
|
+
const rule = ruleForModule(source);
|
|
91
|
+
if (!rule)
|
|
92
|
+
return;
|
|
93
|
+
// tree-sitter-typescript does NOT expose the default-import identifier as a field.
|
|
94
|
+
const def = clause.childForFieldName('name') ??
|
|
95
|
+
clause.children.find((c) => c.type === 'identifier') ??
|
|
96
|
+
null;
|
|
97
|
+
if (def?.type === 'identifier')
|
|
98
|
+
bind(def.text, rule, rule.factories.includes(def.text));
|
|
99
|
+
const ns = clause.children.find((c) => c.type === 'namespace_import');
|
|
100
|
+
if (ns) {
|
|
101
|
+
const id = ns.childForFieldName('name');
|
|
102
|
+
if (id)
|
|
103
|
+
bind(id.text, rule, false);
|
|
104
|
+
}
|
|
105
|
+
const named = clause.children.find((c) => c.type === 'named_imports');
|
|
106
|
+
if (named) {
|
|
107
|
+
for (const spec of named.children.filter((c) => c.type === 'import_specifier')) {
|
|
108
|
+
const imported = spec.childForFieldName('name') ?? spec.children.find((c) => c.type === 'identifier');
|
|
109
|
+
const alias = spec.childForFieldName('alias');
|
|
110
|
+
const local = (alias ?? imported)?.text;
|
|
111
|
+
if (local && imported)
|
|
112
|
+
bind(local, rule, rule.factories.includes(imported.text));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const innerRequire = (n) => {
|
|
117
|
+
if (!n || n.type !== 'call_expression')
|
|
118
|
+
return undefined;
|
|
119
|
+
const fn = n.childForFieldName('function');
|
|
120
|
+
if (fn?.type === 'identifier' && fn.text === 'require')
|
|
121
|
+
return n;
|
|
122
|
+
if (fn?.type === 'call_expression')
|
|
123
|
+
return innerRequire(fn);
|
|
124
|
+
return undefined;
|
|
125
|
+
};
|
|
126
|
+
// --- pass 1: imports & requires ---
|
|
127
|
+
for (const node of walk(root)) {
|
|
128
|
+
if (node.type === 'import_statement') {
|
|
129
|
+
const src = node.childForFieldName('source');
|
|
130
|
+
const clause = node.childForFieldName('clause') ?? node.children.find((c) => c.type === 'import_clause');
|
|
131
|
+
if (src && clause && isStringLiteral(src))
|
|
132
|
+
bindImport(stringValue(src), clause);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (node.type !== 'variable_declarator')
|
|
136
|
+
continue;
|
|
137
|
+
const value = node.childForFieldName('value');
|
|
138
|
+
const req = innerRequire(value);
|
|
139
|
+
if (!req)
|
|
140
|
+
continue;
|
|
141
|
+
const arg = req.childForFieldName('arguments')?.children.find((c) => isStringLiteral(c));
|
|
142
|
+
if (!arg)
|
|
143
|
+
continue;
|
|
144
|
+
const rule = ruleForModule(stringValue(arg));
|
|
145
|
+
if (!rule)
|
|
146
|
+
continue;
|
|
147
|
+
const name = node.childForFieldName('name');
|
|
148
|
+
if (name?.type === 'identifier') {
|
|
149
|
+
bind(name.text, rule, !sameNode(value, req));
|
|
150
|
+
}
|
|
151
|
+
else if (name?.type === 'object_pattern') {
|
|
152
|
+
for (const p of name.children) {
|
|
153
|
+
if (p.type === 'shorthand_property_identifier_pattern' ||
|
|
154
|
+
p.type === 'shorthand_property_identifier') {
|
|
155
|
+
bind(p.text, rule, rule.factories.includes(p.text));
|
|
156
|
+
}
|
|
157
|
+
else if (p.type === 'pair_pattern' || p.type === 'pair') {
|
|
158
|
+
const k = p.childForFieldName('key');
|
|
159
|
+
const v = p.childForFieldName('value') ?? p.childForFieldName('pattern');
|
|
160
|
+
if (k && v)
|
|
161
|
+
bind(v.text, rule, rule.factories.includes(k.text));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// --- pass 2: factory propagation ---
|
|
167
|
+
const calleeProvider = (callee) => {
|
|
168
|
+
if (callee.type === 'identifier') {
|
|
169
|
+
return bindings.get(callee.text)?.factory ? bindings.get(callee.text).providerId : undefined;
|
|
170
|
+
}
|
|
171
|
+
const segs = chainSegments(callee);
|
|
172
|
+
if (!segs)
|
|
173
|
+
return undefined;
|
|
174
|
+
const [r, ...rest] = segs;
|
|
175
|
+
const b = r ? bindings.get(r) : undefined;
|
|
176
|
+
if (!b)
|
|
177
|
+
return undefined;
|
|
178
|
+
const rule = rules.find((x) => x.providerId === b.providerId);
|
|
179
|
+
if (rest.length === 1 && rule?.factories.includes(rest[0]))
|
|
180
|
+
return b.providerId;
|
|
181
|
+
return undefined;
|
|
182
|
+
};
|
|
183
|
+
for (const node of walk(root)) {
|
|
184
|
+
if (node.type !== 'variable_declarator')
|
|
185
|
+
continue;
|
|
186
|
+
const name = node.childForFieldName('name');
|
|
187
|
+
let value = node.childForFieldName('value');
|
|
188
|
+
if (!name || name.type !== 'identifier' || !value)
|
|
189
|
+
continue;
|
|
190
|
+
value = unwrapAwait(value);
|
|
191
|
+
let pid;
|
|
192
|
+
if (value.type === 'new_expression') {
|
|
193
|
+
const ctor = value.childForFieldName('constructor') ??
|
|
194
|
+
value.children.find((c) => c.type === 'identifier' || c.type === 'member_expression');
|
|
195
|
+
pid = ctor ? calleeProvider(ctor) : undefined;
|
|
196
|
+
}
|
|
197
|
+
else if (value.type === 'call_expression') {
|
|
198
|
+
const fn = value.childForFieldName('function');
|
|
199
|
+
pid = fn ? calleeProvider(fn) : undefined;
|
|
200
|
+
}
|
|
201
|
+
if (pid)
|
|
202
|
+
instances.set(name.text, pid);
|
|
203
|
+
}
|
|
204
|
+
const rootOf = (id) => instances.get(id) ?? bindings.get(id)?.providerId;
|
|
205
|
+
const emit = (s) => {
|
|
206
|
+
const key = `${s.file}:${s.line}:${s.path}:${s.receiver}`;
|
|
207
|
+
if (seen.has(key))
|
|
208
|
+
return;
|
|
209
|
+
seen.add(key);
|
|
210
|
+
sites.push({ id: siteId(s.file, s.line - 1, s.path), ...s });
|
|
211
|
+
};
|
|
212
|
+
const pkgOf = (pid) => rules.find((r) => r.providerId === pid)?.packageName ?? pid;
|
|
213
|
+
// --- pass 3: member-call chains ---
|
|
214
|
+
for (const node of walk(root)) {
|
|
215
|
+
if (node.type !== 'call_expression')
|
|
216
|
+
continue;
|
|
217
|
+
// Suppress intermediate calls of a.b().c() chains; the terminal call wins.
|
|
218
|
+
if (node.parent?.type === 'member_expression' &&
|
|
219
|
+
sameNode(node.parent.childForFieldName('object'), node) &&
|
|
220
|
+
node.parent.parent?.type === 'call_expression') {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const chain = [];
|
|
224
|
+
const callNodes = [];
|
|
225
|
+
let cur = node;
|
|
226
|
+
while (cur && cur.type === 'call_expression') {
|
|
227
|
+
const fn = cur.childForFieldName('function');
|
|
228
|
+
if (!fn || (fn.type !== 'member_expression' && fn.type !== 'subscript_expression'))
|
|
229
|
+
break;
|
|
230
|
+
const prop = fn.childForFieldName('property');
|
|
231
|
+
if (prop) {
|
|
232
|
+
chain.unshift(prop.type === 'property_identifier' || prop.type === 'identifier'
|
|
233
|
+
? prop.text
|
|
234
|
+
: isStringLiteral(prop)
|
|
235
|
+
? stringValue(prop)
|
|
236
|
+
: prop.text);
|
|
237
|
+
}
|
|
238
|
+
callNodes.unshift(cur);
|
|
239
|
+
let obj = fn.childForFieldName('object');
|
|
240
|
+
// descend pure member chain: a.b.c() -> [b, c]; calls stay in outer loop
|
|
241
|
+
while (obj && (obj.type === 'member_expression' || obj.type === 'subscript_expression')) {
|
|
242
|
+
const p2 = obj.childForFieldName('property');
|
|
243
|
+
if (p2) {
|
|
244
|
+
chain.unshift(p2.type === 'property_identifier' || p2.type === 'identifier'
|
|
245
|
+
? p2.text
|
|
246
|
+
: isStringLiteral(p2)
|
|
247
|
+
? stringValue(p2)
|
|
248
|
+
: p2.text);
|
|
249
|
+
}
|
|
250
|
+
obj = obj.childForFieldName('object');
|
|
251
|
+
}
|
|
252
|
+
cur = obj;
|
|
253
|
+
}
|
|
254
|
+
if (cur &&
|
|
255
|
+
cur.type === 'identifier' &&
|
|
256
|
+
chain.length > 0 &&
|
|
257
|
+
active.has(rootOf(cur.text) ?? '')) {
|
|
258
|
+
const pid = rootOf(cur.text);
|
|
259
|
+
const args = mergeArgs(callNodes);
|
|
260
|
+
emit({
|
|
261
|
+
file,
|
|
262
|
+
language,
|
|
263
|
+
line: node.startPosition.row + 1,
|
|
264
|
+
endLine: node.endPosition.row + 1,
|
|
265
|
+
package: pkgOf(pid),
|
|
266
|
+
providerId: pid,
|
|
267
|
+
path: chain.join('.'),
|
|
268
|
+
receiver: [cur.text, ...chain].join('.'),
|
|
269
|
+
callText: snippet(code, node.startPosition.row),
|
|
270
|
+
argumentKeys: args.keys,
|
|
271
|
+
argumentLiterals: args.literals,
|
|
272
|
+
memberRefs: [],
|
|
273
|
+
});
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const http = detectHttp(node, cur, chain, callNodes, index);
|
|
277
|
+
if (http) {
|
|
278
|
+
let pathname = '/';
|
|
279
|
+
try {
|
|
280
|
+
pathname = new URL(http.url).pathname;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
/* keep / */
|
|
284
|
+
}
|
|
285
|
+
emit({
|
|
286
|
+
file,
|
|
287
|
+
language,
|
|
288
|
+
line: node.startPosition.row + 1,
|
|
289
|
+
package: '(http)',
|
|
290
|
+
providerId: http.providerId,
|
|
291
|
+
path: pathname,
|
|
292
|
+
receiver: http.url,
|
|
293
|
+
callText: snippet(code, node.startPosition.row),
|
|
294
|
+
argumentKeys: [],
|
|
295
|
+
argumentLiterals: { $0: [http.url] },
|
|
296
|
+
memberRefs: [],
|
|
297
|
+
http: { method: http.method, url: http.url },
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// --- pass 4: enum / constant member references ---
|
|
302
|
+
for (const node of walk(root)) {
|
|
303
|
+
if (node.type !== 'member_expression' && node.type !== 'subscript_expression')
|
|
304
|
+
continue;
|
|
305
|
+
const parent = node.parent;
|
|
306
|
+
if (parent?.type === 'member_expression' || parent?.type === 'subscript_expression')
|
|
307
|
+
continue;
|
|
308
|
+
if (parent?.type === 'call_expression' &&
|
|
309
|
+
sameNode(parent.childForFieldName('function'), node)) {
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
const segs = chainSegments(node);
|
|
313
|
+
if (!segs)
|
|
314
|
+
continue;
|
|
315
|
+
const [r, ...rest] = segs;
|
|
316
|
+
if (!r || rest.length === 0)
|
|
317
|
+
continue;
|
|
318
|
+
const pid = rootOf(r);
|
|
319
|
+
if (!pid || !active.has(pid))
|
|
320
|
+
continue;
|
|
321
|
+
const ref = rest.join('.');
|
|
322
|
+
emit({
|
|
323
|
+
file,
|
|
324
|
+
language,
|
|
325
|
+
line: node.startPosition.row + 1,
|
|
326
|
+
package: pkgOf(pid),
|
|
327
|
+
providerId: pid,
|
|
328
|
+
path: ref,
|
|
329
|
+
receiver: segs.join('.'),
|
|
330
|
+
callText: snippet(code, node.startPosition.row),
|
|
331
|
+
argumentKeys: [],
|
|
332
|
+
argumentLiterals: {},
|
|
333
|
+
memberRefs: [ref],
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
return sites;
|
|
337
|
+
}
|
|
338
|
+
const HTTP_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'request']);
|
|
339
|
+
function detectHttp(node, root, chain, callNodes, index) {
|
|
340
|
+
if (!root)
|
|
341
|
+
return undefined;
|
|
342
|
+
const hostFor = (raw) => {
|
|
343
|
+
let host;
|
|
344
|
+
try {
|
|
345
|
+
host = new URL(raw).hostname.toLowerCase();
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
return undefined;
|
|
349
|
+
}
|
|
350
|
+
const hit = index.hosts.find((h) => host === h.suffix || host.endsWith(`.${h.suffix}`));
|
|
351
|
+
return hit?.providerId;
|
|
352
|
+
};
|
|
353
|
+
if (root.type === 'identifier' && root.text === 'fetch' && chain.length === 0) {
|
|
354
|
+
const args = callArguments(node);
|
|
355
|
+
const urlArg = args.find(isStringLiteral);
|
|
356
|
+
if (!urlArg)
|
|
357
|
+
return undefined;
|
|
358
|
+
const pid = hostFor(stringValue(urlArg));
|
|
359
|
+
if (!pid)
|
|
360
|
+
return undefined;
|
|
361
|
+
const opts = args.find((a) => a.type === 'object');
|
|
362
|
+
const methodPair = opts?.children.find((c) => c.type === 'pair' && c.childForFieldName('key')?.text === 'method');
|
|
363
|
+
const method = methodPair?.childForFieldName('value')?.text.replace(/['"`]/g, '').toUpperCase() ?? 'GET';
|
|
364
|
+
return { method, url: stringValue(urlArg), providerId: pid };
|
|
365
|
+
}
|
|
366
|
+
if (root.type === 'identifier' && root.text === 'axios' && chain.length === 1) {
|
|
367
|
+
const verb = chain[0].toLowerCase();
|
|
368
|
+
if (!HTTP_VERBS.has(verb))
|
|
369
|
+
return undefined;
|
|
370
|
+
const args = callArguments(callNodes[0] ?? node);
|
|
371
|
+
const urlArg = args.find(isStringLiteral);
|
|
372
|
+
if (!urlArg)
|
|
373
|
+
return undefined;
|
|
374
|
+
const pid = hostFor(stringValue(urlArg));
|
|
375
|
+
if (!pid)
|
|
376
|
+
return undefined;
|
|
377
|
+
return { method: verb.toUpperCase(), url: stringValue(urlArg), providerId: pid };
|
|
378
|
+
}
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* web-tree-sitter lifecycle. WASM grammars are used so there are no native
|
|
3
|
+
* compilation requirements (important for Windows / CI).
|
|
4
|
+
*/
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
7
|
+
let modPromise;
|
|
8
|
+
async function getModule() {
|
|
9
|
+
if (!modPromise) {
|
|
10
|
+
modPromise = import('web-tree-sitter').then((m) => {
|
|
11
|
+
const anyMod = m;
|
|
12
|
+
const Parser = anyMod['Parser'] ??
|
|
13
|
+
anyMod['default']?.['Parser'];
|
|
14
|
+
const Language = anyMod['Language'] ??
|
|
15
|
+
anyMod['default']?.['Language'];
|
|
16
|
+
return { Parser, Language };
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
return modPromise;
|
|
20
|
+
}
|
|
21
|
+
export const EXTENSION_LANGUAGE = {
|
|
22
|
+
js: 'javascript',
|
|
23
|
+
mjs: 'javascript',
|
|
24
|
+
cjs: 'javascript',
|
|
25
|
+
jsx: 'javascript',
|
|
26
|
+
ts: 'javascript',
|
|
27
|
+
mts: 'javascript',
|
|
28
|
+
cts: 'javascript',
|
|
29
|
+
tsx: 'javascript',
|
|
30
|
+
py: 'python',
|
|
31
|
+
pyi: 'python',
|
|
32
|
+
go: 'go',
|
|
33
|
+
};
|
|
34
|
+
const GRAMMAR_FILES = {
|
|
35
|
+
javascript: ['tree-sitter-typescript.wasm', 'tree-sitter-javascript.wasm'],
|
|
36
|
+
python: ['tree-sitter-python.wasm'],
|
|
37
|
+
go: ['tree-sitter-go.wasm'],
|
|
38
|
+
};
|
|
39
|
+
export class AstParser {
|
|
40
|
+
parsers = new Map();
|
|
41
|
+
resolveWasm(file) {
|
|
42
|
+
for (const base of ['tree-sitter-wasms/out/', 'tree-sitter-wasms/']) {
|
|
43
|
+
try {
|
|
44
|
+
return nodeRequire.resolve(`${base}${file}`);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
/* try next */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw new Error(`Cannot locate grammar wasm: ${file}`);
|
|
51
|
+
}
|
|
52
|
+
async forLanguage(language) {
|
|
53
|
+
const cached = this.parsers.get(language);
|
|
54
|
+
if (cached)
|
|
55
|
+
return cached;
|
|
56
|
+
const { Parser, Language: TSLanguage } = await getModule();
|
|
57
|
+
await Parser.init();
|
|
58
|
+
const candidates = GRAMMAR_FILES[language];
|
|
59
|
+
let lastErr;
|
|
60
|
+
for (const file of candidates) {
|
|
61
|
+
try {
|
|
62
|
+
const grammar = await TSLanguage.load(this.resolveWasm(file));
|
|
63
|
+
const parser = new Parser();
|
|
64
|
+
parser.setLanguage(grammar);
|
|
65
|
+
this.parsers.set(language, parser);
|
|
66
|
+
return parser;
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
lastErr = err;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
throw lastErr instanceof Error ? lastErr : new Error(`Failed to load grammar for ${language}`);
|
|
73
|
+
}
|
|
74
|
+
async parse(language, code) {
|
|
75
|
+
const parser = await this.forLanguage(language);
|
|
76
|
+
return parser.parse(code).rootNode;
|
|
77
|
+
}
|
|
78
|
+
}
|