@easbot/codebase 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ 'use strict';var chunkUDQ4RD27_cjs=require('./chunk-UDQ4RD27.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunkUDQ4RD27_cjs.c}});
@@ -0,0 +1 @@
1
+ export{c as Log}from'./chunk-T4X2DOE5.mjs';
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var chunk3SPWK34Q_cjs=require('./chunks/chunk-3SPWK34Q.cjs'),$=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),ne=require('fs'),ye=require('better-sqlite3'),utils=require('@easbot/utils'),url=require('url'),Ie=require('fs/promises'),crypto=require('crypto'),Ce=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var $__default=/*#__PURE__*/_interopDefault($);var ne__default=/*#__PURE__*/_interopDefault(ne);var ye__default=/*#__PURE__*/_interopDefault(ye);var Ie__default=/*#__PURE__*/_interopDefault(Ie);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var re={".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 A=class h extends Error{constructor(t,r,s){super(t);chunk3SPWK34Q_cjs.a(this,"name","ParserError");chunk3SPWK34Q_cjs.a(this,"filePath");chunk3SPWK34Q_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},C=class h extends Error{constructor(t,r,s){super(t);chunk3SPWK34Q_cjs.a(this,"name","DatabaseError");chunk3SPWK34Q_cjs.a(this,"operation");chunk3SPWK34Q_cjs.a(this,"cause");this.operation=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},j=class h extends Error{constructor(t,r,s){super(t);chunk3SPWK34Q_cjs.a(this,"name","FileSystemError");chunk3SPWK34Q_cjs.a(this,"filePath");chunk3SPWK34Q_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},X=class h extends Error{constructor(t,r){super(t);chunk3SPWK34Q_cjs.a(this,"name","SchemaError");chunk3SPWK34Q_cjs.a(this,"missing");this.missing=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},q=class h extends Error{constructor(t,r){super(t);chunk3SPWK34Q_cjs.a(this,"name","ConfigError");chunk3SPWK34Q_cjs.a(this,"field");this.field=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Q=class h extends Error{constructor(t,r,s){super(t);chunk3SPWK34Q_cjs.a(this,"name","IndexError");chunk3SPWK34Q_cjs.a(this,"filePath");chunk3SPWK34Q_cjs.a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},H=class h extends Error{constructor(t,r,s){super(t);chunk3SPWK34Q_cjs.a(this,"name","QueryError");chunk3SPWK34Q_cjs.a(this,"params");chunk3SPWK34Q_cjs.a(this,"cause");this.params=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},G=class h extends Error{constructor(t,r){super(`Unsupported language: ${t}`);chunk3SPWK34Q_cjs.a(this,"name","UnsupportedLanguageError");chunk3SPWK34Q_cjs.a(this,"extension");chunk3SPWK34Q_cjs.a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,h.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var v=utils.Filesystem.toUnixPath,D=chunk3SPWK34Q_cjs.c.create({service:"codebase-database"}),k=class{constructor(e){chunk3SPWK34Q_cjs.a(this,"db");chunk3SPWK34Q_cjs.a(this,"dbPath");chunk3SPWK34Q_cjs.a(this,"closed",false);chunk3SPWK34Q_cjs.a(this,"ftsAvailable",false);this.dbPath=utils.Filesystem.toUnixPath(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=$__default.default.dirname(this.dbPath);ne__default.default.existsSync(e)||ne__default.default.mkdirSync(e,{recursive:true});let t=new ye__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
1
+ 'use strict';var chunkUDQ4RD27_cjs=require('./chunks/chunk-UDQ4RD27.cjs'),z=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),ie=require('fs'),Ee=require('better-sqlite3'),utils=require('@easbot/utils'),url=require('url'),Ce=require('fs/promises'),crypto=require('crypto'),Re=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var z__default=/*#__PURE__*/_interopDefault(z);var ie__default=/*#__PURE__*/_interopDefault(ie);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var Re__default=/*#__PURE__*/_interopDefault(Re);var ne={".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 $=class y extends Error{constructor(t,r,n){super(t);chunkUDQ4RD27_cjs.a(this,"name","ParserError");chunkUDQ4RD27_cjs.a(this,"filePath");chunkUDQ4RD27_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},P=class y extends Error{constructor(t,r,n){super(t);chunkUDQ4RD27_cjs.a(this,"name","DatabaseError");chunkUDQ4RD27_cjs.a(this,"operation");chunkUDQ4RD27_cjs.a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},Q=class y extends Error{constructor(t,r,n){super(t);chunkUDQ4RD27_cjs.a(this,"name","FileSystemError");chunkUDQ4RD27_cjs.a(this,"filePath");chunkUDQ4RD27_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r){super(t);chunkUDQ4RD27_cjs.a(this,"name","SchemaError");chunkUDQ4RD27_cjs.a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},H=class y extends Error{constructor(t,r){super(t);chunkUDQ4RD27_cjs.a(this,"name","ConfigError");chunkUDQ4RD27_cjs.a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},V=class y extends Error{constructor(t,r,n){super(t);chunkUDQ4RD27_cjs.a(this,"name","IndexError");chunkUDQ4RD27_cjs.a(this,"filePath");chunkUDQ4RD27_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},B=class y extends Error{constructor(t,r,n){super(t);chunkUDQ4RD27_cjs.a(this,"name","QueryError");chunkUDQ4RD27_cjs.a(this,"params");chunkUDQ4RD27_cjs.a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Y=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);chunkUDQ4RD27_cjs.a(this,"name","UnsupportedLanguageError");chunkUDQ4RD27_cjs.a(this,"extension");chunkUDQ4RD27_cjs.a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=utils.Filesystem.normalize,T=chunkUDQ4RD27_cjs.c.create({service:"codebase-database"}),q=class{constructor(e){chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"dbPath");chunkUDQ4RD27_cjs.a(this,"closed",false);chunkUDQ4RD27_cjs.a(this,"ftsAvailable",false);this.dbPath=w(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=z__default.default.dirname(this.dbPath);ie__default.default.existsSync(e)||ie__default.default.mkdirSync(e,{recursive:true});let t=new Ee__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  id TEXT PRIMARY KEY,
4
4
  name TEXT NOT NULL,
@@ -55,44 +55,44 @@
55
55
  embedding BLOB NOT NULL,
56
56
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
57
57
  )
58
- `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of t)r.run(s,n);}catch(t){throw new X("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:v(e.file_path)};this.db.prepare(`
58
+ `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new G("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:w(e.file_path)};this.db.prepare(`
59
59
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
60
60
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
61
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:v(n.file_path)})),r=this.db.prepare(`
61
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(s=>({...s,file_path:w(s.file_path)})),r=this.db.prepare(`
62
62
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
63
63
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
- `);this.db.transaction(n=>{for(let i of n)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let i=r.get(n.id);i&&t.run(i.rowid),s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){D.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){D.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),s.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){D.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
64
+ `);this.db.transaction(s=>{for(let i of s)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(s);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let s of e)try{let i=r.get(s.id);i&&t.run(i.rowid),n.run(s.id,s.name,s.ast_type,s.language,s.file_path,s.text);}catch(i){T.warn("FTS update failed for node",{nodeId:s.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){T.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),n.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){T.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
65
65
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
66
66
  VALUES (?, ?, ?, ?, ?)
67
67
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
68
68
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
69
69
  VALUES (?, ?, ?, ?, ?)
70
- `);this.db.transaction(s=>{for(let n of s)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${v(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let s="SELECT * FROM nodes";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY file_path, start_line",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new C("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let s="SELECT * FROM edges";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY created_at DESC",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new C("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new C("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(!this.ftsAvailable)return [];try{let r=e.split(/\s+/).map(i=>`${i}*`).join(" ");return this.db.prepare(`
70
+ `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${w(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new P("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
71
71
  SELECT
72
- f.id,
73
- f.name,
74
- f.ast_type,
75
- f.language,
76
- f.file_path,
77
- f.text,
78
- n.start_line,
79
- n.start_col,
80
- n.end_line,
81
- n.end_col,
82
- -bm25(nodes_fts, 0, 1.0, 0.5, 0.3, 0.2, 1.5) as score
83
- FROM nodes_fts f
84
- JOIN nodes n ON n.id = f.id
85
- WHERE nodes_fts MATCH ?
72
+ nodes_fts.id,
73
+ nodes_fts.name,
74
+ nodes_fts.ast_type,
75
+ nodes_fts.language,
76
+ nodes_fts.file_path,
77
+ nodes_fts.text,
78
+ nodes.start_line,
79
+ nodes.start_col,
80
+ nodes.end_line,
81
+ nodes.end_col,
82
+ bm25(nodes_fts) as score
83
+ FROM nodes_fts
84
+ JOIN nodes ON nodes.id = nodes_fts.id
85
+ WHERE nodes_fts.text MATCH ?
86
86
  ORDER BY score DESC
87
87
  LIMIT ?
88
- `).all(r,t)}catch{return []}}deleteNodesByFile(e){let t=v(e);if(this.ftsAvailable)try{let s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of s)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(s){D.warn("FTS delete failed for file",{filePath:t,error:String(s)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=v(e);return this.db.prepare(`
88
+ `).all(r,t);return T.debug("searchNodesFts done",{resultCount:i.length}),i}catch(r){return T.warn("searchNodesFts failed",{error:String(r)}),[]}}deleteNodesByFile(e){let t=w(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let s of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(s.rowid);}catch(n){T.warn("FTS delete failed for file",{filePath:t,error:String(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=w(e);return this.db.prepare(`
89
89
  DELETE FROM edges
90
90
  WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
91
91
  OR target IN (SELECT id FROM nodes WHERE file_path = ?)
92
- `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(v(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
92
+ `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(w(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
93
93
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
94
94
  VALUES (?, ?, ?)
95
- `).run(v(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(v(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),s=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let i of s)n[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:n}}setLastSync(){this.db.prepare(`
95
+ `).run(w(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(w(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),s={};for(let i of n)s[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:s}}setLastSync(){this.db.prepare(`
96
96
  INSERT OR REPLACE INTO meta (key, value)
97
97
  VALUES ('lastSync', ?)
98
98
  `).run(new Date().toISOString());}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let r=this.db.prepare(`
@@ -103,6 +103,6 @@
103
103
  `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
104
104
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
105
105
  VALUES (?, ?, ?)
106
- `);this.db.transaction(s=>{for(let n of s)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){D.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new C("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){D.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ie=chunk3SPWK34Q_cjs.c.create({service:"codebase-parser"}),_e={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"}};function xe(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&chunk3SPWK34Q_cjs.b?$__default.default.dirname(url.fileURLToPath(chunk3SPWK34Q_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function Ne(h,e){let t=xe(),r=t;for(let s=0;s<10;s++){let n=$__default.default.join(r,"node_modules",h,e);if(utils.Filesystem.stat(n)!==void 0)return n;let i=$__default.default.dirname(r);if(i===r)break;r=i;}return $__default.default.join(t,"node_modules",h,e)}var F=class{constructor(){chunk3SPWK34Q_cjs.a(this,"parsers",new Map);chunk3SPWK34Q_cjs.a(this,"initialized",false);chunk3SPWK34Q_cjs.a(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 s=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],n=await Promise.allSettled(s.map(async i=>{try{let o=_e[i];if(!o)return ie.warn("No WASM config for language",{lang:i}),null;let a=Ne(o.package,o.wasmFile),d=await r.load(a),l=new t;return l.setLanguage(d),{lang:i,parser:l,language:d}}catch(o){return ie.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of n)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=$__default.default.extname(e).toLowerCase();return re[t]??null}parse(e,t){if(!this.initialized)throw new A("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new A(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(s){throw new A("Failed to parse code","",s instanceof Error?s:new Error(String(s)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new G($__default.default.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;}},R=null;async function ae(){return R||(R=new F,await R.initialize()),R}function oe(){R&&(R.dispose(),R=null);}var Se={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Te=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),P=class{extractNodes(e,t,r,s){let n=[],i=t.split(`
107
- `);return this.walkTree(e.rootNode,n,r,s,i),n}walkTree(e,t,r,s,n,i){if(Te.has(e.type)){let o=this.extractNode(e,r,s,n,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,s,n,i);}}extractNode(e,t,r,s,n){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,s);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:n}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let s=e.childForFieldName?.(r);if(s?.text)return s.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 s of e.children)if(t.includes(s.type)){let n=this.findNameInChildren(s,r);if(n)return n}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Se))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,s=e.endPosition.row;return r===s?t[r]?.trim()??"":t.slice(r,s+1).join(`
108
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function de(){return new P}var L=class{extractEdges(e,t,r,s){let n=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,n),this.extractCallEdges(e.rootNode,t,n,r,s,i),this.extractInheritanceEdges(e.rootNode,t,n,r,s,i),this.extractImportEdges(e.rootNode,t,n,r,s),this.extractTypeReferences(e.rootNode,t,n,r,s,i),this.extractParameterEdges(e.rootNode,t,n,r,s,i),this.extractDefinesEdges(t,n,r,s,i),this.extractAnnotationEdges(e.rootNode,t,n,r,s),n}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,s,n,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),l=this.extractCalleeName(a);if(d&&l){let g=`${s}:${n}:function_declaration:${l}`;r.push({source:d.id,target:g,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,s,n,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=`${s}:${n}:class_declaration:${d}`,g=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(g){let u=this.findChildByType(g,["extends_clause","superclass"])??g,_=this.extractIdentifier(u);if(_&&_!==d){let x=`${s}:${n}:class_declaration:${_}`;r.push({source:l,target:x,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let u of m){let _=`${s}:${n}:interface_declaration:${u}`;r.push({source:l,target:_,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,s,n){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${s}:${n}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let n=this.findNameInChildren(r);if(n){let i=t.find(g=>g.name===n);if(i)return {id:this.generateNodeId(i),name:n};r.startPosition;let a=t[0],d=a?.language??"ts",l=a?.file_path??"";return {id:`${d}:${l}:function_declaration:${n}`,name:n}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let s=t.children[t.children.length-1];if(s)return s.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let n=this.findDescendantByType(r,t);if(n)return n}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,s,n,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let g=this.findNameInChildren(d);if(!g)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let u=this.extractTypeName(c);if(u&&u!=="void"&&u!=="any"&&u!=="null"){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let u=this.extractTypeName(m);if(u){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let g of d.children)if(g.type==="type_annotation"||g.type==="annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findEnclosingFunction(d,t);u&&r.push({source:u.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let g of d.children)if(g.type==="type_annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findNameInChildren(d);u&&r.push({source:this.generateNodeIdFromName(u,"variable_declaration",s,n),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,s,n,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=this.generateNodeIdFromName(d,a.type,s,n),g=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of g)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let u=this.findNameInChildren(m);if(u&&u!=="self"&&u!=="this"){let _=`${s}:${n}:parameter:${d}:${u}`;r.push({source:l,target:_,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,s,n){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let l of e)if(l.file_path===a.file_path&&o.includes(l.ast_type)&&l.start_line>=a.start_line&&l.end_line<=a.end_line){let g=this.generateNodeId(l);d!==g&&t.push({source:d,target:g,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,s,n){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let l=a.parent;for(;l;){if(o.includes(l.type)){let g=this.findNameInChildren(l);if(g){let c=this.generateNodeIdFromName(g,l.type,s,n),m=`${s}:${n}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}l=l.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let s=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let n of s)return `${t}:${r}:${n}:${e}`;return null}generateNodeIdFromName(e,t,r,s){return `${r}:${s}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let s of e.children)t.includes(s.type)&&r.push(s);return r}};function ce(){return new L}var O=class{constructor(e,t,r){chunk3SPWK34Q_cjs.a(this,"db");chunk3SPWK34Q_cjs.a(this,"parserManager");chunk3SPWK34Q_cjs.a(this,"nodeExtractor");chunk3SPWK34Q_cjs.a(this,"edgeExtractor");chunk3SPWK34Q_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new P,this.edgeExtractor=new L,this.config=r;}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 n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let i=new Float32Array(n);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),s=[],n=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Q("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let l=this.parserManager.parse(a,o),g=this.nodeExtractor.extractNodes(l,a,o,e);n=g.length;let c=this.edgeExtractor.extractEdges(l,g,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(g);let m=this.getValidEdgeCount(c,g);this.storeEdges(c,g),i=m,this.config.embedding&&g.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(g)),this.db.setFileHash(e,d),l.delete();}catch(o){let a=o instanceof Error?o.message:String(o);s.push({filePath:e,error:a});}return {success:s.length===0,filesProcessed:1,nodesCreated:n,edgesCreated:i,errors:s,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),s=e??this.config.workspaceDir,n=[],i=0,o=0,a=0;try{let d=await this.scanFiles(s),l=d.length;for(let g=0;g<d.length;g+=this.config.batchSize){let c=d.slice(g,g+this.config.batchSize);for(let m of c){let u=await this.indexFile(m.filePath,t);i++,o+=u.nodesCreated,a+=u.edgesCreated,!u.success&&u.errors.length>0&&n.push(...u.errors);}}}catch(d){let l=d instanceof Error?d.message:String(d);n.push({filePath:s,error:l});}return this.db.setLastSync(),{success:n.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:n,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],s=0,n=0,i=0,o=0,a=0,d=0;try{let l=await this.scanFiles(this.config.workspaceDir),g=new Set(l.map(u=>u.filePath)),c=this.db.getAllFileHashes(),m=new Set(c.map(u=>u.file_path));for(let u of c)g.has(u.file_path)||(this.db.deleteNodesByFile(u.file_path),this.db.deleteEdgesByFile(u.file_path),this.db.deleteFileHash(u.file_path),i++);for(let u of l){let _=this.db.getFileHash(u.filePath);if(_)if(_!==u.contentHash){let x=await this.indexFile(u.filePath,e);x.success?(n++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}else o++;else {let x=await this.indexFile(u.filePath,e);x.success?(s++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}}}catch(l){let g=l instanceof Error?l.message:String(l);r.push({filePath:this.config.workspaceDir,error:g});}return this.db.setLastSync(),{success:r.length===0,filesAdded:s,filesUpdated:n,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:Date.now()-t}}async scanFiles(e){let t=[],s=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(l=>`**/*${l}`),n=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(l=>l.includes("/")||l.includes("*")?l:`**/${l}/**`),o=[...n,...i],a=e.replace(/\\/g,"/"),d=await Ce__default.default(s,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let l of d){let g=utils.Filesystem.toUnixPath($__default.default.normalize(l)),c=this.parserManager.detectLanguage(g);if(c)try{let m=await this.readFile(g),u=this.computeHash(m);t.push({filePath:g,language:c,contentHash:u,content:m});}catch{}}return t}async readFile(e){try{return await Ie__default.default.readFile(e,"utf-8")}catch(t){throw new j("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n))),s=e.filter(n=>r.has(n.source)&&r.has(n.target)).map((n,i)=>({id:`${n.source}:${n.relation}:${n.target}:${i}`,source:n.source,target:n.target,relation:n.relation,created_at:new Date().toISOString()}));s.length>0&&this.db.insertEdges(s);}getValidEdgeCount(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s)));return e.filter(s=>r.has(s.source)&&r.has(s.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),s=[];for(let n of r){let i=n.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let l=o.embeddings[a];if(l){let g=new Float32Array(l),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,g),s.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:g});}}}catch{for(let a of n){if(!a)continue;let d=this.generateNodeEmbeddingText(a),l=await this.embedText(d);l&&s.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:l});}}}s.length>0&&this.db.storeNodeEmbeddings?.(s);}chunkArray(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}};function le(h,e,t){return new O(h,e,t)}var ge=utils.Filesystem.toUnixPath,M=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunk3SPWK34Q_cjs.a(this,"db");chunk3SPWK34Q_cjs.a(this,"embedding");chunk3SPWK34Q_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:s=this.config.minScore,language:n,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:l=100,vectorWeight:g=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t,u=[];if(m&&this.embedding){let y=await this.vectorSearchNodes(e,r*2,s);for(let f of y)u.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*g});}if(a&&this.db.isFtsAvailable()){let y=this.db.searchNodesFts(e,r*2);for(let f of y){if(n&&f.language!==n||i&&!f.file_path.includes(ge(i))||o&&f.ast_type!==o)continue;let N=this.normalizeScore(f.score),E=u.find(w=>w.id===f.id);E?(E.ftsScore=N,E.hybridScore=E.vectorScore*g+N*c):u.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:N,source:"fts",ftsScore:N,hybridScore:N*c});}}if(!a||!this.db.isFtsAvailable()||u.length===0)try{let y=this.db.queryNodes({limit:r*2,astType:o,language:n,filePath:i}),f=new Set(u.map(b=>b.id)),N=e.toLowerCase(),E=N.split(/\s+/).filter(b=>b.length>0),w=[];for(let b of y){if(f.has(b.id)||i&&!b.file_path.includes(ge(i)))continue;let z=b.name.toLowerCase(),B=b.text.toLowerCase(),ee=0;if(E.some(T=>z.includes(T))){let T=0;for(let U of E){let J=new RegExp(U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),W=z.match(J);T+=W?W.length:0;}ee=.8*Math.min(T/E.length,1);}let Y=0;if(E.some(T=>B.includes(T))){let T=0;for(let W of E){let me=new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),te=B.match(me);T+=te?te.length:0;}Y=.5*Math.min(T/E.length,1);let U=B.indexOf(N),J=U===-1?0:Math.max(0,1-U/B.length)*.2;Y+=J;}let K=Math.max(ee,Y);K>0&&w.push({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,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:K,source:"basic",hybridScore:K});}w.sort((b,z)=>z.score-b.score),u.push(...w.slice(0,r));}catch{}let x=u.filter(y=>y.hybridScore>=s).sort((y,f)=>f.hybridScore-y.hybridScore).slice(0,r).map(y=>({id:y.id,name:y.name,ast_type:y.astType,language:y.language,file_path:y.filePath,start_line:y.startLine,start_col:y.startCol,end_line:y.endLine,end_col:y.endCol,text:y.text,created_at:new Date().toISOString()}));if(d&&x.length>0){let y=x.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:y}),N=new Map;for(let E of f)E.source!==E.target&&(N.has(E.source)||N.set(E.source,[]),N.get(E.source).push(E));return x.map(E=>{let w=N.get(E.id)||[];return {...E,edges:w.slice(0,l)}})}return x.map(y=>({...y,edges:[]}))}async vectorSearchNodes(e,t,r,s){if(!this.embedding)return [];let n=await this.embedText(e);if(!n)return [];let i=new Float32Array(n),o;if(s&&s.length>0){let c=s.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,s);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),u=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:u});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId),l=this.db.queryNodes({ids:d}),g=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return l.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:g.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0,n=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,s+=o*o,n+=a*a;}return s===0||n===0?0:r/(Math.sqrt(s)*Math.sqrt(n))}structuralSearch(e,t){let r=[],s=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let n of s){let i=this.calculateNameSimilarity(e,n.name);r.push({id:n.id,name:n.name,astType:n.ast_type,language:n.language,filePath:n.file_path,text:n.text??"",snippet:(n.text??"").slice(0,200),startLine:n.start_line??0,startCol:n.start_col??0,endLine:n.end_line??0,endCol:n.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),s=t.toLowerCase();if(r===s)return 1;if(s.startsWith(r))return .9;if(s.includes(r))return .7;let n=new Set(r.split("")),i=new Set(s.split("")),o=0;for(let a of n)i.has(a)&&o++;return o/n.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new H("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new H("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 s of t){let n=this.db.getNodeById(s.source),i=this.db.getNodeById(s.target);n&&i&&r.push({edge:s,sourceNode:n,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:s="both",limit:n=100}=t,i=[],o=[],a=new Set;if(s==="outgoing"||s==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.target);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}if(s==="incoming"||s==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.source);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}return {nodes:o.slice(0,n),edges:i.slice(0,n)}}queryCallGraph(e,t=2){let r=new Map,s=new Set,n=(i,o)=>{if(o>t||s.has(i))return;s.add(i);let a=[],d=[],l=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of l)a.push(c.source),n(c.source,o+1);let g=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of g)d.push(c.target),n(c.target,o+1);r.set(i,{callers:a,callees:d});};return n(e,0),r}queryInheritance(e){let t=[],r=[],s=new Set,n=new Set,i=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.target);c&&(t.push(c),i(g.target));}},o=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.source);c&&(r.push(c),o(g.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function ue(h){return new M(h)}var De=chunk3SPWK34Q_cjs.c.create({service:"codebase"}),ke={database:{path:types.getDefaultDatabasePath(xdgBasedir.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:types.DEFAULT_SYNC_CONFIG},V=class{constructor(e={}){chunk3SPWK34Q_cjs.a(this,"config");chunk3SPWK34Q_cjs.a(this,"db");chunk3SPWK34Q_cjs.a(this,"parserManager");chunk3SPWK34Q_cjs.a(this,"indexer");chunk3SPWK34Q_cjs.a(this,"queryInterface");chunk3SPWK34Q_cjs.a(this,"initialized",false);chunk3SPWK34Q_cjs.a(this,"dirty",false);chunk3SPWK34Q_cjs.a(this,"syncTimer");chunk3SPWK34Q_cjs.a(this,"syncingInProgress",false);chunk3SPWK34Q_cjs.a(this,"log",chunk3SPWK34Q_cjs.c.create({service:"codebase"}));this.config={...ke,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let s=this.resolveDbPath();this.db=new k(s),this.parserManager=new F;let n={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.indexer=new O(this.db,this.parserManager,n),this.queryInterface=new M(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunk3SPWK34Q_cjs.c.init({logDir:this.config.logDir||$__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>De.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true);}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){this.log.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{this.log.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=>{this.log.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new q("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new q("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return $__default.default.isAbsolute(e)?e:$__default.default.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 this.log.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{return await this.indexer.sync(e)}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,this.log.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(h){let e=new V(h);return await e.initialize(),e}async function tr(h){let{Log:e}=await import('./chunks/log-RVO7PC3D.cjs'),t=false;await e.init({logDir:h.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:h.print??false,dev:h.dev??t,level:h.level??("INFO")});}exports.CodeBase=V;exports.ConfigError=q;exports.DatabaseError=C;exports.DatabaseManager=k;exports.EdgeExtractor=L;exports.FILE_EXTENSION_MAP=re;exports.FileSystemError=j;exports.IndexError=Q;exports.Indexer=O;exports.NodeExtractor=P;exports.ParserError=A;exports.ParserManager=F;exports.QueryError=H;exports.QueryInterface=M;exports.SchemaError=X;exports.UnsupportedLanguageError=G;exports.createCodebase=$e;exports.createEdgeExtractor=ce;exports.createIndexer=le;exports.createNodeExtractor=de;exports.createQueryInterface=ue;exports.getParserManager=ae;exports.initLog=tr;exports.resetParserManager=oe;
106
+ `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new P("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ae=chunkUDQ4RD27_cjs.c.create({service:"codebase-parser"}),Ne={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"}};function Se(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&chunkUDQ4RD27_cjs.b?z__default.default.dirname(url.fileURLToPath(chunkUDQ4RD27_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function Te(y,e){let t=Se(),r=t;for(let n=0;n<10;n++){let s=z__default.default.join(r,"node_modules",y,e);if(utils.Filesystem.stat(s)!==void 0)return s;let i=z__default.default.dirname(r);if(i===r)break;r=i;}return z__default.default.join(t,"node_modules",y,e)}var O=class{constructor(){chunkUDQ4RD27_cjs.a(this,"parsers",new Map);chunkUDQ4RD27_cjs.a(this,"initialized",false);chunkUDQ4RD27_cjs.a(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"],s=await Promise.allSettled(n.map(async i=>{try{let o=Ne[i];if(!o)return ae.warn("No WASM config for language",{lang:i}),null;let a=Te(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return ae.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=z__default.default.extname(e).toLowerCase();return ne[t]??null}parse(e,t){if(!this.initialized)throw new $("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new $(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new $("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new Y(z__default.default.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;}},L=null;async function oe(){return L||(L=new O,await L.initialize()),L}function de(){L&&(L.dispose(),L=null);}var Ie={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},ve=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),M=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
+ `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(ve.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);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 s=this.findNameInChildren(n,r);if(s)return s}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Ie))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function ce(){return new M}var A=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let F=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:F,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function le(){return new A}var D=class{constructor(e,t,r){chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"parserManager");chunkUDQ4RD27_cjs.a(this,"nodeExtractor");chunkUDQ4RD27_cjs.a(this,"edgeExtractor");chunkUDQ4RD27_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new M,this.edgeExtractor=new A,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new V("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),F=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Re__default.default(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=utils.Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Ce__default.default.readFile(e,"utf-8")}catch(t){throw new Q("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ge(y,e,t){return new D(y,e,t)}var ue=utils.Filesystem.normalize,N=chunkUDQ4RD27_cjs.c.create({service:"codebase.query"}),k=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"embedding");chunkUDQ4RD27_cjs.a(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:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(ue(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(ue(i)))continue;let W=b.name.toLowerCase(),U=b.text.toLowerCase(),re=0;if(E.some(v=>W.includes(v))){let v=0;for(let j of E){let ee=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),X=W.match(ee);v+=X?X.length:0;}re=.8*Math.min(v/E.length,1);}let J=0;if(E.some(v=>U.includes(v))){let v=0;for(let X of E){let fe=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),se=U.match(fe);v+=se?se.length:0;}J=.5*Math.min(v/E.length,1);let j=U.indexOf(_),ee=j===-1?0:Math.max(0,1-j/U.length)*.2;J+=ee;}let Z=Math.max(re,J);Z>0&&I.push({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,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:Z,source:"basic",hybridScore:Z});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let F=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&F.length>0){let h=F.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return F.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return F.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new B("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new B("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function pe(y){return new k(y)}var R=chunkUDQ4RD27_cjs.c.create({service:"codebase"}),ke={database:{path:types.getDefaultDatabasePath(xdgBasedir.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:types.DEFAULT_SYNC_CONFIG},K=class{constructor(e={}){chunkUDQ4RD27_cjs.a(this,"config");chunkUDQ4RD27_cjs.a(this,"db");chunkUDQ4RD27_cjs.a(this,"parserManager");chunkUDQ4RD27_cjs.a(this,"indexer");chunkUDQ4RD27_cjs.a(this,"queryInterface");chunkUDQ4RD27_cjs.a(this,"initialized",false);chunkUDQ4RD27_cjs.a(this,"dirty",false);chunkUDQ4RD27_cjs.a(this,"syncTimer");chunkUDQ4RD27_cjs.a(this,"syncingInProgress",false);this.config={...ke,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new q(n),this.parserManager=new O;let s={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.indexer=new D(this.db,this.parserManager,s),this.queryInterface=new k(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunkUDQ4RD27_cjs.c.init({logDir:this.config.logDir||z__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>R.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,R.debug("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){R.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{R.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=>{R.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return z__default.default.isAbsolute(e)?e:z__default.default.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 R.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return R.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,R.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(y){let e=new K(y);return await e.initialize(),e}async function tr(y){let{Log:e}=await import('./chunks/log-BXSFPAB3.cjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}exports.CodeBase=K;exports.ConfigError=H;exports.DatabaseError=P;exports.DatabaseManager=q;exports.EdgeExtractor=A;exports.FILE_EXTENSION_MAP=ne;exports.FileSystemError=Q;exports.IndexError=V;exports.Indexer=D;exports.NodeExtractor=M;exports.ParserError=$;exports.ParserManager=O;exports.QueryError=B;exports.QueryInterface=k;exports.SchemaError=G;exports.UnsupportedLanguageError=Y;exports.createCodebase=$e;exports.createEdgeExtractor=le;exports.createIndexer=ge;exports.createNodeExtractor=ce;exports.createQueryInterface=pe;exports.getParserManager=oe;exports.initLog=tr;exports.resetParserManager=de;
package/dist/index.d.cts CHANGED
@@ -533,7 +533,6 @@ declare class CodeBase implements ICodebase {
533
533
  private dirty;
534
534
  private syncTimer?;
535
535
  private syncingInProgress;
536
- private log;
537
536
  constructor(config?: Partial<CodebaseConfig>);
538
537
  initialize(): Promise<void>;
539
538
  private startSyncTimer;
package/dist/index.d.ts CHANGED
@@ -533,7 +533,6 @@ declare class CodeBase implements ICodebase {
533
533
  private dirty;
534
534
  private syncTimer?;
535
535
  private syncingInProgress;
536
- private log;
537
536
  constructor(config?: Partial<CodebaseConfig>);
538
537
  initialize(): Promise<void>;
539
538
  private startSyncTimer;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {c,a,b}from'./chunks/chunk-7KMRJNOJ.mjs';import q from'path';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 se from'fs';import Ee from'better-sqlite3';import {Filesystem}from'@easbot/utils';import {fileURLToPath}from'url';import ve from'fs/promises';import {createHash}from'crypto';import Re from'fast-glob';var ne={".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 D=class h extends Error{constructor(t,r,s){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},R=class h extends Error{constructor(t,r,s){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},X=class h extends Error{constructor(t,r,s){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},Q=class h extends Error{constructor(t,r){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},H=class h extends Error{constructor(t,r){super(t);a(this,"name","ConfigError");a(this,"field");this.field=r,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},G=class h extends Error{constructor(t,r,s){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},z=class h extends Error{constructor(t,r,s){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=r,this.cause=s,Object.setPrototypeOf(this,h.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},V=class h extends Error{constructor(t,r){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,h.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=Filesystem.toUnixPath,k=c.create({service:"codebase-database"}),$=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=Filesystem.toUnixPath(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=q.dirname(this.dbPath);se.existsSync(e)||se.mkdirSync(e,{recursive:true});let t=new Ee(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
1
+ import {c,a,b}from'./chunks/chunk-T4X2DOE5.mjs';import H from'path';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 ae from'fs';import be from'better-sqlite3';import {Filesystem}from'@easbot/utils';import {fileURLToPath}from'url';import we from'fs/promises';import {createHash}from'crypto';import Fe from'fast-glob';var ie={".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 q=class y extends Error{constructor(t,r,n){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},L=class y extends Error{constructor(t,r,n){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r,n){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},V=class y extends Error{constructor(t,r){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},B=class y extends Error{constructor(t,r){super(t);a(this,"name","ConfigError");a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Y=class y extends Error{constructor(t,r,n){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},U=class y extends Error{constructor(t,r,n){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},K=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var R=Filesystem.normalize,T=c.create({service:"codebase-database"}),z=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=R(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=H.dirname(this.dbPath);ae.existsSync(e)||ae.mkdirSync(e,{recursive:true});let t=new be(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  id TEXT PRIMARY KEY,
4
4
  name TEXT NOT NULL,
@@ -55,44 +55,44 @@ import {c,a,b}from'./chunks/chunk-7KMRJNOJ.mjs';import q from'path';import {xdgD
55
55
  embedding BLOB NOT NULL,
56
56
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
57
57
  )
58
- `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of t)r.run(s,n);}catch(t){throw new Q("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:w(e.file_path)};this.db.prepare(`
58
+ `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new V("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:R(e.file_path)};this.db.prepare(`
59
59
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
60
60
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
61
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:w(n.file_path)})),r=this.db.prepare(`
61
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(s=>({...s,file_path:R(s.file_path)})),r=this.db.prepare(`
62
62
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
63
63
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
- `);this.db.transaction(n=>{for(let i of n)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let i=r.get(n.id);i&&t.run(i.rowid),s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){k.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){k.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),s=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),s.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){k.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
64
+ `);this.db.transaction(s=>{for(let i of s)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(s);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let s of e)try{let i=r.get(s.id);i&&t.run(i.rowid),n.run(s.id,s.name,s.ast_type,s.language,s.file_path,s.text);}catch(i){T.warn("FTS update failed for node",{nodeId:s.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){T.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),n.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){T.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
65
65
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
66
66
  VALUES (?, ?, ?, ?, ?)
67
67
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
68
68
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
69
69
  VALUES (?, ?, ?, ?, ?)
70
- `);this.db.transaction(s=>{for(let n of s)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${w(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let s="SELECT * FROM nodes";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY file_path, start_line",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new R("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let s="SELECT * FROM edges";t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY created_at DESC",e.limit&&(s+=" LIMIT ?",r.push(e.limit)),e.offset&&(s+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(s).all(...r)}catch(n){throw new R("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new R("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(!this.ftsAvailable)return [];try{let r=e.split(/\s+/).map(i=>`${i}*`).join(" ");return this.db.prepare(`
70
+ `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${R(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new L("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new L("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new L("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
71
71
  SELECT
72
- f.id,
73
- f.name,
74
- f.ast_type,
75
- f.language,
76
- f.file_path,
77
- f.text,
78
- n.start_line,
79
- n.start_col,
80
- n.end_line,
81
- n.end_col,
82
- -bm25(nodes_fts, 0, 1.0, 0.5, 0.3, 0.2, 1.5) as score
83
- FROM nodes_fts f
84
- JOIN nodes n ON n.id = f.id
85
- WHERE nodes_fts MATCH ?
72
+ nodes_fts.id,
73
+ nodes_fts.name,
74
+ nodes_fts.ast_type,
75
+ nodes_fts.language,
76
+ nodes_fts.file_path,
77
+ nodes_fts.text,
78
+ nodes.start_line,
79
+ nodes.start_col,
80
+ nodes.end_line,
81
+ nodes.end_col,
82
+ bm25(nodes_fts) as score
83
+ FROM nodes_fts
84
+ JOIN nodes ON nodes.id = nodes_fts.id
85
+ WHERE nodes_fts.text MATCH ?
86
86
  ORDER BY score DESC
87
87
  LIMIT ?
88
- `).all(r,t)}catch{return []}}deleteNodesByFile(e){let t=w(e);if(this.ftsAvailable)try{let s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of s)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(s){k.warn("FTS delete failed for file",{filePath:t,error:String(s)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=w(e);return this.db.prepare(`
88
+ `).all(r,t);return T.debug("searchNodesFts done",{resultCount:i.length}),i}catch(r){return T.warn("searchNodesFts failed",{error:String(r)}),[]}}deleteNodesByFile(e){let t=R(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let s of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(s.rowid);}catch(n){T.warn("FTS delete failed for file",{filePath:t,error:String(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=R(e);return this.db.prepare(`
89
89
  DELETE FROM edges
90
90
  WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
91
91
  OR target IN (SELECT id FROM nodes WHERE file_path = ?)
92
- `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(w(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
92
+ `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(R(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
93
93
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
94
94
  VALUES (?, ?, ?)
95
- `).run(w(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(w(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),s=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let i of s)n[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:n}}setLastSync(){this.db.prepare(`
95
+ `).run(R(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(R(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),s={};for(let i of n)s[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:s}}setLastSync(){this.db.prepare(`
96
96
  INSERT OR REPLACE INTO meta (key, value)
97
97
  VALUES ('lastSync', ?)
98
98
  `).run(new Date().toISOString());}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let r=this.db.prepare(`
@@ -103,6 +103,6 @@ import {c,a,b}from'./chunks/chunk-7KMRJNOJ.mjs';import q from'path';import {xdgD
103
103
  `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
104
104
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
105
105
  VALUES (?, ?, ?)
106
- `);this.db.transaction(s=>{for(let n of s)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){k.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new R("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){k.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ae=c.create({service:"codebase-parser"}),xe={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"}};function Ne(){return typeof import.meta<"u"&&import.meta.url?q.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function Se(h,e){let t=Ne(),r=t;for(let s=0;s<10;s++){let n=q.join(r,"node_modules",h,e);if(Filesystem.stat(n)!==void 0)return n;let i=q.dirname(r);if(i===r)break;r=i;}return q.join(t,"node_modules",h,e)}var P=class{constructor(){a(this,"parsers",new Map);a(this,"initialized",false);a(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 s=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],n=await Promise.allSettled(s.map(async i=>{try{let o=xe[i];if(!o)return ae.warn("No WASM config for language",{lang:i}),null;let a=Se(o.package,o.wasmFile),d=await r.load(a),l=new t;return l.setLanguage(d),{lang:i,parser:l,language:d}}catch(o){return ae.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of n)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=q.extname(e).toLowerCase();return ne[t]??null}parse(e,t){if(!this.initialized)throw new D("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new D(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(s){throw new D("Failed to parse code","",s instanceof Error?s:new Error(String(s)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new V(q.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;}},F=null;async function oe(){return F||(F=new P,await F.initialize()),F}function de(){F&&(F.dispose(),F=null);}var Te={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Ie=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),L=class{extractNodes(e,t,r,s){let n=[],i=t.split(`
107
- `);return this.walkTree(e.rootNode,n,r,s,i),n}walkTree(e,t,r,s,n,i){if(Ie.has(e.type)){let o=this.extractNode(e,r,s,n,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,s,n,i);}}extractNode(e,t,r,s,n){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,s);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:n}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let s=e.childForFieldName?.(r);if(s?.text)return s.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 s of e.children)if(t.includes(s.type)){let n=this.findNameInChildren(s,r);if(n)return n}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Te))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,s=e.endPosition.row;return r===s?t[r]?.trim()??"":t.slice(r,s+1).join(`
108
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function ce(){return new L}var O=class{extractEdges(e,t,r,s){let n=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,n),this.extractCallEdges(e.rootNode,t,n,r,s,i),this.extractInheritanceEdges(e.rootNode,t,n,r,s,i),this.extractImportEdges(e.rootNode,t,n,r,s),this.extractTypeReferences(e.rootNode,t,n,r,s,i),this.extractParameterEdges(e.rootNode,t,n,r,s,i),this.extractDefinesEdges(t,n,r,s,i),this.extractAnnotationEdges(e.rootNode,t,n,r,s),n}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,s,n,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),l=this.extractCalleeName(a);if(d&&l){let g=`${s}:${n}:function_declaration:${l}`;r.push({source:d.id,target:g,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,s,n,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=`${s}:${n}:class_declaration:${d}`,g=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(g){let u=this.findChildByType(g,["extends_clause","superclass"])??g,_=this.extractIdentifier(u);if(_&&_!==d){let x=`${s}:${n}:class_declaration:${_}`;r.push({source:l,target:x,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let u of m){let _=`${s}:${n}:interface_declaration:${u}`;r.push({source:l,target:_,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,s,n){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${s}:${n}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let n=this.findNameInChildren(r);if(n){let i=t.find(g=>g.name===n);if(i)return {id:this.generateNodeId(i),name:n};r.startPosition;let a=t[0],d=a?.language??"ts",l=a?.file_path??"";return {id:`${d}:${l}:function_declaration:${n}`,name:n}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let s=t.children[t.children.length-1];if(s)return s.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let n=this.findDescendantByType(r,t);if(n)return n}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,s,n,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let g=this.findNameInChildren(d);if(!g)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let u=this.extractTypeName(c);if(u&&u!=="void"&&u!=="any"&&u!=="null"){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let u=this.extractTypeName(m);if(u){let _=this.resolveTypeNodeId(u,s,n);_&&r.push({source:this.generateNodeIdFromName(g,d.type,s,n),target:_,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let g of d.children)if(g.type==="type_annotation"||g.type==="annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findEnclosingFunction(d,t);u&&r.push({source:u.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let g of d.children)if(g.type==="type_annotation"){let c=this.extractTypeName(g);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,s,n);if(m){let u=this.findNameInChildren(d);u&&r.push({source:this.generateNodeIdFromName(u,"variable_declaration",s,n),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,s,n,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let l=this.generateNodeIdFromName(d,a.type,s,n),g=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of g)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let u=this.findNameInChildren(m);if(u&&u!=="self"&&u!=="this"){let _=`${s}:${n}:parameter:${d}:${u}`;r.push({source:l,target:_,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,s,n){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let l of e)if(l.file_path===a.file_path&&o.includes(l.ast_type)&&l.start_line>=a.start_line&&l.end_line<=a.end_line){let g=this.generateNodeId(l);d!==g&&t.push({source:d,target:g,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,s,n){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let l=a.parent;for(;l;){if(o.includes(l.type)){let g=this.findNameInChildren(l);if(g){let c=this.generateNodeIdFromName(g,l.type,s,n),m=`${s}:${n}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}l=l.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let s=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let n of s)return `${t}:${r}:${n}:${e}`;return null}generateNodeIdFromName(e,t,r,s){return `${r}:${s}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let s of e.children)t.includes(s.type)&&r.push(s);return r}};function le(){return new O}var M=class{constructor(e,t,r){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new L,this.edgeExtractor=new O,this.config=r;}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 n=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(n){let i=new Float32Array(n);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),s=[],n=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new G("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let l=this.parserManager.parse(a,o),g=this.nodeExtractor.extractNodes(l,a,o,e);n=g.length;let c=this.edgeExtractor.extractEdges(l,g,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(g);let m=this.getValidEdgeCount(c,g);this.storeEdges(c,g),i=m,this.config.embedding&&g.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(g)),this.db.setFileHash(e,d),l.delete();}catch(o){let a=o instanceof Error?o.message:String(o);s.push({filePath:e,error:a});}return {success:s.length===0,filesProcessed:1,nodesCreated:n,edgesCreated:i,errors:s,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),s=e??this.config.workspaceDir,n=[],i=0,o=0,a=0;try{let d=await this.scanFiles(s),l=d.length;for(let g=0;g<d.length;g+=this.config.batchSize){let c=d.slice(g,g+this.config.batchSize);for(let m of c){let u=await this.indexFile(m.filePath,t);i++,o+=u.nodesCreated,a+=u.edgesCreated,!u.success&&u.errors.length>0&&n.push(...u.errors);}}}catch(d){let l=d instanceof Error?d.message:String(d);n.push({filePath:s,error:l});}return this.db.setLastSync(),{success:n.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:n,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],s=0,n=0,i=0,o=0,a=0,d=0;try{let l=await this.scanFiles(this.config.workspaceDir),g=new Set(l.map(u=>u.filePath)),c=this.db.getAllFileHashes(),m=new Set(c.map(u=>u.file_path));for(let u of c)g.has(u.file_path)||(this.db.deleteNodesByFile(u.file_path),this.db.deleteEdgesByFile(u.file_path),this.db.deleteFileHash(u.file_path),i++);for(let u of l){let _=this.db.getFileHash(u.filePath);if(_)if(_!==u.contentHash){let x=await this.indexFile(u.filePath,e);x.success?(n++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}else o++;else {let x=await this.indexFile(u.filePath,e);x.success?(s++,a+=x.nodesCreated,d+=x.edgesCreated):r.push(...x.errors);}}}catch(l){let g=l instanceof Error?l.message:String(l);r.push({filePath:this.config.workspaceDir,error:g});}return this.db.setLastSync(),{success:r.length===0,filesAdded:s,filesUpdated:n,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:Date.now()-t}}async scanFiles(e){let t=[],s=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(l=>`**/*${l}`),n=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(l=>l.includes("/")||l.includes("*")?l:`**/${l}/**`),o=[...n,...i],a=e.replace(/\\/g,"/"),d=await Re(s,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let l of d){let g=Filesystem.toUnixPath(q.normalize(l)),c=this.parserManager.detectLanguage(g);if(c)try{let m=await this.readFile(g),u=this.computeHash(m);t.push({filePath:g,language:c,contentHash:u,content:m});}catch{}}return t}async readFile(e){try{return await ve.readFile(e,"utf-8")}catch(t){throw new X("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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n))),s=e.filter(n=>r.has(n.source)&&r.has(n.target)).map((n,i)=>({id:`${n.source}:${n.relation}:${n.target}:${i}`,source:n.source,target:n.target,relation:n.relation,created_at:new Date().toISOString()}));s.length>0&&this.db.insertEdges(s);}getValidEdgeCount(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s)));return e.filter(s=>r.has(s.source)&&r.has(s.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),s=[];for(let n of r){let i=n.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<n.length;a++){let d=n[a];if(!d)continue;let l=o.embeddings[a];if(l){let g=new Float32Array(l),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,g),s.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:g});}}}catch{for(let a of n){if(!a)continue;let d=this.generateNodeEmbeddingText(a),l=await this.embedText(d);l&&s.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:l});}}}s.length>0&&this.db.storeNodeEmbeddings?.(s);}chunkArray(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}};function ge(h,e,t){return new M(h,e,t)}var ue=Filesystem.toUnixPath,A=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:s=this.config.minScore,language:n,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:l=100,vectorWeight:g=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t,u=[];if(m&&this.embedding){let y=await this.vectorSearchNodes(e,r*2,s);for(let f of y)u.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*g});}if(a&&this.db.isFtsAvailable()){let y=this.db.searchNodesFts(e,r*2);for(let f of y){if(n&&f.language!==n||i&&!f.file_path.includes(ue(i))||o&&f.ast_type!==o)continue;let N=this.normalizeScore(f.score),E=u.find(C=>C.id===f.id);E?(E.ftsScore=N,E.hybridScore=E.vectorScore*g+N*c):u.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:N,source:"fts",ftsScore:N,hybridScore:N*c});}}if(!a||!this.db.isFtsAvailable()||u.length===0)try{let y=this.db.queryNodes({limit:r*2,astType:o,language:n,filePath:i}),f=new Set(u.map(b=>b.id)),N=e.toLowerCase(),E=N.split(/\s+/).filter(b=>b.length>0),C=[];for(let b of y){if(f.has(b.id)||i&&!b.file_path.includes(ue(i)))continue;let U=b.name.toLowerCase(),B=b.text.toLowerCase(),te=0;if(E.some(T=>U.includes(T))){let T=0;for(let W of E){let Z=new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),j=U.match(Z);T+=j?j.length:0;}te=.8*Math.min(T/E.length,1);}let K=0;if(E.some(T=>B.includes(T))){let T=0;for(let j of E){let fe=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),re=B.match(fe);T+=re?re.length:0;}K=.5*Math.min(T/E.length,1);let W=B.indexOf(N),Z=W===-1?0:Math.max(0,1-W/B.length)*.2;K+=Z;}let J=Math.max(te,K);J>0&&C.push({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,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:J,source:"basic",hybridScore:J});}C.sort((b,U)=>U.score-b.score),u.push(...C.slice(0,r));}catch{}let x=u.filter(y=>y.hybridScore>=s).sort((y,f)=>f.hybridScore-y.hybridScore).slice(0,r).map(y=>({id:y.id,name:y.name,ast_type:y.astType,language:y.language,file_path:y.filePath,start_line:y.startLine,start_col:y.startCol,end_line:y.endLine,end_col:y.endCol,text:y.text,created_at:new Date().toISOString()}));if(d&&x.length>0){let y=x.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:y}),N=new Map;for(let E of f)E.source!==E.target&&(N.has(E.source)||N.set(E.source,[]),N.get(E.source).push(E));return x.map(E=>{let C=N.get(E.id)||[];return {...E,edges:C.slice(0,l)}})}return x.map(y=>({...y,edges:[]}))}async vectorSearchNodes(e,t,r,s){if(!this.embedding)return [];let n=await this.embedText(e);if(!n)return [];let i=new Float32Array(n),o;if(s&&s.length>0){let c=s.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,s);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),u=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:u});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId),l=this.db.queryNodes({ids:d}),g=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return l.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:g.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0,n=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,s+=o*o,n+=a*a;}return s===0||n===0?0:r/(Math.sqrt(s)*Math.sqrt(n))}structuralSearch(e,t){let r=[],s=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let n of s){let i=this.calculateNameSimilarity(e,n.name);r.push({id:n.id,name:n.name,astType:n.ast_type,language:n.language,filePath:n.file_path,text:n.text??"",snippet:(n.text??"").slice(0,200),startLine:n.start_line??0,startCol:n.start_col??0,endLine:n.end_line??0,endCol:n.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),s=t.toLowerCase();if(r===s)return 1;if(s.startsWith(r))return .9;if(s.includes(r))return .7;let n=new Set(r.split("")),i=new Set(s.split("")),o=0;for(let a of n)i.has(a)&&o++;return o/n.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new z("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new z("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 s of t){let n=this.db.getNodeById(s.source),i=this.db.getNodeById(s.target);n&&i&&r.push({edge:s,sourceNode:n,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:s="both",limit:n=100}=t,i=[],o=[],a=new Set;if(s==="outgoing"||s==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.target);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}if(s==="incoming"||s==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:n});for(let l of d){if(r&&!r.includes(l.relation))continue;i.push(l);let g=this.db.getNodeById(l.source);g&&!a.has(g.id)&&(o.push(g),a.add(g.id));}}return {nodes:o.slice(0,n),edges:i.slice(0,n)}}queryCallGraph(e,t=2){let r=new Map,s=new Set,n=(i,o)=>{if(o>t||s.has(i))return;s.add(i);let a=[],d=[],l=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of l)a.push(c.source),n(c.source,o+1);let g=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of g)d.push(c.target),n(c.target,o+1);r.set(i,{callers:a,callees:d});};return n(e,0),r}queryInheritance(e){let t=[],r=[],s=new Set,n=new Set,i=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.target);c&&(t.push(c),i(g.target));}},o=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),l=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let g of [...d,...l]){let c=this.db.getNodeById(g.source);c&&(r.push(c),o(g.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function pe(h){return new A(h)}var ke=c.create({service:"codebase"}),$e={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},Y=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);a(this,"log",c.create({service:"codebase"}));this.config={...$e,...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},this.validateConfig();let s=this.resolveDbPath();this.db=new $(s),this.parserManager=new P;let n={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.indexer=new M(this.db,this.parserManager,n),this.queryInterface=new A(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await c.init({logDir:this.config.logDir||q.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>ke.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true);}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){this.log.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{this.log.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=>{this.log.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return q.isAbsolute(e)?e:q.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 this.log.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{return await this.indexer.sync(e)}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,this.log.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function qe(h){let e=new Y(h);return await e.initialize(),e}async function rr(h){let{Log:e}=await import('./chunks/log-RUXF5FO4.mjs'),t=false;await e.init({logDir:h.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:h.print??false,dev:h.dev??t,level:h.level??("INFO")});}export{Y as CodeBase,H as ConfigError,R as DatabaseError,$ as DatabaseManager,O as EdgeExtractor,ne as FILE_EXTENSION_MAP,X as FileSystemError,G as IndexError,M as Indexer,L as NodeExtractor,D as ParserError,P as ParserManager,z as QueryError,A as QueryInterface,Q as SchemaError,V as UnsupportedLanguageError,qe as createCodebase,le as createEdgeExtractor,ge as createIndexer,ce as createNodeExtractor,pe as createQueryInterface,oe as getParserManager,rr as initLog,de as resetParserManager};
106
+ `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new L("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var oe=c.create({service:"codebase-parser"}),Se={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"}};function Te(){return typeof import.meta<"u"&&import.meta.url?H.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function Ie(y,e){let t=Te(),r=t;for(let n=0;n<10;n++){let s=H.join(r,"node_modules",y,e);if(Filesystem.stat(s)!==void 0)return s;let i=H.dirname(r);if(i===r)break;r=i;}return H.join(t,"node_modules",y,e)}var M=class{constructor(){a(this,"parsers",new Map);a(this,"initialized",false);a(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"],s=await Promise.allSettled(n.map(async i=>{try{let o=Se[i];if(!o)return oe.warn("No WASM config for language",{lang:i}),null;let a=Ie(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return oe.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}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=H.extname(e).toLowerCase();return ie[t]??null}parse(e,t){if(!this.initialized)throw new q("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new q(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new q("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new K(H.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;}},O=null;async function de(){return O||(O=new M,await O.initialize()),O}function ce(){O&&(O.dispose(),O=null);}var ve={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Ce=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),A=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
+ `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(Ce.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_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 "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);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 s=this.findNameInChildren(n,r);if(s)return s}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"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(ve))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function le(){return new A}var D=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}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,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let P=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:P,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function ge(){return new D}var k=class{constructor(e,t,r){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new A,this.edgeExtractor=new D,this.config=r;}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 s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Y("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),P=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Fe(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await we.readFile(e,"utf-8")}catch(t){throw new G("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.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}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=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.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 ue(y,e,t){return new k(y,e,t)}var pe=Filesystem.normalize,N=c.create({service:"codebase.query"}),$=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(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:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(pe(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(pe(i)))continue;let W=b.name.toLowerCase(),j=b.text.toLowerCase(),se=0;if(E.some(v=>W.includes(v))){let v=0;for(let X of E){let te=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),Q=W.match(te);v+=Q?Q.length:0;}se=.8*Math.min(v/E.length,1);}let Z=0;if(E.some(v=>j.includes(v))){let v=0;for(let Q of E){let ye=new RegExp(Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),ne=j.match(ye);v+=ne?ne.length:0;}Z=.5*Math.min(v/E.length,1);let X=j.indexOf(_),te=X===-1?0:Math.max(0,1-X/j.length)*.2;Z+=te;}let ee=Math.max(se,Z);ee>0&&I.push({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,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:ee,source:"basic",hybridScore:ee});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let P=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&P.length>0){let h=P.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return P.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return P.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target: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,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new U("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new U("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 s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function he(y){return new $(y)}var F=c.create({service:"codebase"}),$e={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},J=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);this.config={...$e,...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},this.validateConfig();let n=this.resolveDbPath();this.db=new z(n),this.parserManager=new M;let s={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.indexer=new k(this.db,this.parserManager,s),this.queryInterface=new $(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await c.init({logDir:this.config.logDir||H.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>F.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,F.debug("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){F.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{F.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=>{F.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new B("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new B("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return H.isAbsolute(e)?e:H.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 F.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return F.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}),t}finally{this.syncingInProgress=false;}}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 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}}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(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,F.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function qe(y){let e=new J(y);return await e.initialize(),e}async function rr(y){let{Log:e}=await import('./chunks/log-JVQMUDSH.mjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}export{J as CodeBase,B as ConfigError,L as DatabaseError,z as DatabaseManager,D as EdgeExtractor,ie as FILE_EXTENSION_MAP,G as FileSystemError,Y as IndexError,k as Indexer,A as NodeExtractor,q as ParserError,M as ParserManager,U as QueryError,$ as QueryInterface,V as SchemaError,K as UnsupportedLanguageError,qe as createCodebase,ge as createEdgeExtractor,ue as createIndexer,le as createNodeExtractor,he as createQueryInterface,de as getParserManager,rr as initLog,ce as resetParserManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/codebase",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Code Knowledge Graph SDK for EASBot - Property Graph model for code indexing and querying with Tree-sitter parsing, FTS hybrid search, and incremental updates",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -46,16 +46,16 @@
46
46
  "LICENSE"
47
47
  ],
48
48
  "dependencies": {
49
- "@ai-sdk/provider": "^3.0.8",
50
- "@ai-sdk/provider-utils": "^4.0.21",
49
+ "@ai-sdk/provider": "^3.0.10",
50
+ "@ai-sdk/provider-utils": "^4.0.27",
51
51
  "@tree-sitter-grammars/tree-sitter-zig": "^1.1.2",
52
- "@tursodatabase/database": "0.5.1",
53
- "ai": "^6.0.136",
52
+ "@tursodatabase/database": "0.5.3",
53
+ "ai": "^6.0.176",
54
54
  "better-sqlite3": "^12.9.0",
55
55
  "commander": "^14.0.3",
56
56
  "fast-glob": "^3.3.3",
57
57
  "tree-sitter-c": "^0.24.1",
58
- "tree-sitter-c-sharp": "^0.23.1",
58
+ "tree-sitter-c-sharp": "^0.23.5",
59
59
  "tree-sitter-cpp": "^0.23.4",
60
60
  "tree-sitter-go": "^0.25.0",
61
61
  "tree-sitter-java": "^0.23.5",
@@ -66,22 +66,22 @@
66
66
  "tree-sitter-rust": "^0.24.0",
67
67
  "tree-sitter-scala": "^0.24.0",
68
68
  "tree-sitter-typescript": "^0.23.2",
69
- "web-tree-sitter": "^0.25.0",
69
+ "web-tree-sitter": "^0.26.8",
70
70
  "xdg-basedir": "^5.1.0",
71
- "zod": "^4.3.6",
72
- "@easbot/local-model-sdk": "0.2.1",
73
- "@easbot/types": "0.2.1",
74
- "@easbot/utils": "0.2.1"
71
+ "zod": "^4.4.3",
72
+ "@easbot/local-model-sdk": "0.2.3",
73
+ "@easbot/types": "0.2.3",
74
+ "@easbot/utils": "0.2.3"
75
75
  },
76
76
  "devDependencies": {
77
- "@biomejs/biome": "^2.4.8",
77
+ "@biomejs/biome": "^2.4.14",
78
78
  "@types/better-sqlite3": "^7.6.13",
79
- "@types/node": "^22.17.0",
80
- "@vitest/coverage-v8": "^4.1.1",
81
- "dotenv": "^17.3.1",
79
+ "@types/node": "^25.6.2",
80
+ "@vitest/coverage-v8": "^4.1.5",
81
+ "dotenv": "^17.4.2",
82
82
  "tsup": "^8.5.1",
83
- "typescript": "^6.0.2",
84
- "vitest": "^4.1.1"
83
+ "typescript": "^6.0.3",
84
+ "vitest": "^4.1.5"
85
85
  },
86
86
  "engines": {
87
87
  "node": ">=22.17.0"
@@ -1 +0,0 @@
1
- export{c as Log}from'./chunk-7KMRJNOJ.mjs';
@@ -1 +0,0 @@
1
- 'use strict';var chunk3SPWK34Q_cjs=require('./chunk-3SPWK34Q.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunk3SPWK34Q_cjs.c}});