@easbot/codebase 0.3.21 → 0.3.23
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.en.md +46 -0
- package/README.md +46 -0
- package/dist/chunks/{chunk-JWTI3BWI.cjs → chunk-3NTIN3AN.cjs} +19 -19
- package/dist/chunks/chunk-A4EAKE3M.mjs +49 -0
- package/dist/chunks/chunk-DHH2XXGJ.mjs +203 -0
- package/dist/chunks/{chunk-22PKTMO5.mjs → chunk-GWR5LCUV.mjs} +19 -19
- package/dist/chunks/{chunk-BEQN3CKO.cjs → chunk-HRFLFP6O.cjs} +1 -1
- package/dist/chunks/chunk-KU6UZET2.cjs +49 -0
- package/dist/chunks/{chunk-WXWENWCY.mjs → chunk-QQXDOGRV.mjs} +1 -1
- package/dist/chunks/chunk-UAWXUGY5.cjs +47 -0
- package/dist/chunks/chunk-XXH7ZLAJ.mjs +47 -0
- package/dist/chunks/chunk-YY3Z7NGV.cjs +203 -0
- package/dist/chunks/cli-handler-7XFZK7GK.cjs +1 -0
- package/dist/chunks/cli-handler-H6VHMEHB.mjs +1 -0
- package/dist/chunks/code-base-E5TX7O7M.cjs +1 -0
- package/dist/chunks/code-base-HAX5SGRL.mjs +1 -0
- package/dist/chunks/database-manager-WTV3TBJS.cjs +1 -0
- package/dist/chunks/database-manager-YGQQHLYR.mjs +1 -0
- package/dist/chunks/file-watcher-HVST5PAC.cjs +1 -0
- package/dist/chunks/file-watcher-LCQ55MPE.mjs +1 -0
- package/dist/chunks/{interfaces-5HZADUYB.mjs → interfaces-DPFLQBQ6.mjs} +1 -1
- package/dist/chunks/{interfaces-ORRCH4XV.cjs → interfaces-YX56SVRQ.cjs} +1 -1
- package/dist/chunks/{llm-MPD7FHPM.mjs → llm-ADBGTSCV.mjs} +1 -1
- package/dist/chunks/{llm-JQV6XWGD.cjs → llm-BDMNIGOH.cjs} +1 -1
- package/dist/chunks/stdio-server-2QHQ7ESX.cjs +47 -0
- package/dist/chunks/stdio-server-5YSJE5E5.mjs +47 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +35 -3
- package/dist/index.d.ts +35 -3
- package/dist/index.mjs +1 -1
- package/package.json +12 -12
- package/dist/chunks/chunk-AGZFRKQ4.mjs +0 -188
- package/dist/chunks/chunk-CSMSBVAG.mjs +0 -34
- package/dist/chunks/chunk-R74KIJM2.cjs +0 -34
- package/dist/chunks/chunk-TR3DFBJH.mjs +0 -47
- package/dist/chunks/chunk-VFTVDTEY.cjs +0 -188
- package/dist/chunks/chunk-YYF5OQDS.cjs +0 -47
- package/dist/chunks/cli-handler-3I5JC3HY.cjs +0 -1
- package/dist/chunks/cli-handler-IJ2PNNTK.mjs +0 -1
- package/dist/chunks/code-base-6TM7JDJ6.cjs +0 -1
- package/dist/chunks/code-base-BSRUQYXN.mjs +0 -1
- package/dist/chunks/database-manager-26PY6VTD.mjs +0 -1
- package/dist/chunks/database-manager-U7D7QIHC.cjs +0 -1
- package/dist/chunks/file-watcher-GHRFHOQF.cjs +0 -1
- package/dist/chunks/file-watcher-OORREWFV.mjs +0 -1
- package/dist/chunks/stdio-server-2GBPZY6J.cjs +0 -47
- package/dist/chunks/stdio-server-BZYPM34X.mjs +0 -47
- /package/dist/chunks/{chunk-TMICZT3L.mjs → chunk-2YMB6W5S.mjs} +0 -0
- /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
import {a as a$2,h,f,c,g,n,e,m}from'./chunk-22PKTMO5.mjs';import {a as a$3}from'./chunk-GWCRGM4D.mjs';import {a as a$1,b}from'./chunk-TMICZT3L.mjs';import V,{join,dirname}from'path';import {existsSync,mkdirSync,readFileSync}from'fs';import {fileURLToPath}from'url';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {Filesystem,Log,Shell,Glob,Ignore}from'@easbot/utils';import {Worker}from'worker_threads';import {createRequire}from'module';import Ue from'fs/promises';import {createHash}from'crypto';var Le={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var j=Filesystem.toUnixPath,it=`
|
|
2
|
-
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
|
-
`,at=`
|
|
5
|
-
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?)
|
|
7
|
-
`,st="DELETE FROM nodes_fts WHERE rowid = (SELECT rowid FROM nodes_fts WHERE id = ?)",ot="INSERT INTO nodes_fts (id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)";var ct=`
|
|
8
|
-
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
9
|
-
VALUES (?, ?, ?)
|
|
10
|
-
`,dt=`
|
|
11
|
-
INSERT OR IGNORE INTO embedding_cache (content_hash, embedding)
|
|
12
|
-
VALUES (?, ?)
|
|
13
|
-
`,lt=`
|
|
14
|
-
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
15
|
-
VALUES (?, ?, ?)
|
|
16
|
-
`;var Ae=`
|
|
17
|
-
INSERT INTO unresolved_refs
|
|
18
|
-
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
19
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
20
|
-
`,pt="DELETE FROM edges WHERE source IN (SELECT id FROM nodes WHERE file_path = ?) OR target IN (SELECT id FROM nodes WHERE file_path = ?)",ut="DELETE FROM nodes WHERE file_path = ?";var ft="DELETE FROM file_hashes WHERE file_path = ?",G="INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",gt="DELETE FROM meta WHERE key = ?",le=class{constructor(e,t,r={}){a$1(this,"db",e);a$1(this,"writeBackend",t);a$1(this,"options",r);}insertNodes(e){if(e.length===0)return;let t=[];for(let r of e){let n=j(r.file_path);t.push({sql:it,params:[r.id,r.name,r.ast_type,r.language,n,r.start_line,r.start_col,r.end_line,r.end_col,r.text,r.created_at]}),this.options.ftsAvailable&&(t.push({sql:st,params:[r.id]}),t.push({sql:ot,params:[r.id,r.name,r.ast_type,r.language,n,r.text]}));}this.writeBackend.enqueue(t);}insertEdges(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:at,params:[r.id,r.source,r.target,r.relation,r.created_at]});this.writeBackend.enqueue(t);}insertUnresolvedRef(e){this.writeBackend.enqueue([{sql:Ae,params:[e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,j(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null]}]);}insertUnresolvedRefsBatch(e){if(e.length===0)return;let t=e.map(r=>({sql:Ae,params:[r.fromNodeId??null,r.referenceName,r.referenceKind,r.line??null,r.col??null,j(r.filePath),r.language,r.candidates?JSON.stringify(r.candidates):null]}));this.writeBackend.enqueue(t);}setFileHash(e,t){this.writeBackend.enqueue([{sql:ct,params:[j(e),t,Date.now()]}]);}setLastSync(){this.setMeta("lastSync",new Date().toISOString());}cacheEmbedding(e,t){this.writeBackend.enqueue([{sql:dt,params:[e,Buffer.from(t.buffer,t.byteOffset,t.byteLength)]}]);}storeNodeEmbeddings(e){if(e.length===0)return;let t=[];for(let r of e)t.push({sql:lt,params:[r.nodeId,r.embeddingText,Buffer.from(r.embedding.buffer,r.embedding.byteOffset,r.embedding.byteLength)]});this.writeBackend.enqueue(t);}deleteEdgesByFile(e){let t=j(e);return this.writeBackend.enqueue([{sql:pt,params:[t,t]}]),-1}deleteNodesByFile(e){let t=j(e);return this.writeBackend.enqueue([{sql:ut,params:[t]}]),-1}deleteFtsByFile(e){return this.db.deleteFtsByFile(e)}deleteFileHash(e){this.writeBackend.enqueue([{sql:ft,params:[j(e)]}]);}async flush(){await this.writeBackend.flush();}setMeta(e,t){this.writeBackend.enqueue([{sql:G,params:[e,t]}]);}deleteMeta(e){this.writeBackend.enqueue([{sql:gt,params:[e]}]);}markIndexed(e,t,r){let n=[{sql:G,params:["indexed_with_version",e]},{sql:G,params:["indexed_with_extraction_version",String(t)]},{sql:G,params:["index_state","complete"]},{sql:G,params:["last_index_state_change",r]}];this.writeBackend.enqueue(n);}setIndexState(e){let t=new Date().toISOString(),r=[{sql:G,params:["index_state",e]},{sql:G,params:["last_index_state_change",t]}];this.writeBackend.enqueue(r);}async dispose(){await this.writeBackend.dispose();}pendingCount(){return this.writeBackend.pendingCount()}};function mt(){return `
|
|
21
|
-
const { parentPort } = require('node:worker_threads');
|
|
22
|
-
|
|
23
|
-
if (parentPort !== null) {
|
|
24
|
-
const port = parentPort;
|
|
25
|
-
let queueDepth = 0;
|
|
26
|
-
|
|
27
|
-
port.on('message', (msg) => {
|
|
28
|
-
if (msg.type === 'shutdown') {
|
|
29
|
-
const reqId = msg.requestId;
|
|
30
|
-
// \u7B49\u961F\u5217 drain \u518D exit\uFF08\u4EFF Real worker drainInterval \u6A21\u5F0F\uFF09
|
|
31
|
-
const drainInterval = setInterval(() => {
|
|
32
|
-
if (queueDepth === 0) {
|
|
33
|
-
clearInterval(drainInterval);
|
|
34
|
-
port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
|
|
35
|
-
process.exit(0);
|
|
36
|
-
}
|
|
37
|
-
}, 5);
|
|
38
|
-
return;
|
|
39
|
-
}
|
|
40
|
-
if (msg.type === 'ping') {
|
|
41
|
-
port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
if (msg.type === 'open') {
|
|
45
|
-
port.postMessage({ type: 'open_ack', requestId: msg.requestId });
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
if (msg.type === 'flush') {
|
|
49
|
-
port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
if (msg.type === 'write_batch') {
|
|
53
|
-
const reqId = msg.requestId;
|
|
54
|
-
queueDepth++;
|
|
55
|
-
const affected = (msg.statements || []).reduce((sum, s) => sum + (s.affectedRows || 0), 0);
|
|
56
|
-
setTimeout(() => {
|
|
57
|
-
queueDepth--;
|
|
58
|
-
port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
|
|
59
|
-
}, 10);
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
port.postMessage({ type: 'ready' });
|
|
64
|
-
}
|
|
65
|
-
`}function Oe(){return new Worker(mt(),{eval:true})}function yt(u){return `
|
|
66
|
-
const { parentPort } = require('node:worker_threads');
|
|
67
|
-
|
|
68
|
-
if (parentPort !== null) {
|
|
69
|
-
const port = parentPort;
|
|
70
|
-
let Database;
|
|
71
|
-
try {
|
|
72
|
-
Database = require(${JSON.stringify(u)});
|
|
73
|
-
} catch (err) {
|
|
74
|
-
port.postMessage({ type: 'error', requestId: -1, error: 'better-sqlite3 not loadable at ${u}: ' + err.message });
|
|
75
|
-
process.exit(1);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
let db = null;
|
|
79
|
-
let queueDepth = 0;
|
|
80
|
-
const queueMax = 1000;
|
|
81
|
-
// Wave 5 \u5927\u4ED3 sync \u4F18\u5316\uFF1A\u5355 batch timeout \u52A0\u5927\u5230 5min\uFF08100 \u6761 SQL + WAL fsync \u5927\u6587\u4EF6\u53EF\u80FD\u8D85 30s\uFF09
|
|
82
|
-
// \u4E4B\u524D 30s \u5728 30K files \u5927\u4ED3\u4E0A\u4F1A\u5047\u9633\u6027 timeout \u2014\u2014 \u5B9E\u9645\u662F WAL fsync \u7B49 IO \u800C\u4E0D\u662F\u5361\u6B7B
|
|
83
|
-
const txTimeoutMs = 300000;
|
|
84
|
-
// Wave 5 \u5927\u4ED3 sync \u4F18\u5316\uFF1Astatement cache \u2014\u2014 30K files \xD7 11 stmts = 330K \u6B21 prepare \u592A\u6162
|
|
85
|
-
// \u5B9E\u6D4B 1407 files sync \u8DD1\u5230 53% \u65F6 5min flush timeout \u2014\u2014 \u6839\u56E0\u662F\u91CD\u590D prepare
|
|
86
|
-
// \u4FEE\uFF1AMap<sql, prepared statement> \u7F13\u5B58\uFF0C\u540C SQL \u6A21\u677F\u590D\u7528 prepared \u5BF9\u8C61
|
|
87
|
-
const stmtCache = new Map();
|
|
88
|
-
|
|
89
|
-
function getPrepared(sql) {
|
|
90
|
-
let prepared = stmtCache.get(sql);
|
|
91
|
-
if (!prepared) {
|
|
92
|
-
prepared = db.prepare(sql);
|
|
93
|
-
stmtCache.set(sql, prepared);
|
|
94
|
-
}
|
|
95
|
-
return prepared;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function runStatement(stmt) {
|
|
99
|
-
try {
|
|
100
|
-
const prepared = getPrepared(stmt.sql);
|
|
101
|
-
const info = prepared.run(...(stmt.params || []));
|
|
102
|
-
return info.changes || 0;
|
|
103
|
-
} catch (err) {
|
|
104
|
-
// Wave 4 R3-2\uFF1Aworker \u7AEF debug \u65E5\u5FD7 \u2014\u2014 \u771F\u51F6\u96BE\u8FFD\uFF0C\u52A0\u8BE6\u7EC6 error \u4FE1\u606F
|
|
105
|
-
// \u8F93\u51FA SQL + params + error \u8BE6\u60C5\uFF08\u901A\u8FC7 stderr \u2192 \u4E3B\u8FDB\u7A0B\uFF09
|
|
106
|
-
port.postMessage({
|
|
107
|
-
type: 'debug_error',
|
|
108
|
-
requestId: -1,
|
|
109
|
-
sql: stmt.sql,
|
|
110
|
-
paramsCount: (stmt.params || []).length,
|
|
111
|
-
paramsJson: JSON.stringify(stmt.params || []).slice(0, 500),
|
|
112
|
-
error: err.message,
|
|
113
|
-
});
|
|
114
|
-
throw err;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
port.on('message', (msg) => {
|
|
119
|
-
if (msg.type === 'shutdown') {
|
|
120
|
-
const reqId = msg.requestId;
|
|
121
|
-
const drainInterval = setInterval(() => {
|
|
122
|
-
if (queueDepth === 0) {
|
|
123
|
-
clearInterval(drainInterval);
|
|
124
|
-
try { if (db) db.close(); } catch (e) {}
|
|
125
|
-
port.postMessage({ type: 'shutdown_ack', requestId: reqId, queueDepth: 0 });
|
|
126
|
-
process.exit(0);
|
|
127
|
-
}
|
|
128
|
-
}, 5);
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
if (msg.type === 'ping') {
|
|
132
|
-
port.postMessage({ type: 'pong', requestId: msg.requestId, ts: Date.now() });
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
if (msg.type === 'open') {
|
|
136
|
-
const reqId = msg.requestId;
|
|
137
|
-
try {
|
|
138
|
-
if (db) db.close();
|
|
139
|
-
db = new Database(msg.dbPath, { timeout: txTimeoutMs });
|
|
140
|
-
db.pragma('journal_mode = WAL');
|
|
141
|
-
db.pragma('synchronous = NORMAL');
|
|
142
|
-
// Wave 3 \u8BC4\u5BA1 R3\uFF1Aworker \u4E5F\u8981\u5F00 FK \u7EA7\u8054 \u2014\u2014 \u5220 nodes \u81EA\u52A8\u7EA7\u8054\u6E05 node_embeddings / edges
|
|
143
|
-
db.pragma('foreign_keys = ON');
|
|
144
|
-
port.postMessage({ type: 'open_ack', requestId: reqId });
|
|
145
|
-
} catch (err) {
|
|
146
|
-
port.postMessage({ type: 'error', requestId: reqId, error: err.message });
|
|
147
|
-
}
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
if (msg.type === 'flush') {
|
|
151
|
-
port.postMessage({ type: 'flush_ack', requestId: msg.requestId, queueDepth });
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
if (msg.type === 'write_batch') {
|
|
155
|
-
const reqId = msg.requestId;
|
|
156
|
-
if (!db) {
|
|
157
|
-
port.postMessage({ type: 'error', requestId: reqId, error: 'db not open' });
|
|
158
|
-
return;
|
|
159
|
-
}
|
|
160
|
-
if (queueDepth >= queueMax) {
|
|
161
|
-
port.postMessage({ type: 'error', requestId: reqId, error: 'queue overflow (' + queueDepth + '/' + queueMax + ')' });
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
queueDepth++;
|
|
165
|
-
try {
|
|
166
|
-
const tx = db.transaction((statements) => {
|
|
167
|
-
let totalChanges = 0;
|
|
168
|
-
for (const stmt of statements) {
|
|
169
|
-
totalChanges += runStatement(stmt);
|
|
170
|
-
}
|
|
171
|
-
return totalChanges;
|
|
172
|
-
});
|
|
173
|
-
const affected = tx(msg.statements || []);
|
|
174
|
-
port.postMessage({ type: 'write_batch_ack', requestId: reqId, affectedRows: affected });
|
|
175
|
-
} catch (err) {
|
|
176
|
-
port.postMessage({ type: 'error', requestId: reqId, error: err.message });
|
|
177
|
-
} finally {
|
|
178
|
-
queueDepth--;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
port.postMessage({ type: 'ready' });
|
|
184
|
-
}
|
|
185
|
-
`}function Ee(u,e){return new Worker(yt(e.betterSqlite3Path),{eval:true})}var ue=Log.create({service:"codebase.better-sqlite3-resolver"}),We=createRequire(import.meta.url);async function ze(u={}){try{let s=We.resolve("better-sqlite3");if(s)return ue.debug("better-sqlite3 resolved from monorepo",{resolved:s}),{absolutePath:Filesystem.normalize(s),source:"monorepo"}}catch(s){ue.debug("better-sqlite3 not in current resolve paths",{error:s instanceof Error?s.message:String(s)});}let e=process.env.EASBOT_CACHE_PATH,t=u.installPath??e??`${process.cwd()}/.easbot/cache`,r=Filesystem.normalize(t),n=u.version??"latest";ue.info("better-sqlite3 not found locally, installing to cache",{installPath:r,version:n,envCache:e});let i;try{i=await Shell.install("better-sqlite3",n,r);}catch(s){throw new fe(`Failed to install better-sqlite3@${n} into ${r}: ${s instanceof Error?s.message:String(s)}. You can also install it manually: \`npm i -g better-sqlite3\` or \`pnpm add better-sqlite3\` in your project.`,r)}try{let s=We.resolve("better-sqlite3",{paths:[i]}),d=Filesystem.normalize(s),c=r===Filesystem.normalize(e??"")?"env-cache-install":"cwd-cache-install";return ue.info("better-sqlite3 installed and resolved",{resolved:d,installPath:r}),{absolutePath:d,source:c}}catch(s){throw new fe(`Installed better-sqlite3 to ${i} but cannot resolve entry from there: ${s instanceof Error?s.message:String(s)}`,i)}}var fe=class extends Error{constructor(t,r){super(t);a$1(this,"installPath");this.name="BetterSqlite3ResolveError",this.installPath=r;}};var ne=Log.create({service:"database.async-write"}),we,re,ge=class{constructor(e){a$1(this,"worker");a$1(this,"mock");a$1(this,"dbPath");a$1(this,"batchSize");a$1(this,"batchIntervalMs");a$1(this,"queueMax");a$1(this,"bufferedStatements",[]);a$1(this,"pendingRequests",new Map);a$1(this,"nextRequestId",1);a$1(this,"flushTimer",null);a$1(this,"ready");a$1(this,"disposed",false);if(this.dbPath=e.dbPath,this.mock=e.mock??false,this.batchSize=e.batchSize??100,this.batchIntervalMs=e.batchIntervalMs??50,this.queueMax=e.queueMax??1e3,this.mock)this.worker=Oe(),this.ready=this.waitForReady();else {let t=e.betterSqlite3Path;t?(this.worker=Ee(this.dbPath,{betterSqlite3Path:t}),this.ready=this.waitForReady()):(this.worker=null,this.ready=this.initRealAsync());}this.worker&&this.installAckHandler();}async initRealAsync(){let e=await Tt();this.worker=Ee(this.dbPath,{betterSqlite3Path:e}),this.installAckHandler(),await this.waitForReady();}installAckHandler(){this.requireWorker().on("message",t=>{let r=t;if(r.type==="debug_error"){ne.error("AsyncWriteBackend statement failed (debug)",{sql:r.sql?.slice(0,200),paramsCount:r.paramsCount,params:r.paramsJson,error:r.error});return}if(typeof r.requestId!="number"||r.requestId<1)return;let n=this.pendingRequests.get(r.requestId);n&&(this.pendingRequests.delete(r.requestId),clearTimeout(n.timer),r.type==="write_batch_ack"?n.resolve():r.type==="error"&&n.reject(new Error(r.error??"worker write error")));});}requireWorker(){if(!this.worker)throw new Error("AsyncWriteBackend worker not initialized yet (call installAckHandler / waitForReady only after spawn)");return this.worker}waitForReady(){let e=this.requireWorker();return new Promise((t,r)=>{let n=setTimeout(()=>r(new Error("worker init timeout")),1e4),i=s=>{if(s.type==="ready"){clearTimeout(n),e.off("message",i);let d=setTimeout(()=>r(new Error("worker open timeout")),1e4),c=o=>{o.type==="open_ack"&&o.requestId===0?(clearTimeout(d),e.off("message",c),t()):o.type==="error"&&o.requestId===0&&(clearTimeout(d),e.off("message",c),r(new Error(o.error??"worker open error")));};e.on("message",c),e.postMessage({type:"open",requestId:0,dbPath:this.dbPath});}else s.type==="error"&&s.requestId===-1&&(clearTimeout(n),e.off("message",i),r(new Error(s.error??"unknown init error")));};e.on("message",i);})}async waitReady(){await this.ready;}enqueue(e){if(this.disposed)throw new Error("AsyncWriteBackend \u5DF2 dispose");if(!this.worker)throw new Error("AsyncWriteBackend worker not ready yet (await backend.ready before enqueue)");let t=Math.ceil(this.bufferedStatements.length/Math.max(this.batchSize,1));if(this.pendingRequests.size+t>=this.queueMax)throw new Error(`AsyncWriteBackend queue overflow (pending=${this.pendingRequests.size}, buffered=${this.bufferedStatements.length}, max=${this.queueMax})`);this.bufferedStatements.push(...e),this.bufferedStatements.length>=this.batchSize?this.flushBuffer():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flushBuffer(),this.batchIntervalMs));}flushBuffer(){if(!this.worker||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.bufferedStatements.length===0))return;let e=this.bufferedStatements;this.bufferedStatements=[];let t=this.nextRequestId++,r={resolve:()=>{},reject:n=>{ne.error("AsyncWriteBackend write failed",{error:n.message,requestId:t});},timer:setTimeout(()=>{this.pendingRequests.delete(t),r.reject(new Error(`AsyncWriteBackend write timeout (${t})`));},3e4)};this.pendingRequests.set(t,r),this.worker.postMessage({type:"write_batch",statements:e,requestId:t});}async flush(e=Number.parseInt(process.env.EASBOT_FLUSH_TIMEOUT??"3600000",10)||36e5){if(this.flushBuffer(),this.pendingRequests.size===0)return;let t=this.pendingRequests.size,r=Date.now();await new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(`flush timeout after ${e}ms, pending=${this.pendingRequests.size}`)),e),d=setInterval(()=>{let o=this.pendingRequests.size,l=Math.floor((Date.now()-r)/1e3);o>0&&l>0&&l%5===0&&ne.info("flush in progress",{pending:o,initial:t,elapsedSec:l});},1e3),c=setInterval(()=>{this.pendingRequests.size===0&&(clearTimeout(s),clearInterval(c),clearInterval(d),n());},5);});}async dispose(){this.disposed=true,this.flushBuffer();try{await this.flush(3e4);}catch(e){ne.warn("dispose flush failed, forcing terminate",{pending:this.pendingRequests.size,error:e instanceof Error?e.message:String(e)});}this.worker&&(this.worker.postMessage({type:"shutdown",requestId:0}),await this.worker.terminate());}pendingCount(){return this.pendingRequests.size}};async function Tt(){return we||(re||(re=ze().then(u=>(we=u.absolutePath,re=void 0,ne.info("better-sqlite3 resolved for AsyncWriteBackend",{path:u.absolutePath,source:u.source}),u.absolutePath)).catch(u=>{throw re=void 0,u})),re)}var He=Log.create({service:"codebase-parser"}),Nt={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"},zig:{package:"@tree-sitter-grammars/tree-sitter-zig",wasmFile:"tree-sitter-zig.wasm"}};function vt(){return typeof import.meta<"u"&&import.meta.url?V.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function It(u,e){let t=vt(),r=t;for(let n=0;n<10;n++){let i=V.join(r,"node_modules",u,e);if(Filesystem.stat(i)!==void 0)return i;let s=V.dirname(r);if(s===r)break;r=s;}return V.join(t,"node_modules",u,e)}var Y=class{constructor(){a$1(this,"parsers",new Map);a$1(this,"initialized",false);a$1(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala","zig"],i=await Promise.allSettled(n.map(async s=>{try{let d=Nt[s];if(!d)return He.warn("No WASM config for language",{lang:s}),null;let c=It(d.package,d.wasmFile),o=await r.load(c),l=new t;return l.setLanguage(o),{lang:s,parser:l,language:o}}catch(d){return He.warn("Failed to load parser",{lang:s,error:String(d)}),null}}));for(let s of i)if(s.status==="fulfilled"&&s.value){let{lang:d,parser:c,language:o}=s.value;this.parsers.set(d,{parser:c,language:o});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=V.extname(e).toLowerCase();return Le[t]??null}parse(e,t){if(!this.initialized)throw new a$2("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new a$2(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new a$2("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new h(V.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},Q=null;async function Pt(){return Q||(Q=new Y,await Q.initialize()),Q}function Ct(){Q&&(Q.dispose(),Q=null);}var F={class_declaration:"class_declaration",class_item:"class_declaration",class_definition:"class_declaration",abstract_class_declaration:"class_declaration",class_specifier:"class_declaration",record_declaration:"class_declaration",interface_declaration:"interface_declaration",protocol_declaration:"interface_declaration",function_declaration:"function_definition",function_definition:"function_definition",function_item:"function_definition",function_expression:"function_definition",arrow_function:"function_definition",method_definition:"method_definition",method_declaration:"method_definition",method:"method_definition",method_invocation:"method_definition",public_field_definition:"property_declaration",field_definition:"property_declaration",property_signature:"property_declaration",field_declaration:"field_declaration",property_declaration:"property_declaration",val_definition:"property_declaration",var_definition:"property_declaration",variable_declaration:"variable_declaration",lexical_declaration:"variable_declaration",variable_declarator:"variable_declaration",assignment:"variable_declaration",module:"module_declaration",internal_module:"module_declaration",ambient_declaration:"module_declaration",namespace_declaration:"module_declaration",namespace_definition:"module_declaration",mod_item:"module_declaration",import_declaration:"import_declaration",import_statement:"import_declaration",import_from_statement:"import_declaration",use_declaration:"import_declaration",use_list:"import_declaration",using_directive:"import_declaration",require:"import_declaration",require_relative:"import_declaration",preproc_include:"import_declaration",include_directive:"import_declaration",struct_declaration:"struct_declaration",struct_definition:"struct_declaration",struct_item:"struct_declaration",struct_specifier:"struct_declaration",trait_item:"trait_declaration",trait_definition:"trait_declaration",impl_item:"impl_item",enum_declaration:"enum_declaration",enum_item:"enum_declaration",enum_specifier:"enum_declaration",type_alias_declaration:"type_alias_declaration",type_declaration:"type_declaration",class:"class_declaration",decorator:"decorator",annotation:"annotation",marker_annotation:"annotation",attribute:"attribute",attribute_item:"attribute",modifiers:"modifiers",decorated_expression:"decorator",attribute_decorator:"decorator",export_statement:"export_statement",const_item:"constant_declaration",constant_declaration:"constant_declaration",function:"function_definition"},Se={language:"ts",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["module","internal_module","ambient_declaration"],methodTypes:["method_definition","function_declaration"],propertyTypes:["public_field_definition","property_signature"],functionTypes:["function_declaration"],typeAliasTypes:["type_alias_declaration"],enumTypes:["enum_declaration"],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:["export_statement"],ambientDeclarationTypes:["ambient_declaration"]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","extends_type_clause"],implementsClauseTypes:["implements_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","abstract_class_declaration","function_declaration","method_definition","export_statement"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},kt={...Se,language:"tsx"},qt={language:"js",rawTypes:{classTypes:["class_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_definition"],propertyTypes:["public_field_definition","field_definition"],functionTypes:["function_declaration","function_expression","arrow_function"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement"],annotationTypes:["decorator"],variableTypes:["lexical_declaration","variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","function_declaration","method_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["required_parameter","optional_parameter"],typeInWrapper:["type_identifier","generic_type","predefined_type","array_type"],declaratorStyle:"wrapper"}},Rt={language:"py",rawTypes:{classTypes:["class_definition"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:[],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_statement","import_from_statement"],annotationTypes:["decorator"],variableTypes:["assignment","expression_statement"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["argument_list","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["function_definition","class_definition","decorated_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["identifier","typed_parameter","default_parameter","list_splat_pattern","dictionary_splat_pattern"],typeInWrapper:["type","identifier"],declaratorStyle:"wrapper"}},Mt={language:"java",rawTypes:{classTypes:["class_declaration","abstract_class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["import_declaration"],annotationTypes:["annotation","marker_annotation","modifiers"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass","extends_clause"],implementsClauseTypes:["super_interfaces","implements_clause","interface_list"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration","interface_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["formal_parameter"],typeInWrapper:["type_identifier","generic_type","array_type","integral_type","floating_point_type","boolean_type"],declaratorStyle:"wrapper"}},Ft={language:"csharp",rawTypes:{classTypes:["class_declaration","record_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:["field_declaration","property_declaration"],functionTypes:[],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:["using_directive"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_list","super"],implementsClauseTypes:["base_list"],fallbackToFirstIdentifier:true,stripTemplateArgs:true},annotation:{annotatableTypes:["class_declaration","method_declaration","field_declaration"]},parameters:{wrapperType:"formal_parameters",paramTypes:["parameter"],typeInWrapper:["predefined_type","identifier","generic_name","array_type","nullable_type"],declaratorStyle:"wrapper"}},Lt={language:"c",rawTypes:{classTypes:["struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","union_specifier","enum_specifier"],declaratorStyle:"declarator"}},At={language:"cpp",rawTypes:{classTypes:["class_specifier","struct_specifier"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["field_declaration"],functionTypes:["function_definition"],typeAliasTypes:["type_declaration"],enumTypes:["enum_specifier"],importTypes:["preproc_include"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_class_clause","superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["class_specifier","function_definition"]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","parameter"],typeInWrapper:["type_identifier","primitive_type","pointer_type","array_type","sized_type_specifier","struct_specifier","class_specifier","enum_specifier","scoped_identifier","template_type","auto"],declaratorStyle:"declarator"}},Dt={language:"rs",rawTypes:{classTypes:["struct_item","enum_item","impl_item"],interfaceTypes:["trait_item"],moduleTypes:["mod_item"],methodTypes:["function_item"],propertyTypes:["field_declaration"],functionTypes:["function_item"],typeAliasTypes:["type_declaration"],enumTypes:["enum_item"],importTypes:["use_declaration"],annotationTypes:["attribute_item"],variableTypes:["const_item"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_item","struct_item","trait_item"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","reference_type","slice_type","array_type","generic_type","scoped_identifier","pointer_type","unit_type","never_type"],declaratorStyle:"wrapper"}},Ot={language:"go",rawTypes:{classTypes:["type_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["method_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:["type_declaration"],enumTypes:[],importTypes:["import_declaration"],annotationTypes:[],variableTypes:[],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameter_list",paramTypes:["parameter_declaration","variadic_parameter"],typeInWrapper:["type_identifier","pointer_type","slice_type","map_type","channel_type","array_type","function_type","qualified_type","generic_type"],declaratorStyle:"wrapper"}},Wt={language:"ruby",rawTypes:{classTypes:["class"],interfaceTypes:[],moduleTypes:["module"],methodTypes:["method","method_definition","singleton_method"],propertyTypes:[],functionTypes:["method","method_definition"],typeAliasTypes:[],enumTypes:[],importTypes:[],annotationTypes:[],variableTypes:["assignment"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["superclass"],implementsClauseTypes:[],fallbackToFirstIdentifier:true,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"method_parameters",paramTypes:["identifier","required_parameter","optional_parameter","splat_parameter","hash_splat_parameter","block_parameter","keyword_rest_parameter"],typeInWrapper:[],declaratorStyle:"wrapper"}},zt={language:"php",rawTypes:{classTypes:["class_declaration"],interfaceTypes:["interface_declaration"],moduleTypes:["namespace_definition"],methodTypes:["method_declaration"],propertyTypes:["property_declaration"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["namespace_use_declaration"],annotationTypes:["attribute"],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["base_clause"],implementsClauseTypes:["class_interface_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:["class_declaration","method_declaration","function_definition"]},parameters:{wrapperType:"formal_parameters",paramTypes:["simple_parameter","variadic_parameter","property_promotion_parameter"],typeInWrapper:["named_type","primitive_type","optional_type"],declaratorStyle:"wrapper"}},Ht={language:"scala",rawTypes:{classTypes:["class_definition"],interfaceTypes:["trait_definition"],moduleTypes:[],methodTypes:["function_definition"],propertyTypes:["val_definition","var_definition"],functionTypes:["function_definition"],typeAliasTypes:[],enumTypes:[],importTypes:["import_declaration"],annotationTypes:["annotation"],variableTypes:["val_definition","var_definition"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:["extends_clause"],implementsClauseTypes:["with_clause"],fallbackToFirstIdentifier:false,stripTemplateArgs:true},annotation:{annotatableTypes:["function_definition","class_definition","trait_definition"]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["type_identifier","generic_type","scoped_type_identifier","function_type","tuple_type","refined_type"],declaratorStyle:"wrapper"}},Bt={language:"zig",rawTypes:{classTypes:["struct_declaration","enum_declaration"],interfaceTypes:[],moduleTypes:[],methodTypes:["function_declaration"],propertyTypes:[],functionTypes:["function_declaration"],typeAliasTypes:[],enumTypes:["enum_declaration"],importTypes:[],annotationTypes:[],variableTypes:["variable_declaration"],exportTypes:[],ambientDeclarationTypes:[]},normalizeMap:F,inheritance:{extendsClauseTypes:[],implementsClauseTypes:[],fallbackToFirstIdentifier:false,stripTemplateArgs:false},annotation:{annotatableTypes:[]},parameters:{wrapperType:"parameters",paramTypes:["parameter"],typeInWrapper:["identifier","optional_type","array_type","pointer_type","slice_type"],declaratorStyle:"wrapper"}},Be=new Map([["ts",Se],["tsx",kt],["js",qt],["py",Rt],["java",Mt],["csharp",Ft],["c",Lt],["cpp",At],["rs",Dt],["go",Ot],["php",zt],["scala",Ht],["zig",Bt],["ruby",Wt]]);function L(u){return Be.get(u)??Se}Array.from(Be.keys());function $e(u){let e=L(u),t=new Set;for(let r of [e.rawTypes.classTypes,e.rawTypes.interfaceTypes,e.rawTypes.moduleTypes,e.rawTypes.methodTypes,e.rawTypes.propertyTypes,e.rawTypes.functionTypes,e.rawTypes.typeAliasTypes,e.rawTypes.enumTypes,e.rawTypes.importTypes,e.rawTypes.annotationTypes,e.rawTypes.variableTypes,e.rawTypes.exportTypes,e.rawTypes.ambientDeclarationTypes])for(let n of r)t.add(n);return t}function je(u){let e=L(u),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(r);for(let r of e.rawTypes.propertyTypes)t.add(r);return t}function q(u,e){return L(u).normalizeMap[e]??e}var K=class{extractNodes(e,t,r,n){let i=[],s=t.split(`
|
|
186
|
-
`),d=$e(r),c=je(r);return this.walkTree(e.rootNode,i,r,n,s,d,c),i}walkTree(e,t,r,n,i,s,d,c,o){if(s.has(e.type)){let l=this.extractNode(e,r,n,i,c,o,d);l&&(t.push(l),l.name&&(c=this.generateNodeId(l)),d.has(e.type)||(o=l.name??o));}for(let l=0;l<e.childCount;l++){let p=e.children[l];p&&this.walkTree(p,t,r,n,i,s,d,c,o);}}extractNode(e,t,r,n,i,s,d){let c=this.getNodeName(e,t);if(!c)return null;let o=e.startPosition,l=e.endPosition,p=this.getNodeText(e,n),m=d.has(e.type),g=m&&s?`${s}.${c}@${o.row+1}`:c,f=m?this.extractParameterTypes(e,t):[];return {name:g,ast_type:q(t,e.type),language:t,file_path:r,start_line:o.row+1,start_col:o.column,end_line:l.row+1,end_col:l.column,text:p,parent_id:i,metadata:m?{originalName:c,parameterTypes:f}:void 0}}extractParameterTypes(e,t){let n=L(t).parameters;if(!n)return [];let i=new Set(n.typeInWrapper),s=[],d=c=>{for(let o of c.children)if(o.type===n.wrapperType)return o;return null};if(n.declaratorStyle==="declarator"){for(let c of e.children)if(c.type==="function_declarator"||c.type==="pointer_declarator"){let o=d(c);if(o){for(let l of o.children)if(n.paramTypes.includes(l.type)){let p=this.findTypeInNode(l,i);p&&s.push(p);}return s}}}else {let c=d(e);if(c){for(let o of c.children)if(n.paramTypes.includes(o.type)){let l=this.findTypeInNode(o,i);l&&s.push(l);}}}return s}findTypeInNode(e,t){for(let r of e.children)if(t.has(r.type))return r.text;return null}getNodeName(e,t){switch(e.type){case "class_declaration":case "class_definition":case "abstract_class_declaration":case "class":case "interface_declaration":case "protocol_declaration":case "trait_item":case "trait_definition":case "struct_item":case "struct_declaration":case "struct_definition":case "struct_specifier":case "enum_item":case "enum_declaration":case "enum_specifier":case "type_alias_declaration":case "record_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "function_expression":case "arrow_function":case "function":case "method_definition":case "method_declaration":case "method":case "method_invocation":case "singleton_method":return this.findNameInChildren(e,["name","property_identifier","function_name"])??this.findNameInGrandchildren(e,["function_declarator","declarator","name"],["identifier","property_identifier","field_identifier","name"]);case "public_field_definition":case "field_definition":case "field_declaration":case "property_signature":case "property_declaration":case "val_definition":case "var_definition":return this.findNameInGrandchildren(e,["variable_declarator","declarator","property_element"],["identifier","name"])??this.findNameInChildren(e,["name","property_identifier","field_identifier"]);case "module":case "internal_module":case "ambient_declaration":case "namespace_declaration":case "namespace_definition":case "mod_item":case "type_declaration":if(e.type==="namespace_definition"){for(let n of e.children)if(n.type==="namespace_name")return n.text}return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["type_spec","type_alias","namespace_name"],["type_identifier","identifier","name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "import_from_statement":case "use_declaration":case "use_list":case "namespace_use_declaration":case "namespace_use_clause":case "using_directive":case "require":case "require_relative":case "preproc_include":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);case "attribute_item":case "attribute":case "annotation":case "marker_annotation":case "decorator":return this.findNameInChildren(e,["name","identifier"])??this.findNameInGrandchildren(e,["attribute","decorator"],["identifier","name","token_tree"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let i=this.findNameInChildren(n,r);if(i)return i}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"||t.type==="dotted_name"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
|
|
187
|
-
`)}generateNodeId(e){let t=Filesystem.toUnixPath(e.file_path);return `${e.language}:${t}:${e.ast_type}:${e.name}`}};function jt(){return new K}var a={class_declaration:"class_declaration",class_definition:"class_definition",class_specifier:"class_specifier",interface_declaration:"interface_declaration",struct_item:"struct_item",struct_declaration:"struct_declaration",struct_specifier:"struct_specifier",type_declaration:"type_declaration",type_alias_declaration:"type_alias_declaration",enum_declaration:"enum_declaration",record_declaration:"record_declaration",function_declaration:"function_declaration",function_definition:"function_definition",function_item:"function_item",method_declaration:"method_declaration",method_definition:"method_definition",method_invocation:"method_invocation",invocation_expression:"invocation_expression",variable_declaration:"variable_declaration",lexical_declaration:"lexical_declaration",assignment:"assignment",parameter:"parameter",parameter_declaration:"parameter_declaration",formal_parameter:"formal_parameter",formal_parameters:"formal_parameters",simple_parameter:"simple_parameter",typed_param:"typed_param",argument:"argument",field_declaration:"field_declaration",property_declaration:"property_declaration",public_field_definition:"public_field_definition",field_definition:"field_definition",property_signature:"property_signature",type_identifier:"type_identifier",type_annotation:"type_annotation",generic_type:"generic_type",named_type:"named_type",primitive_type:"primitive_type",return_type:"return_type",pointer_type:"pointer_type",reference_type:"reference_type",array_type:"array_type",sized_type_specifier:"sized_type_specifier",void_type:"void_type",predefined_type:"predefined_type",this:"this",function_declarator:"function_declarator",pointer_declarator:"pointer_declarator",declarator:"declarator",identifier:"identifier",property_identifier:"property_identifier",field_identifier:"field_identifier",name:"name",type_spec:"type_spec",super:"super",required_parameter:"required_parameter",optional_parameter:"optional_parameter",aliased_import:"aliased_import",relative_import:"relative_import",import_prefix:"import_prefix",import_statement:"import_statement",import_from_statement:"import_from_statement",namespace_use_declaration:"namespace_use_declaration",scoped_identifier:"scoped_identifier",qualified_name:"qualified_name",dotted_name:"dotted_name",dotted_identifier:"dotted_identifier",module_name:"module_name",namespace_name:"namespace_name",system_lib_string:"system_lib_string",string_literal:"string_literal",string:"string",string_content:"string_content",interpreted_string_literal:"interpreted_string_literal",interpreted_string_literal_content:"interpreted_string_literal_content",annotation:"annotation",attribute:"attribute",call:"call",call_expression:"call_expression",method_call_expression:"method_call_expression",function_call:"function_call",function_call_expression:"function_call_expression",member_call_expression:"member_call_expression",builtin_call_expression:"builtin_call_expression",member_expression:"member_expression",member_access:"member_access",member_access_expression:"member_access_expression",field_access:"field_access",field_expression:"field_expression",new_expression:"new_expression",object_creation_expression:"object_creation_expression",instance_expression:"instance_expression",scoped_type_identifier:"scoped_type_identifier",selector_expression:"selector_expression",constant:"constant",slice_type:"slice_type",map_type:"map_type",channel_type:"channel_type",parenthesized_type:"parenthesized_type",parameters:"parameters",variable_name:"variable_name",decorated_definition:"decorated_definition",export_statement:"export_statement",namespace_use_clause:"namespace_use_clause"},Ne={extends:"extends",implements:"implements"},Ge="new",ie={void_any_null:new Set(["void","any","null"]),string_number_boolean:new Set(["string","number","boolean"])};function me(u,e){e(u);for(let t of u.children)me(t,e);}function A(u){for(let e of u.children)if(e.type===a.identifier||e.type===a.type_identifier||e.type===a.property_identifier||e.type===a.field_identifier||e.type===a.name)return e.text;return null}function ye(u){for(let e=u.children.length-1;e>=0;e--){let t=u.children[e];if(t&&(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name))return t.text}return null}function he(u,e){for(let t of u.children)if(e.includes(t.type))return t;return null}function W(u,e){for(let t of u.children){if(e.includes(t.type))return t;let r=W(t,e);if(r)return r}return null}function z(u,e){for(let t of u.children)if(e.includes(t.type)){let r=A(t);if(r)return r;for(let n of t.children){let i=A(n);if(i)return i}}for(let t of u.children){let r=z(t,e);if(r)return r}return null}function ae(u){let e=u.indexOf("<");if(e<0)return u;let t=0,r=null;for(let n=e;n<u.length;n++){let i=u[n];if(r){i===r&&(r=null);continue}if(i==='"'||i==="'"||i==="`"){r=i;continue}if(i==="<")t++;else if(i===">"&&(t--,t===0))return u.slice(0,e).trim()}return u}function Qe(u){let e=L(u),t=new Set;for(let r of e.rawTypes.classTypes)t.add(q(u,r));for(let r of e.rawTypes.interfaceTypes)t.add(q(u,r));for(let r of e.rawTypes.moduleTypes)t.add(q(u,r));return t}function Gt(u){let e=L(u),t=new Set;for(let r of e.rawTypes.methodTypes)t.add(q(u,r));return t}function Qt(u){let e=L(u),t=new Set;for(let r of e.rawTypes.propertyTypes)t.add(q(u,r));return t}var J=class{extractEdges(e,t,r,n){let i=[],s=new Map;for(let c of t){let o=s.get(c.name);o||(o=[],s.set(c.name,o)),o.push(c);}let d=new Map;for(let[c,o]of s){let l=o[0];l&&d.set(c,l);}return this.extractContainsEdges(t,i),this.extractCallEdges(e.rootNode,t,i,r,n,d),this.extractInheritanceEdges(e.rootNode,t,i,r,n,d),this.extractImportEdges(e.rootNode,t,i,r,n),this.extractTypeReferences(e.rootNode,t,i,r,n,d),this.extractAnnotationEdges(e.rootNode,t,i,r,n),this.extractHasMethodEdges(t,i,r),this.extractHasPropertyEdges(t,i,r),this.extractOverrideEdges(t,i,r,n),i}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,i,s){let d=new Set([a.call_expression,a.call,a.method_call_expression,a.function_call,a.function_call_expression,a.member_call_expression,a.method_invocation,a.invocation_expression,a.builtin_call_expression,a.new_expression,a.object_creation_expression,a.instance_expression]);this.walkTree(e,c=>{if(d.has(c.type)){let o=this.findEnclosingFunction(c,t,s),l=this.extractCalleeName(c);if(o&&l){let p=`${n}:*:*:${l}`;r.push({source:o.id,target:p,relation:"CALLS",line:(c.startPosition?.row??-1)+1,col:(c.startPosition?.column??-1)+1,filePath:i});}}});}extractInheritanceEdges(e,t,r,n,i,s){let d=L(n),c=new Set(d.rawTypes.classTypes),o=new Set(d.rawTypes.interfaceTypes),l=this.buildImportAliasMap(e,n);this.walkTree(e,p=>{if(c.has(p.type)){let m=A(p);if(!m)return;let g=Filesystem.toUnixPath(i),f=`${n}:${g}:${q(n,p.type)}:${m}`,T=he(p,[...d.inheritance.extendsClauseTypes]);T||(T=W(p,[...d.inheritance.extendsClauseTypes]));let h=[];T?(h=this.extractClauseNames(T,n),d.inheritance.stripTemplateArgs&&(h=h.map(x=>ae(x)))):d.inheritance.fallbackToFirstIdentifier&&(h=this.collectNamedIdentifiers(p).filter(x=>x!==m).slice(0,1));for(let x of h){if(!x||x===m)continue;let _=q(n,d.rawTypes.classTypes[0]??"class_declaration"),w=l.get(x)??x,y=Filesystem.toUnixPath(i),b=`${n}:${y}:${_}:${w}`;r.push({source:f,target:b,relation:"EXTENDS",line:(T?.startPosition?.row??p.startPosition?.row??-1)+1,col:(T?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}for(let x of d.inheritance.implementsClauseTypes){let _=he(p,[x]);if(_||(_=W(p,[x])),_){let w=this.extractClauseNames(_,n);d.inheritance.stripTemplateArgs&&(w=w.map(y=>ae(y)));for(let y of w){if(!y)continue;let b=d.rawTypes.interfaceTypes[0]??d.rawTypes.classTypes[0]??a.interface_declaration,N=l.get(y)??y,P=Filesystem.toUnixPath(i),H=`${n}:${P}:${b}:${N}`;r.push({source:f,target:H,relation:"IMPLEMENTS",line:(_?.startPosition?.row??p.startPosition?.row??-1)+1,col:(_?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}}}return}if(o.has(p.type)){let m=A(p);if(!m)return;let g=Filesystem.toUnixPath(i),f=`${n}:${g}:${q(n,p.type)}:${m}`;for(let T of d.inheritance.extendsClauseTypes){let h=W(p,[T]);if(h){let x=this.extractClauseNames(h,n);d.inheritance.stripTemplateArgs&&(x=x.map(_=>ae(_)));for(let _ of x){if(_===m)continue;let w=q(n,d.rawTypes.interfaceTypes[0]??"interface_declaration"),y=l.get(_)??_,b=`${n}:${g}:${w}:${y}`;r.push({source:f,target:b,relation:"EXTENDS",line:(h?.startPosition?.row??p.startPosition?.row??-1)+1,col:(h?.startPosition?.column??p.startPosition?.column??-1)+1,filePath:i});}break}}}});}collectTypeAnnotations(e){let t=[],r=new Set([a.type_annotation,"type",a.reference_type,a.pointer_type,a.generic_type,a.array_type,a.named_type,a.primitive_type]),n=i=>{if(r.has(i.type)){t.push(i);return}for(let s of i.children)n(s);};return n(e),t}collectNamedIdentifiers(e){let t=[],r=new Set,n=i=>{if(i.type===a.identifier||i.type===a.type_identifier||i.type===a.attribute){let s=i.text;r.has(s)||(r.add(s),t.push(s));return}for(let s of i.namedChildren)s&&n(s);};return n(e),t}extractClauseNames(e,t){let r=[],n=new Set,i=o=>{!o||n.has(o)||(n.add(o),r.push(o));},s=new Set([a.scoped_identifier,a.scoped_type_identifier,a.qualified_name,a.dotted_name,a.dotted_identifier]),d=new Set([a.identifier,a.type_identifier,a.name,a.attribute]),c=o=>{if(s.has(o.type)){i(o.text);return}if(d.has(o.type)){if(o.type===a.name&&(o.text===Ne.extends||o.text===Ne.implements))return;i(o.text);return}if(o.type===a.generic_type){let l=o.childForFieldName?.("name")?.text??o.namedChildren[0]?.text;l&&i(l);return}for(let l of o.namedChildren)l&&c(l);};return c(e),r}extractImportEdges(e,t,r,n,i){let s=L(n),d=new Set(s.rawTypes.importTypes),c=new Set;this.walkTree(e,o=>{if(d.has(o.type)){let l,p=this.extractImportWholePath(o);p?l=[p]:l=this.extractImportPaths(o);for(let m of l){if(!m||c.has(m))continue;c.add(m);let g=Filesystem.toUnixPath(i),f=`${n}:${g}:module:file`;r.push({source:f,target:m,relation:"IMPORTS",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}}});}walkTree(e,t){me(e,t);}findEnclosingFunction(e,t,r){let n=e,i=new Set([a.function_declaration,a.function_definition,a.method_definition,a.method_declaration,a.function_item]);for(;n;){if(i.has(n.type)){let s=A(n)??z(n,[a.function_declarator,a.declarator]);if(s){let d=r.get(s);if(d)return {id:this.generateNodeId(d),name:s};let c=t[0],o=c?.language??"ts",l=c?.file_path??"";return {id:`${o}:${l}:function_definition:${s}`,name:s}}}n=n.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;let r=new Set([a.member_expression,a.field_access,a.attribute,a.member_access,a.member_access_expression,a.member_call_expression,a.field_expression,a.selector_expression,a.constant]);if(t.type===a.variable_name&&e.type===a.member_call_expression){let n=e.childForFieldName?.("name");if(n)return n.text;let i=e.children.find(s=>s.type===a.name);if(i)return i.text}if(r.has(t.type)){let n=t.childForFieldName?.("property");if(n)return n.text;let i=t.childForFieldName?.("field");if(i)return i.text;let s=t.childForFieldName?.("name");if(s)return s.text;for(let d=t.children.length-1;d>=0;d--){let c=t.children[d];if(c&&(c.type===a.identifier||c.type===a.property_identifier||c.type===a.name||c.type===a.field_identifier||c.type===a.constant))return c.text}}if(t.type===a.identifier||t.type===a.property_identifier||t.type===a.name||t.type===a.constant)return t.text;if(t.type===a.this){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===a.identifier&&t.text.includes(".")){let n=t.text.split(".");return n[n.length-1]??t.text}if(t.type===a.super){for(let n of e.children)if(n.type===a.identifier||n.type===a.property_identifier)return n.text}if(t.type===Ge){for(let n of e.children)if(n.type===a.identifier||n.type===a.type_identifier||n.type===a.name||n.type===a.scoped_identifier)return n.text}return null}extractImportPaths(e){let t=this.extractPythonImportPaths(e);if(t.length>0)return t;let r=new Set([a.string,a.string_literal,a.string_content,a.interpreted_string_literal,a.interpreted_string_literal_content,a.system_lib_string]),n=new Set([a.dotted_name,a.dotted_identifier,a.scoped_identifier,a.qualified_name,a.module_name,a.namespace_name,a.name,a.identifier]),i=[],s=c=>{if(r.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)s(o);};if(s(e),i.length>0)return i;let d=c=>{if(n.has(c.type)){let o=c.text;(o.startsWith('"')||o.startsWith("'")||o.startsWith("<"))&&(o=o.slice(1,-1)),i.push(o);return}for(let o of c.children)d(o);};return d(e),i}extractPythonImportPaths(e){let t=e.type;if(t!==a.import_statement&&t!==a.import_from_statement)return [];let r=[];if(t===a.import_statement){for(let n of e.children)if(n.type===a.dotted_name)r.push(n.text);else if(n.type===a.aliased_import){let i=n.childForFieldName?.("name");if(i)r.push(i.text);else for(let s of n.children)if(s.type===a.dotted_name||s.type===a.identifier){r.push(s.text);break}}}else for(let n of e.children){if(n.type===a.dotted_name){r.push(n.text);break}if(n.type===a.relative_import){let i=n.childForFieldName?.(a.import_prefix),s=n.childForFieldName?.(a.module_name),d="";i&&(d+=i.text),s&&(d+=s.text),d?r.push(d):r.push(n.text);break}}return r}extractImportWholePath(e){let t=new Set([a.qualified_name,a.scoped_identifier,a.dotted_name,a.dotted_identifier,a.module_name,a.namespace_name,a.namespace_use_clause,a.name,a.identifier,a.string,a.string_literal,a.interpreted_string_literal,a.system_lib_string]);return (n=>{if(t.has(n.type)){let i=n.text;return (i.startsWith('"')||i.startsWith("'")||i.startsWith("<"))&&(i=i.slice(1,-1)),n.type===a.namespace_use_clause&&i.includes(" as ")&&(i=i.split(" as ")[0]??i),i}if(n.type===a.namespace_use_declaration||n.type===a.namespace_use_clause){for(let i of n.children)if(t.has(i.type)){let s=i.text;return (s.startsWith('"')||s.startsWith("'")||s.startsWith("<"))&&(s=s.slice(1,-1)),i.type===a.namespace_use_clause&&s.includes(" as ")&&(s=s.split(" as ")[0]??s),s}}return null})(e)}generateNodeId(e){let t=Filesystem.toUnixPath(e.file_path);return `${e.language}:${t}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,i,s){let d=new Set([a.function_declaration,a.function_definition,a.function_item,a.method_declaration,a.method_definition,a.variable_declaration,a.lexical_declaration,a.property_declaration,a.field_declaration,a.typed_param,a.identifier]),c=new Set([a.field_declaration,a.parameter_declaration,a.parameter]),o=new Set([a.formal_parameters,a.parameter,a.parameter_declaration,a.formal_parameter,a.simple_parameter,a.typed_param,a.argument,a.required_parameter,a.optional_parameter,a.parameter,a.parameters]);this.walkTree(e,l=>{if(d.has(l.type)&&l.type!==a.lexical_declaration&&l.type!==a.variable_declaration){let g=l.childForFieldName?.("name")?.text??ye(l)??A(l)??z(l,[a.function_declarator,a.pointer_declarator,a.declarator]);if(!g)return;let f=null,T=[a.return_type,a.type_annotation,"type",a.pointer_type,a.array_type,a.void_type];for(let y of T){for(let b of l.children)if(b.type===y){f=b;break}if(f)break}let h=new Set([a.type_identifier,a.generic_type,a.array_type,a.identifier,a.struct_specifier,a.class_specifier,a.named_type,a.primitive_type]),x=new Set([a.function_declarator,a.pointer_declarator,a.declarator]);if(!f){for(let y of l.children)if(h.has(y.type)){if(y.type===a.void_type)continue;let b=ye(l);if(b&&y.text===b||x.has(y.type))continue;f=y;break}}let _=new Set([a.type_identifier,a.pointer_type,a.array_type]);if(!f){let y=false;for(let b of l.children){if(b.type==="->"||b.text==="->"){y=true;continue}if(y&&_.has(b.type)){f=b;break}}}if(f){let y=this.extractTypeName(f);if(y&&!ie.void_any_null.has(y)){let b=this.resolveTypeNodeId(y,n,i);b&&r.push({source:this.generateNodeIdFromName(g,l.type,n,i),target:b,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:i});}}let w=W(l,["type_parameter","generic_type"]);if(w){let y=this.extractTypeName(w);if(y){let b=this.resolveTypeNodeId(y,n,i);b&&r.push({source:this.generateNodeIdFromName(g,l.type,n,i),target:b,relation:"TYPE_REFERENCES",line:(w.startPosition?.row??-1)+1,col:(w.startPosition?.column??-1)+1,filePath:i});}}}if(c.has(l.type)){let g=this.findEnclosingClass(l,t);if(g){for(let f of l.children)if(f.type===a.type_identifier){let T=f.text,h=this.resolveTypeNodeId(T,n,i);h&&r.push({source:g.id,target:h,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:i});}}}let p=new Set([a.type_annotation,a.annotation,"type",a.reference_type,a.pointer_type,a.type_identifier,a.struct_specifier,a.class_specifier,a.array_type,a.sized_type_specifier,a.named_type,a.primitive_type,a.slice_type,a.array_type,a.map_type,a.channel_type]);if(o.has(l.type)){for(let g of l.children)if(p.has(g.type)){let f=this.extractTypeName(g);if(f&&!ie.string_number_boolean.has(f)){let T=this.resolveTypeNodeId(f,n,i);if(T){let h=this.findEnclosingFunction(l,t,s);h&&r.push({source:h.id,target:T,relation:"TYPE_REFERENCES",line:(g.startPosition?.row??-1)+1,col:(g.startPosition?.column??-1)+1,filePath:i});}}}if((n==="zig"||n==="csharp")&&l.type===a.parameter&&l.children.length>=2){let g=n==="zig"?2:0,f=l.children[g];if(f&&f.type===a.identifier){let T=f.text;if(T&&!ie.string_number_boolean.has(T)){let h=this.resolveTypeNodeId(T,n,i);if(h){let x=this.findEnclosingFunction(l,t,s);x&&r.push({source:x.id,target:h,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:i});}}}}}if(new Set([a.variable_declaration,a.lexical_declaration,a.public_field_definition,a.field_definition,a.field_declaration,a.property_declaration,a.property_signature,a.assignment]).has(l.type)){let g=this.collectTypeAnnotations(l);for(let f of g){let T=this.extractTypeName(f);if(T&&!ie.string_number_boolean.has(T)&&T!=="any"){let h=this.resolveTypeNodeId(T,n,i);if(h){let x=A(l)??z(l,["variable_declarator"])??A(l);x&&r.push({source:this.generateNodeIdFromName(x,"variable_declaration",n,i),target:h,relation:"TYPE_REFERENCES",line:(f.startPosition?.row??-1)+1,col:(f.startPosition?.column??-1)+1,filePath:i});}}}}});}extractHasMethodEdges(e,t,r){let n=Qe(r),i=Gt(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_METHOD");}extractHasPropertyEdges(e,t,r){let n=Qe(r),i=Qt(r);this.emitContainerToMemberEdges(e,t,n,i,"HAS_PROPERTY");}emitContainerToMemberEdges(e,t,r,n,i){let s=new Map;for(let d of e){let c=s.get(d.file_path);c||(c=[],s.set(d.file_path,c)),c.push(d);}for(let d of s.values()){d.sort((o,l)=>o.start_line-l.start_line);let c=[];for(let o of d){for(;c.length>0&&(c[c.length-1]?.end_line??1/0)<o.start_line;)c.pop();if(r.has(o.ast_type))c.push(o);else if(n.has(o.ast_type)){let l=c[c.length-1];if(l){let p=this.generateNodeId(l),m=this.generateNodeId(o);t.push({source:p,target:m,relation:i});}}}}}extractOverrideEdges(e,t,r,n){let i=L(r),s=new Set;for(let l of i.rawTypes.classTypes)s.add(q(r,l));for(let l of i.rawTypes.interfaceTypes)s.add(q(r,l));let d=e.filter(l=>s.has(l.ast_type));if(d.length===0)return;let c=new Map;for(let l of e){let p=c.get(l.file_path);p||(p=[],c.set(l.file_path,p)),p.push(l);}let o=new Map;for(let l of t)if(l.relation==="EXTENDS"){let p;for(let g of c.values())if(p=g.find(f=>this.generateNodeId(f)===l.target),p)break;if(!p)continue;let m=o.get(l.source);m||(m=[],o.set(l.source,m)),m.push(p);}for(let l of d){let p=o.get(this.generateNodeId(l))??[];if(p.length===0)continue;let m=this.collectMemberIdsByName(l,c,"HAS_METHOD",r);if(m.size===0)continue;let g=new Set,f=[],T=[...p];for(;T.length>0;){let h=T.shift();if(g.has(this.generateNodeId(h)))continue;g.add(this.generateNodeId(h)),f.push(h);let x=o.get(this.generateNodeId(h))??[];T.push(...x);}for(let[h,x]of m){let _=x[0];if(!_)continue;let w=null;for(let y of f){let N=this.collectMemberIdsByName(y,c,"HAS_METHOD",r).get(h);if(!(!N||N.length===0)){w=N[0]??null;break}}if(w&&w!==_){let y=this.generateNodeId(l);if(t.some(P=>P.relation==="METHOD_OVERRIDES"&&P.source===y&&P.target===w))continue;t.push({source:y,target:w,relation:"METHOD_OVERRIDES"});}}}}collectMemberIdsByName(e,t,r,n){let i=new Map,s=t.get(e.file_path);if(!s)return i;let d=new Set([a.method_definition,a.method_declaration,a.function_definition]);for(let c of s)if(d.has(c.ast_type)&&c.start_line>=e.start_line&&c.end_line<=e.end_line){let o=c.metadata?.originalName??c.name,l=c.metadata?.parameterTypes??[],p=l.length>0?`${o}|${l.join(",")}`:o,m=i.get(p);m||(m=[],i.set(p,m));let g=this.generateNodeId(c);m.push(g);}return i}buildImportAliasMap(e,t){let r=new Map;return this.walkTree(e,n=>{if(n.type===a.namespace_use_clause){let i=n.children,s=i.findIndex(d=>d.type==="as");if(s>=0){let d=i.slice(0,s).find(o=>o.type===a.qualified_name),c=i[s+1];d&&c&&c.type===a.name&&c.text&&r.set(c.text,d.text);}}}),r}findEnclosingClass(e,t){let r=e.parent,n=new Set([a.class_declaration,a.class_definition,a.struct_specifier,a.struct_declaration,a.struct_item,a.type_declaration,a.record_declaration,a.class_specifier,a.enum_declaration]);for(;r;){if(n.has(r.type)){let i=A(r)??z(r,[a.type_spec,a.name]);if(i){let s=t.find(l=>l.name===i);if(s)return {id:this.generateNodeId(s),name:i};let d=t[0],c=d?.language??"ts",o=d?.file_path??"";return {id:`${c}:${o}:${r.type}:${i}`,name:i}}}r=r.parent;}return null}extractAnnotationEdges(e,t,r,n,i){let s=L(n),d=new Set(s.rawTypes.annotationTypes),c=new Set(s.annotation.annotatableTypes);this.walkTree(e,o=>{if(d.has(o.type)){let l=this.extractTypeName(o)||A(o);if(!l)return;let p=o.parent;for(;p;){if(c.has(p.type)){let m=A(p),g=p.type;if(!m&&(p.type===a.decorated_definition||p.type===a.export_statement)){let f=z(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]),T=W(p,[a.function_definition,a.class_definition,a.method_definition,a.function_declaration,a.method_declaration]);f&&(m=f,g=T?.type??"function_definition");}if(m){let f=this.generateNodeIdFromName(m,g,n,i),T=Filesystem.toUnixPath(i),h=`${n}:${T}:annotation:${l}`;r.push({source:h,target:f,relation:"ANNOTATES",line:(o.startPosition?.row??-1)+1,col:(o.startPosition?.column??-1)+1,filePath:i});}break}p=p.parent;}}});}extractTypeName(e){if(e.type===a.type_identifier||e.type===a.identifier||e.type===a.predefined_type||e.type===a.name)return e.text;let t=new Set([a.type_identifier,a.identifier,a.name]);for(let n of e.children)if(t.has(n.type))return n.text;for(let n of e.children)if(n.type===a.predefined_type)return n.text;let r=new Set([a.pointer_type,a.reference_type,a.array_type,a.generic_type,a.slice_type,a.map_type,a.channel_type,a.parenthesized_type]);for(let n of e.children)if(r.has(n.type)){let i=this.extractTypeName(n);if(i)return i}return null}resolveTypeNodeId(e,t,r){let n=[a.class_declaration,a.interface_declaration,a.type_alias_declaration,a.type_declaration,a.enum_declaration,a.struct_declaration];for(let i of n)return `${t}:${Filesystem.toUnixPath(r)}:${i}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${Filesystem.toUnixPath(n)}:${q(r,t)}:${e}`}};function Ut(){return new J}var Z=Log.create({service:"codebase-indexer"}),X=class{constructor(e,t,r,n){a$1(this,"db");a$1(this,"parserManager");a$1(this,"nodeExtractor");a$1(this,"edgeExtractor");a$1(this,"config");a$1(this,"writeProxy",null);this.db=e,this.parserManager=t,this.nodeExtractor=new K,this.edgeExtractor=new J,this.config=r,this.writeProxy=n??null;}async flushPendingWrites(){this.writeProxy&&await this.writeProxy.flush();}get dbWriter(){return this.writeProxy?this.writeProxy:this.db}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let i=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(i){let s=new Float32Array(i);return this.dbWriter.cacheEmbedding?.(t,s),s}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],i=0,s=0,d=null;try{let c=this.parserManager.detectLanguage(e);if(!c)throw new f("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let o=await this.readFile(e),l=this.computeHash(o);if(this.config.incremental&&this.db.getFileHash(e)===l)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.dbWriter.deleteEdgesByFile(e),this.db.deleteFtsByFile(e),this.dbWriter.deleteNodesByFile(e),this.writeProxy&&await this.writeProxy.flush(),t?.({currentFile:e,processed:0,total:1,stage:"extracting"}),d=this.parserManager.parse(o,c);let p=this.nodeExtractor.extractNodes(d,o,c,e);i=p.length;let m=this.edgeExtractor.extractEdges(d,p,c,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(p);let g=this.getValidEdgeCount(m,p);this.storeEdges(m,p),s=g,this.config.embedding&&p.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(p)),this.dbWriter.setFileHash(e,l),this.writeProxy&&this.writeProxy.flush();}catch(c){let o=c instanceof Error?c.message:String(c);n.push({filePath:e,error:o});}finally{if(d)try{d.delete();}catch(c){Z.warn("tree.delete failed",{filePath:e,error:String(c)});}}return {success:n.length===0,filesProcessed:1,nodesCreated:i,edgesCreated:s,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,i=[],s=0,d=0,c=0;try{let o=await this.scanFiles(n);for(let f of o.readErrors)i.push(f);let l=o.results,p=l.length,m=0,g=f=>{t&&t({currentFile:f.currentFile,processed:m,total:l.length,stage:f.stage});};for(let f=0;f<l.length;f+=this.config.batchSize){let T=l.slice(f,f+this.config.batchSize),h=await Promise.all(T.map(x=>this.indexFile(x.filePath,g)));for(let x of h)s++,m++,d+=x.nodesCreated,c+=x.edgesCreated,!x.success&&x.errors.length>0&&i.push(...x.errors);}if(t&&l.length>0){let f=l[l.length-1]?.filePath??"";t({currentFile:f,processed:l.length,total:l.length,stage:"storing"});}}catch(o){let l=o instanceof Error?o.message:String(o);i.push({filePath:n,error:l});}return this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush(),{success:i.length===0,filesProcessed:s,nodesCreated:d,edgesCreated:c,errors:i,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,i=0,s=0,d=0,c=0,o=0;try{let g=await this.scanFiles(this.config.workspaceDir),f=g.results;for(let E of g.readErrors)r.push(E);let T=new Set(f.map(E=>E.filePath)),h=this.db.getAllFileHashes(),x=new Set(h.map(E=>E.file_path));for(let E of h)T.has(E.file_path)||(this.dbWriter.deleteFtsByFile?.(E.file_path),this.dbWriter.deleteNodesByFile(E.file_path),this.dbWriter.deleteEdgesByFile(E.file_path),this.dbWriter.deleteFileHash(E.file_path),s++);let _=f.length,w=0,y=E=>{e&&e({currentFile:E.currentFile,processed:w,total:_,stage:E.stage});},b=Math.max(1,this.config.batchSize),N=new Map;for(let E of h)N.set(E.file_path,E.content_hash);for(let E=0;E<f.length;E+=b){let B=f.slice(E,E+b),U=await Promise.all(B.map(R=>{let M=N.get(R.filePath);return M?M!==R.contentHash?this.indexFile(R.filePath,y).then($=>({file:R,kind:"updated",r:$})):Promise.resolve({file:R,kind:"skipped",r:null}):this.indexFile(R.filePath,y).then($=>({file:R,kind:"added",r:$}))}));for(let{kind:R,r:M}of U)R==="skipped"?d++:M&&(M.success?M.nodesCreated===0?d++:(R==="added"?n++:i++,c+=M.nodesCreated,o+=M.edgesCreated):r.push(...M.errors));w+=B.length;}if(e&&_>0){let E=f[f.length-1]?.filePath??"";e({currentFile:E,processed:_,total:_,stage:"storing"});}this.writeProxy&&await this.writeProxy.flush();let P=new Set(this.db.queryAll("SELECT DISTINCT file_path FROM nodes").map(E=>E.file_path)),H=this.db.getAllFileHashes().filter(E=>!P.has(E.file_path)).map(E=>E.file_path);for(let E of H)this.dbWriter.deleteFileHash(E);}catch(g){let f=g instanceof Error?g.message:String(g);r.push({filePath:this.config.workspaceDir,error:f});}this.dbWriter.setLastSync(),this.writeProxy&&await this.writeProxy.flush();let l=new Date().toISOString(),p=Date.now()-t,m={timestamp:l,success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:d,nodesCreated:c,edgesCreated:o,errorCount:r.length,errors:r,duration:p};return this.db.setMeta("lastSyncResult",JSON.stringify(m)),{success:r.length===0,filesAdded:n,filesUpdated:i,filesDeleted:s,filesSkipped:d,nodesCreated:c,edgesCreated:o,errors:r,duration:p}}async scanFiles(e){let t=[],r=[],i=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(h=>`**/*${h}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts","**/.easbot/**","**/.codebase/**"],d=this.config.ignorePatterns.map(h=>h.includes("/")||h.includes("*")?h:`**/${h}/**`),c=[...s,...d],o=await this.loadGitignore(e),l=new Set;for(let h of i){let x=await Glob.scan(h,{cwd:e,absolute:true,include:"file",dot:false,symlink:false,ignore:c});for(let _ of x)l.has(_)||l.add(_);}let p=Array.from(l),m=Filesystem.toUnixPath(e),g=o?p.filter(h=>!o.ignores(this.toRelativePosix(h,m),false)):p,f=Math.max(1,Number.parseInt(process.env.EASBOT_SCAN_BATCH_SIZE??"50",10)||50),T=[];for(let h of g){let x=Filesystem.normalize(h);this.parserManager.detectLanguage(x)&&T.push(x);}for(let h=0;h<T.length;h+=f){let x=T.slice(h,h+f),_=await Promise.all(x.map(async w=>{try{let y=await this.readFile(w),b=this.computeHash(y),N=this.parserManager.detectLanguage(w);return N?{filePath:w,language:N,contentHash:b,content:y}:null}catch(y){let b=y instanceof Error?y.message:String(y);return r.push({filePath:w,error:b}),Z.warn("scanFiles read failed",{filePath:w,error:b}),null}}));for(let w of _)w&&t.push(w);}return {results:t,readErrors:r}}async loadGitignore(e){try{let t=`${Filesystem.toUnixPath(e)}/.gitignore`,r=await Ue.readFile(t,"utf-8"),n=Ignore.create();return n.add(r),Z.debug("Loaded .gitignore",{path:t,lines:r.split(`
|
|
188
|
-
`).length}),n}catch(t){return t.code!=="ENOENT"&&Z.warn("Failed to read .gitignore, falling back to defaultIgnore only",{error:String(t)}),null}}toRelativePosix(e,t){let r=Filesystem.toUnixPath(e),n=Filesystem.toUnixPath(t),i=r;return n&&i.startsWith(n)&&(i=i.slice(n.length)),(n.endsWith("/")&&i.startsWith("/")||i.startsWith("/"))&&(i=i.slice(1)),i}async readFile(e){try{return await Ue.readFile(e,"utf-8")}catch(t){throw new c("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.dbWriter.insertNodes(t),e.length>0&&this.storeNameSegments(e);}storeNameSegments(e){let t=[];for(let r of e){let n=this.splitIdentifier(r.name);for(let i of n)i.length>0&&t.push({segment:i,name:r.name});}if(t.length!==0)try{this.db.insertNameSegmentsBatch(t);}catch(r){Z.warn("insertNameSegmentsBatch failed, falling back to per-row insert",{batchSize:t.length,error:String(r)});for(let{segment:n,name:i}of t)try{this.db.insertNameSegment(n,i);}catch(s){Z.warn("insertNameSegment failed",{nodeName:i,segment:n,error:String(s)});}}}splitIdentifier(e){if(!e||e.length===0)return [];let t=[],i=e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");for(let s of i.split(/\s+/)){let d=s.toLowerCase();d.length>0&&t.push(d);}return t}storeEdges(e,t){let r=new Set(t.map(i=>this.nodeExtractor.generateNodeId(i))),n=e.filter(i=>i.source!==i.target&&r.has(i.source)&&r.has(i.target)).map((i,s)=>({id:`${i.source}:${i.relation}:${i.target}:${s}`,source:i.source,target:i.target,relation:i.relation,created_at:new Date().toISOString()}));n.length>0&&this.dbWriter.insertEdges(n),this.storeUnresolvedRefs(e,t,r);}storeUnresolvedRefs(e,t,r){let n=new Map,i=(o,l)=>{let p=n.get(o);p||(p=[],n.set(o,p)),p.includes(l)||p.push(l);};for(let o of t){let l=this.nodeExtractor.generateNodeId(o);i(o.name,l);let p=o.metadata?.originalName;typeof p=="string"&&p.length>0&&i(p,l);let m=o.name.lastIndexOf("@");if(m>0){let g=o.name.slice(0,m),f=g.lastIndexOf(".");f>0&&i(g.slice(f+1),l);}}let s=t[0]?.file_path??"",d=t[0]?.language??"unknown",c=[];for(let o of e){let l=r.has(o.source),p=r.has(o.target);if(l&&p)continue;let m=l?o.target:o.source,g=l?o.source:r.has(o.target)?o.target:void 0,f=m.includes(":")?m.split(":").pop()??m:m,T=n.get(f)??[];c.push({fromNodeId:g,referenceName:m,referenceKind:o.relation,line:o.line,col:o.col,filePath:o.filePath??s,language:d,candidates:T.length>0?T:void 0});}c.length!==0&&this.dbWriter.insertUnresolvedRefsBatch(c);}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[],i=4,s=r.map((c,o)=>({index:o,batch:c})),d=[];for(let c=0;c<s.length;c+=i){let o=s.slice(c,c+i),l=await Promise.all(o.map(async({index:p,batch:m})=>{let g=[],f=m.map(T=>this.generateNodeEmbeddingText(T));try{let T=await this.config.embedding.doEmbed({values:f});for(let h=0;h<m.length;h++){let x=m[h];if(!x)continue;let _=T.embeddings[h];if(_){let w=new Float32Array(_),y=this.computeHash(this.generateNodeEmbeddingText(x));this.dbWriter.cacheEmbedding?.(y,w),g.push({nodeId:this.nodeExtractor.generateNodeId(x),embeddingText:f[h]||"",embedding:w});}}}catch{for(let h of m){if(!h)continue;let x=this.generateNodeEmbeddingText(h),_=await this.embedText(x);_&&g.push({nodeId:this.nodeExtractor.generateNodeId(h),embeddingText:x,embedding:_});}}return {index:p,embeddings:g}}));d.push(...l);}d.sort((c,o)=>c.index-o.index);for(let c of d)n.push(...c.embeddings);n.length>0&&this.dbWriter.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function Zt(u,e,t){return new X(u,e,t)}function ve(u){if(!u)return [];let e=u.split(/[^a-zA-Z0-9]+/),t=[];for(let r of e){if(!r)continue;let n=r.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);n&&t.push(...n);}return t.map(r=>r.toLowerCase()).filter(r=>r.length>0)}function Ve(u,e){if(u.length===0||e.length===0)return 0;let t=0;for(let r of u)e.includes(r)&&t++;return t/u.length}function Ye(u,e,t={}){let r=t.limit??20,n=t.minScore??.2;if(!u)return [];let i=ve(u),s=[];for(let d of e){let c=d.id.split(":").pop()??"";if(c===u||d.name===u){s.push({nodeId:d.id,score:1,matchedPart:"full"});continue}let o=ve(c),l=ve(d.name),p=Ve(i,o),m=Ve(i,l),g=Math.max(p,m);g>=n&&s.push({nodeId:d.id,score:g,matchedPart:g>=.99?"full":"segment"});}return s.sort((d,c)=>c.score-d.score),s.slice(0,r)}var Ie=Filesystem.toUnixPath,v=Log.create({service:"codebase.query"}),tr=new Set(["AND","OR","NOT","NEAR"]),rr=/[\p{L}\p{N}_]/u;function nr(u){return u?u.split(/\s+/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!tr.has(t.toUpperCase())).filter(t=>rr.test(t)).join(" "):""}var ee=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a$1(this,"db");a$1(this,"embedding");a$1(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:i,filePath:s,astType:d,enableFts:c=true,includeEdges:o=true,edgesLimit:l=100,vectorWeight:p=this.config.hybrid.vectorWeight,textWeight:m=this.config.hybrid.textWeight,enableEmbedding:g=true}=t;v.debug("search() called",{query:e,astType:d,language:i,enableEmbedding:g,enableFts:c,minScore:n});let f=[],T=new Map;if(g&&this.embedding){let _=await this.vectorSearchNodes(e,r*2,n);v.debug("vectorSearchNodes results",{count:_.length,astTypeFilter:d});for(let w of _){if(i&&w.language!==i||d&&w.astType!==d)continue;let y={...w,source:"vector",vectorScore:w.score,hybridScore:w.score*p};f.push(y),T.set(y.id,y);}v.debug("after vector filter",{resultsCount:f.length});}if(c&&this.db.isFtsAvailable()){let _=nr(e);_||v.debug("FTS query sanitized to empty \u2014 skipping FTS",{originalQuery:e});let w=_?this.db.searchNodesFts(_,r*2):[];v.debug("FTS results before filter",{count:w.length});for(let y of w){if(i&&y.language!==i||s&&!y.file_path.includes(Ie(s))||d&&y.ast_type!==d)continue;let b=this.normalizeScore(y.score),N=T.get(y.id);if(N)N.ftsScore=b,N.hybridScore=N.vectorScore*p+b*m;else {let P={id:y.id,name:y.name,astType:y.ast_type,language:y.language,filePath:y.file_path,text:y.text,snippet:y.text.slice(0,200),startLine:y.start_line,startCol:y.start_col,endLine:y.end_line,endCol:y.end_col,score:b,source:"fts",ftsScore:b,hybridScore:b*m};f.push(P),T.set(P.id,P);}}v.debug("after FTS filter",{resultsCount:f.length});}if(!c||!this.db.isFtsAvailable()||f.length===0){try{let _=this.db.queryNodes({limit:r*2,astType:d,language:i,filePath:s}),w=new Set(f.map(E=>E.id)),y=e.toLowerCase(),b=y.split(/\s+/).filter(E=>E.length>0),N=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),P=b.map(E=>({term:E,regex:new RegExp(N(E),"gi")})),H=[];for(let E of _){if(s&&!E.file_path.includes(Ie(s)))continue;let B=E.name.toLowerCase(),U=E.text.toLowerCase(),R=0;if(P.some(({term:D})=>B.includes(D))){let D=0;for(let{regex:oe}of P){let ce=B.match(oe);D+=ce?ce.length:0;}R=.8*Math.min(D/P.length,1);}let M=0;if(P.some(({term:D})=>U.includes(D))){let D=0;for(let{regex:rt}of P){let ke=U.match(rt);D+=ke?ke.length:0;}M=.5*Math.min(D/P.length,1);let oe=U.indexOf(y),ce=oe===-1?0:Math.max(0,1-oe/U.length)*.2;M+=ce;}let $=Math.max(R,M);$>0&&H.push({id:E.id,name:E.name,astType:E.ast_type,language:E.language,filePath:E.file_path,text:E.text,snippet:E.text.slice(0,200),startLine:E.start_line,startCol:E.start_col,endLine:E.end_line,endCol:E.end_col,score:$,source:"basic",hybridScore:$});}H.sort((E,B)=>B.score-E.score),f.push(...H.slice(0,r));}catch{}if(f.length===0)try{let _=this.db.queryNodes({limit:1e3}),w=Ye(e,_,{limit:r,minScore:.5});v.debug("name-segment matches",{count:w.length,query:e});for(let y of w){let b=this.db.getNodeById(y.nodeId);if(!b||i&&b.language!==i||d&&b.ast_type!==d||s&&!b.file_path.includes(Ie(s)))continue;let N={id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text??"",snippet:(b.text??"").slice(0,200),startLine:b.start_line??0,startCol:b.start_col??0,endLine:b.end_line??0,endCol:b.end_col??0,score:y.score,source:"structural",hybridScore:y.score};f.push(N),T.set(N.id,N);}}catch(_){v.debug("name-segment channel error",{error:_ instanceof Error?_.message:String(_)});}}let x=f.filter(_=>_.hybridScore>=n).sort((_,w)=>w.hybridScore-_.hybridScore).slice(0,r).map(_=>({id:_.id,name:_.name,ast_type:_.astType,language:_.language,file_path:_.filePath,start_line:_.startLine,start_col:_.startCol,end_line:_.endLine,end_col:_.endCol,text:_.text,created_at:new Date().toISOString()}));if(o&&x.length>0){let _=x.map(b=>b.id),w=this.db.queryEdges({sourceOrTarget:_}),y=new Map;for(let b of w)b.source!==b.target&&(y.has(b.source)||y.set(b.source,[]),y.get(b.source).push(b));return x.map(b=>{let N=y.get(b.id)||[];return {...b,edges:N.slice(0,l)}})}return x.map(_=>({..._,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(v.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return v.debug("vectorSearchNodes skip - no embedding model"),[];let i=await this.embedText(e);if(!i)return v.debug("vectorSearchNodes skip - no embedding result"),[];let s=new Float32Array(i),d,c=5e3;if(n&&n.length>0){let g=n.map(()=>"?").join(",");d=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${g})`,n);}else d=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[c]);v.debug("vectorSearchNodes vectors loaded",{count:d.length});let o=[];for(let g of d){let f=new Float32Array(g.embedding.buffer,g.embedding.byteOffset,g.embedding.length/4),T=this.cosineSimilarity(s,f);T<r||(o.push({nodeId:g.node_id,score:T}),o.length>t&&(o.sort((h,x)=>x.score-h.score),o.splice(t)));}if(o.length===0)return v.debug("vectorSearchNodes done - no results above minScore"),[];o.sort((g,f)=>f.score-g.score);let l=o.map(g=>g.nodeId);v.debug("vectorSearchNodes query nodes",{nodeIdsCount:l.length});let p=this.db.queryNodes({ids:l}),m=new Map(o.map(g=>[g.nodeId,g.score]));return v.debug("vectorSearchNodes done",{nodesFound:p.length}),p.map(g=>({id:g.id,name:g.name,astType:g.ast_type,language:g.language,filePath:g.file_path,text:g.text??"",snippet:(g.text??"").slice(0,200),startLine:g.start_line??0,startCol:g.start_col??0,endLine:g.end_line??0,endCol:g.end_col??0,score:m.get(g.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({sourceOrTarget:[e.id],limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,i=0;for(let s=0;s<e.length;s++){let d=e[s],c=t[s];r+=d*c,n+=d*d,i+=c*c;}return n===0||i===0?0:r/(Math.sqrt(n)*Math.sqrt(i))}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){v.debug("queryNodes() called",{language:e.language,astType:e.astType,filePath:e.filePath?.slice(0,80),name:e.name,limit:e.limit});try{return this.db.queryNodes(e)}catch(t){throw new g("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){v.debug("queryEdges() called",{source:e.source?.split(":").slice(-2).join(":"),target:e.target?.split(":").slice(-2).join(":"),sourceOrTarget:Array.isArray(e.sourceOrTarget)?e.sourceOrTarget.map(t=>t.split(":").slice(-2).join(":")):void 0,relation:e.relation,limit:e.limit});try{return this.db.queryEdges(e)}catch(t){throw new g("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let i=this.db.getNodeById(n.source),s=this.db.getNodeById(n.target);i&&s&&r.push({edge:n,sourceNode:i,targetNode:s});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:i=100}=t;v.debug("queryNeighbors() called",{nodeId:e.split(":").slice(-2).join(":"),relationTypes:r,direction:n,limit:i});let s=[],d=[],c=new Set,o=new Set,l=r&&r.length>0?r:[void 0],p=m=>{for(let g of l){let f=g===void 0?{}:{relation:g},T=m==="outgoing"?this.db.queryEdges({source:e,...f,limit:i}):this.db.queryEdges({target:e,...f,limit:i});for(let h of T){if(o.has(h.id))continue;o.add(h.id),s.push(h);let x=m==="outgoing"?h.target:h.source,_=this.db.getNodeById(x);_&&!c.has(_.id)&&(d.push(_),c.add(_.id));}}};return (n==="outgoing"||n==="both")&&p("outgoing"),(n==="incoming"||n==="both")&&p("incoming"),{nodes:d.slice(0,i),edges:s.slice(0,i)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,i=(s,d)=>{if(d>t||n.has(s))return;n.add(s);let c=[],o=[],l=this.db.queryEdges({target:s,relation:"CALLS"});for(let m of l)c.push(m.source),i(m.source,d+1);let p=this.db.queryEdges({source:s,relation:"CALLS"});for(let m of p)o.push(m.target),i(m.target,d+1);r.set(s,{callers:c,callees:o});};return i(e,0),r}queryInheritance(e){v.debug("queryInheritance() called",{nodeId:e.split(":").slice(-2).join(":")});let t=[],r=[],n=new Set,i=new Set,s=c=>{if(n.has(c))return;n.add(c);let o=this.db.queryEdges({source:c,relation:"EXTENDS"}),l=this.db.queryEdges({source:c,relation:"IMPLEMENTS"});for(let p of [...o,...l]){let m=this.db.getNodeById(p.target);m&&(t.push(m),s(p.target));}},d=c=>{if(i.has(c))return;i.add(c);let o=this.db.queryEdges({target:c,relation:"EXTENDS"}),l=this.db.queryEdges({target:c,relation:"IMPLEMENTS"});for(let p of [...o,...l]){let m=this.db.getNodeById(p.source);m&&(r.push(m),d(p.source));}};return s(e),d(e),{ancestors:t,descendants:r}}queryMembers(e,t){let r=t?Array.isArray(t)?t:[t]:["HAS_METHOD","HAS_PROPERTY"],n=[],i=new Set;for(let s of r){let d=this.db.queryEdges({source:e,relation:s});for(let c of d){if(i.has(c.target))continue;i.add(c.target);let o=this.db.getNodeById(c.target);o&&n.push(o);}}return n}queryOverrides(e){let t=this.db.queryEdges({source:e,relation:"METHOD_OVERRIDES"}),r=[],n=new Set;for(let i of t){if(n.has(i.target))continue;n.add(i.target);let s=this.db.getNodeById(i.target);s&&r.push(s);}return r}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function ir(u){return new ee(u)}function Ze(u){return join(u,".easbot")}function zn(u){return join(Ze(u),"codebase.json")}function sr(u){return join(Ze(u),"db","codebase.db")}function Hn(u){let e=dirname(sr(u));existsSync(e)||mkdirSync(e,{recursive:true});}function Xe(u){existsSync(u)||mkdirSync(u,{recursive:true});}var I=Log.create({service:"codebase"}),mr={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},Ce=class{constructor(e={}){a$1(this,"config");a$1(this,"db");a$1(this,"writeBackend",null);a$1(this,"writeProxy",null);a$1(this,"parserManager");a$1(this,"indexer");a$1(this,"queryInterface");a$1(this,"initialized",false);a$1(this,"dirty",false);a$1(this,"syncTimer");a$1(this,"syncingInProgress",false);a$1(this,"codebasePackageVersion");a$1(this,"fileWatcher",null);this.config={...mr,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm,graphLlm:e.graphLlm},a$3.init({models:{graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm}}),this.validateConfig();let n$1=this.resolveDbPath();Xe(V.dirname(n$1)),this.db=new n(n$1),this.parserManager=new Y,this.queryInterface=new ee(this.db,this.config.embeddingLlm,this.config.search),this.codebasePackageVersion=yr();}get dbWriter(){return this.writeProxy??this.db}async initialize(){if(!this.initialized){this.db.initialize(),await this.parserManager.initialize(),this.writeBackend=new ge({dbPath:this.db.getDbPath()}),await this.writeBackend.ready,this.writeProxy=new le(this.db,this.writeBackend,{ftsAvailable:this.db.isFtsAvailable()}),this.indexer=new X(this.db,this.parserManager,{workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm},this.writeProxy);try{let e=this.config.workspaceDir??"";this.db.setProjectMetadata("worktree",e),this.db.setProjectMetadata("project",e),this.db.setProjectMetadata("version",this.codebasePackageVersion),this.db.setProjectMetadata("language","ts");}catch(e){I.warn("setProjectMetadata failed",{error:String(e)});}this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>I.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,I.info("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0});}}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){I.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{I.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{I.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new e("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new e("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return V.isAbsolute(e)?e:V.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return I.info("sync skipped \u2014 another sync is already in progress"),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0,skipped:true};this.syncingInProgress=true,this.dbWriter.setIndexState("indexing");try{let t=await this.indexer.sync(e),r=new Date().toISOString();return t.errors.length===0?this.dbWriter.markIndexed(this.codebasePackageVersion,m,r):t.nodesCreated>0||t.filesAdded>0||t.filesUpdated>0?(this.dbWriter.markIndexed(this.codebasePackageVersion,m,r),this.dbWriter.setIndexState("partial")):this.dbWriter.setIndexState("failed"),I.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),this.writeProxy&&await this.writeProxy.flush(),t}catch(t){throw this.dbWriter.setIndexState("failed"),this.writeProxy&&await this.writeProxy.flush(),t}finally{this.syncingInProgress=false;}}async watch(e){if(await this.ensureInitialized(),this.fileWatcher)return I.warn("watch already running, returning existing instance"),{stop:()=>this.fileWatcher.stop()};let{FileWatcher:t}=await import('./file-watcher-OORREWFV.mjs'),r=this.config.workspaceDir,n=e?.debounceMs??200,i=e?.initialSync??true,s=new t({workspaceDir:r,ignorePatterns:e?.ignorePatterns??this.config.indexer?.ignorePatterns});this.fileWatcher=s;try{await s.start();}catch(p){throw this.fileWatcher=null,p}let d=null,c=new Set,o=()=>{d=null;let p=c.size;c.clear(),p!==0&&(I.info("file-watcher triggered sync",{changedFiles:p}),this.sync().catch(m=>{I.error("auto-sync after file change failed",{error:m instanceof Error?m.message:String(m)});}));},l=()=>{d&&clearTimeout(d),d=setTimeout(o,n);};return s.on((p,m)=>{I.debug("file change",{event:p,relPath:m}),c.add(m),l();}),i&&this.sync().catch(p=>{I.warn("initial sync in watch failed",{error:p instanceof Error?p.message:String(p)});}),I.info("file watcher started",{workspaceDir:r,debounceMs:n}),{stop:async()=>{d&&(clearTimeout(d),d=null),await s.stop(),this.fileWatcher=null,I.info("file watcher stopped");}}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async queryMembers(e,t){return await this.ensureInitialized(),this.queryInterface.queryMembers(e,t)}async queryOverrides(e){return await this.ensureInitialized(),this.queryInterface.queryOverrides(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized,indexState:e.indexState,extractionVersion:e.extractionVersion,isStale:e.isStale,indexedWithVersion:e.meta.indexed_with_version,lastSync:e.meta.lastSync}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(e={}){this.db.clearAll({keepEmbeddings:e.keepEmbeddings});}async close(){if(this.initialized){if(this.stopSyncTimer(),this.fileWatcher){try{await this.fileWatcher.stop();}catch(e){I.warn("fileWatcher stop during close failed",{error:String(e)});}this.fileWatcher=null;}if(this.writeProxy)try{await this.writeProxy.flush();}catch(e){I.warn("writeProxy flush during close failed",{error:String(e)});}if(this.writeBackend){try{await this.writeBackend.dispose();}catch(e){I.warn("writeBackend dispose during close failed",{error:String(e)});}this.writeBackend=null;}this.writeProxy=null,this.db.close(),this.parserManager.dispose(),this.initialized=false,I.info("Codebase closed");}}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}getWorkspaceDir(){return this.config.workspaceDir??process.cwd()}};async function oi(u){let e=new Ce(u);return await e.initialize(),e}function yr(){try{let e=V.dirname(fileURLToPath(import.meta.url));for(let t=0;t<8;t++){let r=V.join(e,"package.json");try{let i=JSON.parse(readFileSync(r,"utf-8"));if(i&&i.name==="@easbot/codebase"&&typeof i.version=="string")return i.version}catch{}let n=V.dirname(e);if(n===e)break;e=n;}}catch{}return "0.0.0"}export{Ze as a,zn as b,sr as c,Hn as d,ze as e,Le as f,Y as g,Pt as h,Ct as i,K as j,jt as k,J as l,Ut as m,X as n,Zt as o,Ye as p,ee as q,ir as r,Ce as s,oi as t};
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import {c,s,p}from'./chunk-AGZFRKQ4.mjs';import {a}from'./chunk-TMICZT3L.mjs';import {Log,Filesystem,TruncateContent}from'@easbot/utils';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';var R=class extends Error{constructor(n,l,a$1){super(n);a(this,"code",l);a(this,"details",a$1);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},F=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};Log.create({service:"codebase-service"});var E=Filesystem.toUnixPath;async function _(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=E(n.file),r=a.filter(d=>E(d.file_path).endsWith(o)||E(d.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(d=>d.ast_type.includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let c=p(n.name,a,{limit:10,minScore:.5});if(c.length===0)throw new P(n.name);if(c.length===1){let o=e.getNode(c[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:c.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of c){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new F(n.name,s)}async function S(e){let t=c(e.rootDir),n=new s({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:DEFAULT_EMBEDDING_CONFIG,indexer:DEFAULT_INDEXER_CONFIG,parser:DEFAULT_PARSER_CONFIG,search:DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function pe(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:E(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function J(e,t){let n=Date.now(),c=await(await S(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();c=c.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=E(t.file);c=c.filter(r=>E(r.file_path).endsWith(o)||E(r.file_path).includes(o));}let s=c.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:E(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function me(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await _(l,e,t),c=[];if(t.includeEdges){let s=t.edgesLimit??50;c=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:c}}var ge=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function fe(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await _(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,d=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;d.length>0;){let g=d.shift();if(g.depth>=c)continue;if(r.size>=s){u=true;break}let h=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??ge,limit:s-r.size+1});for(let y of h.edges){p.push(y);let $=y.source===g.nodeId?y.target:y.source;if(!r.has($)&&(r.set($,g.depth+1),d.push({nodeId:$,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),b=m.length>0?a.queryNodes({ids:m}):[],f=new Map(b.map(g=>[g.id,g])),x=[];for(let[g,h]of r.entries()){let y=f.get(g);y&&x.push({node:y,depth:h});}return {root:i,nodes:x,edges:p,truncated:u,totalNodes:x.length,totalEdges:p.length}}var he=["CALLS","IMPORTS","TYPE_REFERENCES"];async function ye(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await _(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,s=t.maxResults??50,o=t.relationTypes??he,r=new Set([i.id]),d=[],p=[i.id];for(let u=1;u<=c&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),b=o.map(()=>"?").join(","),f=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${b})`,[...p,...o]),x=[],g=new Set;for(let h of f)if(!r.has(h.source)&&!g.has(h.source)&&(g.add(h.source),r.add(h.source),x.push(h.source),r.size-1>=s))break;if(x.length>0){let h=x.slice(0,10),y=a.queryNodes({ids:h}),$=new Map(y.map(L=>[L.id,L])),se=h.map(L=>{let U=$.get(L);return {id:L,name:U?.name??"(unknown)",filePath:U?E(U.file_path):"(unknown)",relation:"CALLS"}});d.push({depth:u,count:x.length,sample:se});}p=x;}return {root:i,totalImpacted:r.size-1,buckets:d}}var be=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function xe(e,t){return O(e,t,"incoming")}async function Ee(e,t){return O(e,t,"outgoing")}async function O(e,t,n,l){let a=await S(e),i=a.getQuery(),c=a.getDatabase(),{node:s}=await _(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??be,d=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of d.edges){let b=pe(m,s.id,c,n==="incoming"?"in":"out");b&&p.push(b);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ne(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await S(e);l.getQuery();l.getDatabase();let s=(await J(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=E(p.filePath),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,d=[];for(let[p,u]of o){let m=u.slice(0,r),b=[];for(let f of m){let x=await O(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await O(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"outgoing");b.push({node:{id:f.nodeId,name:f.name,ast_type:f.kind,language:"ts",file_path:f.filePath,start_line:f.startLine??0,end_line:f.endLine??0,text:""},callers:x.callers,callees:g.callers});}d.push({file:p,symbols:b});}return {query:t.query,entryPoints:d,totalHits:s.length}}async function Re(e,t){return await(await S(e)).getStatus()}async function Pe(e,t){return await(await S(e)).healthCheck()}var Z=Filesystem.toUnixPath;function Ce(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Ie(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function N(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Z(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Ce(e),modifiers:Ie(e)}}function T(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function K(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:Z(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(n=>T({...n}))}))}function j(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var $e=Log.create({service:"codebase-format-truncate"}),z="**`",Le="**",te=24e3,ne=25e3;async function D(e,t={}){let n=t.softLimit??te,l=t.hardCeiling??ne,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,l),s=c.lastIndexOf(`
|
|
2
|
-
${z}`),o=c.lastIndexOf(`
|
|
3
|
-
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let d=r>0?c.slice(0,r):c,u=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(m){return $e.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function v(e,t={}){let n=t.softLimit??te,l=t.hardCeiling??ne;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
|
-
${z}`),c=a.lastIndexOf(`
|
|
5
|
-
`),s;i>l*.5?s=i:c>0?s=c:s=-1;let o=s>0?a.slice(0,s):a;return {content:o+`
|
|
6
|
-
|
|
7
|
-
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}function Fe(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function H(e,t){if(!e||e.length===0)return null;let n=e.filter(a=>t.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${Fe(a.lastEventAt)})`).join(", ")}
|
|
8
|
-
|
|
9
|
-
`}function w(e,t,n={}){return (re[e]??re.default).replace(/<(\w+)>/g,(a,i)=>i==="tool"?t:n[i]??`<${i}>`)}var re={search:`---
|
|
10
|
-
|
|
11
|
-
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
12
|
-
> If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
|
|
13
|
-
|
|
14
|
-
> **Output truncated to budget; the content above is the source of truth.**
|
|
15
|
-
> For more detail, call \`<tool>\` with refined parameters.`};async function M(e,t){let{pendingFiles:n,toolName:l,sync:a=false}=t;if(e.length===0)return k(l,"No matches found.","Try broader search terms, or use `explore` to read source.");let i=ke(e),c=new Set(i.keys()),s=[];s.push(H(n,c)??"");let o="[[codebase-search-summary]]";s.push(o+`
|
|
16
|
-
`);let r=e.length;s.push(`**Files with matches:** ${i.size}
|
|
17
|
-
`);for(let[m,b]of i){let f=b.map(y=>y.node.name),x=f.slice(0,5).join(", "),g=f.length>5?`, +${f.length-5} more`:"";s.push(`**\`${m}\`** \u2014 ${x}${g}
|
|
18
|
-
`);let h=b[0]?.node.language??"";s.push("```"+h);for(let y of b)s.push(`L${y.node.startLine} ${y.snippet}`);s.push("```\n");}s.push(w("search",l,{}));let d=s.join(`
|
|
19
|
-
`),p=`Found ${r} symbol${r===1?"":"s"} across ${i.size} file${i.size===1?"":"s"}.`,u=d.replace(o,p);return A(u,t,a)}async function q(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(t.length===0||t.every(r=>r.count===0))return k(a,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let c=t.reduce((r,d)=>r+d.count,0),s=we(c),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${c})
|
|
20
|
-
`);for(let r of t){o.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let d of r.samples.slice(0,5))o.push(` - \`${d.name}\` ${d.file}:${d.line} [${d.relation}]`);r.samples.length>5&&o.push(` - ... and ${r.samples.length-5} more`);}return o.push(w("impact",a,{root:e.name,riskLevel:s})),A(o.join(`
|
|
21
|
-
`),n,i)}function we(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function Q(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function Y(e,t){let{root:n,incoming:l,outgoing:a,neighbors:i}=e,{pendingFiles:c,toolName:s,sync:o=false}=t;if(l.length===0&&a.length===0&&i.length===0)return k(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(H(c,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
|
|
22
|
-
`),r.push(`**Incoming** (${l.length}):`);for(let d of l.slice(0,10))r.push(`- ${d.source} \u2192 [${d.relation}] \u2192 \`${n.name}\``);l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let d of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${d.relation}] \u2192 ${d.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),i.length>0){r.push(`**Neighbors** (${i.length}):`);for(let d of i.slice(0,20))r.push(`- [d=${d.depth}] \`${d.node.name}\` (${d.node.astType}) ${d.node.filePath}:${d.node.startLine}`);i.length>20&&r.push(`- ... and ${i.length-20} more`),r.push("");}return r.push(w("context",s,{})),A(r.join(`
|
|
23
|
-
`),t,o)}async function B(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(!e.id)return k(a,"Node not found.","Check the node ID or use `search` to find it.");let c=t.filter(r=>r.direction==="in"),s=t.filter(r=>r.direction==="out"),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Node: \`${e.name}\`**
|
|
24
|
-
`),o.push(`- ID: \`${e.id}\``),o.push(`- Kind: ${e.astType}`),o.push(`- Language: ${e.language}`),o.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),o.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&o.push(`- Modifiers: ${e.modifiers.join(", ")}`),o.push(""),o.push(`**Edges** (incoming: ${c.length} / outgoing: ${s.length}):`);for(let r of c.slice(0,5))o.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))o.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&o.push(`- ... and ${t.length-10} more`),o.push(w("default",a,{})),A(o.join(`
|
|
25
|
-
`),n,i)}async function oe(e,t){let{entryPoints:n,totalHits:l,query:a}=e,{toolName:i,sync:c=false}=t;if(n.length===0)return k(i,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
|
|
26
|
-
`),s.push(`**Query:** ${a} `),s.push(`**Total hits:** ${l} `),s.push(`**Entry points:** ${n.length}
|
|
27
|
-
`);for(let o of n){s.push(`**\`${o.file}\`** \u2014 ${o.symbols.length} symbol${o.symbols.length===1?"":"s"}
|
|
28
|
-
`);for(let r of o.symbols){let d=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(d),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
|
|
29
|
-
`),s.push(w("context",i,{})),A(s.join(`
|
|
30
|
-
`),t,c)}function ke(e){let t=new Map;for(let n of e){let l=n.node.filePath,a=t.get(l);a?a.push(n):t.set(l,[n]);}return t}function k(e,t,n){return `**${e}**
|
|
31
|
-
|
|
32
|
-
${t}
|
|
33
|
-
|
|
34
|
-
> **Tip:** ${n}`}async function A(e,t,n){let l={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?v(e,l):await D(e,l)).content}var Oe=Log.create({service:"codebase-format-render"});async function _e(e,t){if(e.length===0)return M([],t);let n=K(e);return M(n,t)}async function De(e,t,n){if(t.length===0)return q(N(e),[],n);let l=[{depth:1,count:t.length,riskLabel:Q(1),samples:t.slice(0,10).map(a=>({name:a.source.name,file:N(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return q(N(e),l,n)}async function ve(e,t,n,l,a){let i=N(e),c=t.map(r=>T(r,"in")),s=n.map(r=>T(r,"out")),o=l.map(r=>({node:N(r),depth:1}));return Y({root:i,incoming:c,outgoing:s,neighbors:o},a)}async function He(e,t,n){if(!e)return B(j(),[],n);let l=N(e),a=t.map(i=>{let c=i.target===e.id?"in":"out";return T(i,c)});return B(l,a,n)}async function Me(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(l=>({file:l.file,symbols:l.symbols.map(a=>({node:N(a.node),source:a.node.text??"",callers:a.callers.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation})),callees:a.callees.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation}))}))}))};return oe(n,t)}Oe.debug("format/render.ts loaded");export{De as A,ve as B,He as C,Me as D,R as a,P as b,F as c,J as d,me as e,fe as f,ye as g,xe as h,Ee as i,Ne as j,Re as k,Pe as l,N as m,T as n,K as o,j as p,z as q,Le as r,D as s,v as t,M as u,q as v,Q as w,Y as x,B as y,_e as z};
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkVFTVDTEY_cjs=require('./chunk-VFTVDTEY.cjs'),chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),types=require('@easbot/types');var R=class extends Error{constructor(n,l,a){super(n);chunkNVGACA7W_cjs.a(this,"code",l);chunkNVGACA7W_cjs.a(this,"details",a);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},L=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};utils.Log.create({service:"codebase-service"});var E=utils.Filesystem.toUnixPath;async function O(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=E(n.file),r=a.filter(d=>E(d.file_path).endsWith(o)||E(d.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(d=>d.ast_type.includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let c=chunkVFTVDTEY_cjs.p(n.name,a,{limit:10,minScore:.5});if(c.length===0)throw new P(n.name);if(c.length===1){let o=e.getNode(c[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:c.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of c){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new L(n.name,s)}async function S(e){let t=chunkVFTVDTEY_cjs.c(e.rootDir),n=new chunkVFTVDTEY_cjs.s({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:types.DEFAULT_EMBEDDING_CONFIG,indexer:types.DEFAULT_INDEXER_CONFIG,parser:types.DEFAULT_PARSER_CONFIG,search:types.DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:E(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function V(e,t){let n=Date.now(),c=await(await S(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();c=c.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=E(t.file);c=c.filter(r=>E(r.file_path).endsWith(o)||E(r.file_path).includes(o));}let s=c.map(o=>({nodeId:o.id,name:o.name,kind:o.ast_type??"unknown",filePath:E(o.file_path),startLine:o.start_line,endLine:o.end_line,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t),c=[];if(t.includeEdges){let s=t.edgesLimit??50;c=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:c}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let c=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,d=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;d.length>0;){let g=d.shift();if(g.depth>=c)continue;if(r.size>=s){u=true;break}let h=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let y of h.edges){p.push(y);let T=y.source===g.nodeId?y.target:y.source;if(!r.has(T)&&(r.set(T,g.depth+1),d.push({nodeId:T,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),b=m.length>0?a.queryNodes({ids:m}):[],f=new Map(b.map(g=>[g.id,g])),x=[];for(let[g,h]of r.entries()){let y=f.get(g);y&&x.push({node:y,depth:h});}return {root:i,nodes:x,edges:p,truncated:u,totalNodes:x.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await S(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await O(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let c=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),d=[],p=[i.id];for(let u=1;u<=c&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),b=o.map(()=>"?").join(","),f=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${b})`,[...p,...o]),x=[],g=new Set;for(let h of f)if(!r.has(h.source)&&!g.has(h.source)&&(g.add(h.source),r.add(h.source),x.push(h.source),r.size-1>=s))break;if(x.length>0){let h=x.slice(0,10),y=a.queryNodes({ids:h}),T=new Map(y.map($=>[$.id,$])),oe=h.map($=>{let B=T.get($);return {id:$,name:B?.name??"(unknown)",filePath:B?E(B.file_path):"(unknown)",relation:"CALLS"}});d.push({depth:u,count:x.length,sample:oe});}p=x;}return {root:i,totalImpacted:r.size-1,buckets:d}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return A(e,t,"incoming")}async function xe(e,t){return A(e,t,"outgoing")}async function A(e,t,n,l){let a=await S(e),i=a.getQuery(),c=a.getDatabase(),{node:s}=await O(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,d=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of d.edges){let b=ue(m,s.id,c,n==="incoming"?"in":"out");b&&p.push(b);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function Ee(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await S(e);l.getQuery();l.getDatabase();let s=(await V(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=E(p.filePath),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,d=[];for(let[p,u]of o){let m=u.slice(0,r),b=[];for(let f of m){let x=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await A(e,{name:f.name,file:p,kind:t.kind,maxResults:5},"outgoing");b.push({node:{id:f.nodeId,name:f.name,ast_type:f.kind,language:"ts",file_path:f.filePath,start_line:f.startLine??0,end_line:f.endLine??0,text:""},callers:x.callers,callees:g.callers});}d.push({file:p,symbols:b});}return {query:t.query,entryPoints:d,totalHits:s.length}}async function Ne(e,t){return await(await S(e)).getStatus()}async function Re(e,t){return await(await S(e)).healthCheck()}var J=utils.Filesystem.toUnixPath;function Se(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Ce(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function N(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:J(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Ce(e)}}function I(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:J(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(n=>I({...n}))}))}function K(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Te=utils.Log.create({service:"codebase-format-truncate"}),j="**`",$e="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let c=e.slice(0,l),s=c.lastIndexOf(`
|
|
2
|
-
${j}`),o=c.lastIndexOf(`
|
|
3
|
-
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let d=r>0?c.slice(0,r):c,u=d+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`};try{let m=await utils.TruncateContent.truncate(e,{maxChars:d.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:utils.TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}catch(m){return Te.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-d.length}/${e.length} characters truncated ...`}}}function D(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
|
-
${j}`),c=a.lastIndexOf(`
|
|
5
|
-
`),s;i>l*.5?s=i:c>0?s=c:s=-1;let o=s>0?a.slice(0,s):a;return {content:o+`
|
|
6
|
-
|
|
7
|
-
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}function Le(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function v(e,t){if(!e||e.length===0)return null;let n=e.filter(a=>t.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${Le(a.lastEventAt)})`).join(", ")}
|
|
8
|
-
|
|
9
|
-
`}function F(e,t,n={}){return (ne[e]??ne.default).replace(/<(\w+)>/g,(a,i)=>i==="tool"?t:n[i]??`<${i}>`)}var ne={search:`---
|
|
10
|
-
|
|
11
|
-
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
12
|
-
> If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
|
|
13
|
-
|
|
14
|
-
> **Output truncated to budget; the content above is the source of truth.**
|
|
15
|
-
> For more detail, call \`<tool>\` with refined parameters.`};async function H(e,t){let{pendingFiles:n,toolName:l,sync:a=false}=t;if(e.length===0)return w(l,"No matches found.","Try broader search terms, or use `explore` to read source.");let i=we(e),c=new Set(i.keys()),s=[];s.push(v(n,c)??"");let o="[[codebase-search-summary]]";s.push(o+`
|
|
16
|
-
`);let r=e.length;s.push(`**Files with matches:** ${i.size}
|
|
17
|
-
`);for(let[m,b]of i){let f=b.map(y=>y.node.name),x=f.slice(0,5).join(", "),g=f.length>5?`, +${f.length-5} more`:"";s.push(`**\`${m}\`** \u2014 ${x}${g}
|
|
18
|
-
`);let h=b[0]?.node.language??"";s.push("```"+h);for(let y of b)s.push(`L${y.node.startLine} ${y.snippet}`);s.push("```\n");}s.push(F("search",l,{}));let d=s.join(`
|
|
19
|
-
`),p=`Found ${r} symbol${r===1?"":"s"} across ${i.size} file${i.size===1?"":"s"}.`,u=d.replace(o,p);return k(u,t,a)}async function M(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(t.length===0||t.every(r=>r.count===0))return w(a,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let c=t.reduce((r,d)=>r+d.count,0),s=Fe(c),o=[];o.push(v(l,new Set([e.filePath]))??""),o.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${c})
|
|
20
|
-
`);for(let r of t){o.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let d of r.samples.slice(0,5))o.push(` - \`${d.name}\` ${d.file}:${d.line} [${d.relation}]`);r.samples.length>5&&o.push(` - ... and ${r.samples.length-5} more`);}return o.push(F("impact",a,{root:e.name,riskLevel:s})),k(o.join(`
|
|
21
|
-
`),n,i)}function Fe(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function z(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function Q(e,t){let{root:n,incoming:l,outgoing:a,neighbors:i}=e,{pendingFiles:c,toolName:s,sync:o=false}=t;if(l.length===0&&a.length===0&&i.length===0)return w(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(v(c,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
|
|
22
|
-
`),r.push(`**Incoming** (${l.length}):`);for(let d of l.slice(0,10))r.push(`- ${d.source} \u2192 [${d.relation}] \u2192 \`${n.name}\``);l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let d of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${d.relation}] \u2192 ${d.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),i.length>0){r.push(`**Neighbors** (${i.length}):`);for(let d of i.slice(0,20))r.push(`- [d=${d.depth}] \`${d.node.name}\` (${d.node.astType}) ${d.node.filePath}:${d.node.startLine}`);i.length>20&&r.push(`- ... and ${i.length-20} more`),r.push("");}return r.push(F("context",s,{})),k(r.join(`
|
|
23
|
-
`),t,o)}async function q(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(!e.id)return w(a,"Node not found.","Check the node ID or use `search` to find it.");let c=t.filter(r=>r.direction==="in"),s=t.filter(r=>r.direction==="out"),o=[];o.push(v(l,new Set([e.filePath]))??""),o.push(`**Node: \`${e.name}\`**
|
|
24
|
-
`),o.push(`- ID: \`${e.id}\``),o.push(`- Kind: ${e.astType}`),o.push(`- Language: ${e.language}`),o.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),o.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&o.push(`- Modifiers: ${e.modifiers.join(", ")}`),o.push(""),o.push(`**Edges** (incoming: ${c.length} / outgoing: ${s.length}):`);for(let r of c.slice(0,5))o.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))o.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&o.push(`- ... and ${t.length-10} more`),o.push(F("default",a,{})),k(o.join(`
|
|
25
|
-
`),n,i)}async function re(e,t){let{entryPoints:n,totalHits:l,query:a}=e,{toolName:i,sync:c=false}=t;if(n.length===0)return w(i,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
|
|
26
|
-
`),s.push(`**Query:** ${a} `),s.push(`**Total hits:** ${l} `),s.push(`**Entry points:** ${n.length}
|
|
27
|
-
`);for(let o of n){s.push(`**\`${o.file}\`** \u2014 ${o.symbols.length} symbol${o.symbols.length===1?"":"s"}
|
|
28
|
-
`);for(let r of o.symbols){let d=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(d),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
|
|
29
|
-
`),s.push(F("context",i,{})),k(s.join(`
|
|
30
|
-
`),t,c)}function we(e){let t=new Map;for(let n of e){let l=n.node.filePath,a=t.get(l);a?a.push(n):t.set(l,[n]);}return t}function w(e,t,n){return `**${e}**
|
|
31
|
-
|
|
32
|
-
${t}
|
|
33
|
-
|
|
34
|
-
> **Tip:** ${n}`}async function k(e,t,n){let l={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?D(e,l):await _(e,l)).content}var Ae=utils.Log.create({service:"codebase-format-render"});async function Oe(e,t){if(e.length===0)return H([],t);let n=G(e);return H(n,t)}async function _e(e,t,n){if(t.length===0)return M(N(e),[],n);let l=[{depth:1,count:t.length,riskLabel:z(1),samples:t.slice(0,10).map(a=>({name:a.source.name,file:N(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return M(N(e),l,n)}async function De(e,t,n,l,a){let i=N(e),c=t.map(r=>I(r,"in")),s=n.map(r=>I(r,"out")),o=l.map(r=>({node:N(r),depth:1}));return Q({root:i,incoming:c,outgoing:s,neighbors:o},a)}async function ve(e,t,n){if(!e)return q(K(),[],n);let l=N(e),a=t.map(i=>{let c=i.target===e.id?"in":"out";return I(i,c)});return q(l,a,n)}async function He(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(l=>({file:l.file,symbols:l.symbols.map(a=>({node:N(a.node),source:a.node.text??"",callers:a.callers.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation})),callees:a.callees.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation}))}))}))};return re(n,t)}Ae.debug("format/render.ts loaded");exports.A=_e;exports.B=De;exports.C=ve;exports.D=He;exports.a=R;exports.b=P;exports.c=L;exports.d=V;exports.e=pe;exports.f=ge;exports.g=he;exports.h=be;exports.i=xe;exports.j=Ee;exports.k=Ne;exports.l=Re;exports.m=N;exports.n=I;exports.o=G;exports.p=K;exports.q=j;exports.r=$e;exports.s=_;exports.t=D;exports.u=H;exports.v=M;exports.w=z;exports.x=Q;exports.y=q;exports.z=Oe;
|