@zipbul/gildash 0.5.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +92 -52
- package/README.md +94 -51
- package/dist/index.js +7 -5
- package/dist/index.js.map +42 -28
- package/dist/migrations/0003_majestic_mongu.sql +1 -0
- package/dist/migrations/0004_cool_firestar.sql +23 -0
- package/dist/migrations/meta/0003_snapshot.json +422 -0
- package/dist/migrations/meta/0004_snapshot.json +429 -0
- package/dist/migrations/meta/_journal.json +14 -0
- package/dist/src/errors.d.ts +9 -7
- package/dist/src/extractor/relation-extractor.d.ts +2 -1
- package/dist/src/gildash/context.d.ts +91 -0
- package/dist/src/gildash/extract-api.d.ts +7 -0
- package/dist/src/gildash/graph-api.d.ts +28 -0
- package/dist/src/gildash/index.d.ts +91 -0
- package/dist/src/gildash/lifecycle.d.ts +60 -0
- package/dist/src/gildash/misc-api.d.ts +20 -0
- package/dist/src/gildash/parse-api.d.ts +9 -0
- package/dist/src/gildash/query-api.d.ts +33 -0
- package/dist/src/gildash/semantic-api.d.ts +20 -0
- package/dist/src/gildash/types.d.ts +162 -0
- package/dist/src/index.d.ts +4 -3
- package/dist/src/indexer/index-coordinator.d.ts +8 -2
- package/dist/src/indexer/relation-indexer.d.ts +6 -0
- package/dist/src/search/dependency-graph.d.ts +1 -0
- package/dist/src/search/relation-search.d.ts +11 -1
- package/dist/src/search/symbol-search.d.ts +6 -0
- package/dist/src/semantic/ast-node-utils.d.ts +9 -0
- package/dist/src/semantic/implementation-finder.d.ts +22 -0
- package/dist/src/semantic/index.d.ts +68 -0
- package/dist/src/semantic/reference-resolver.d.ts +19 -0
- package/dist/src/semantic/symbol-graph.d.ts +36 -0
- package/dist/src/semantic/tsc-program.d.ts +67 -0
- package/dist/src/semantic/type-collector.d.ts +27 -0
- package/dist/src/semantic/types.d.ts +103 -0
- package/dist/src/store/repositories/relation.repository.d.ts +14 -2
- package/dist/src/store/repositories/symbol.repository.d.ts +2 -0
- package/dist/src/store/schema.d.ts +38 -0
- package/package.json +10 -4
- package/dist/src/gildash.d.ts +0 -821
package/dist/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var wt=Object.defineProperty;var St=(n,t)=>{for(var i in t)wt(n,i,{get:t[i],enumerable:!0,configurable:!0,set:(e)=>t[i]=()=>e})};import{err as O,isErr as rn}from"@zipbul/result";import Nn from"path";import{existsSync as mi}from"fs";import{err as bt}from"@zipbul/result";import{parseSync as Ot}from"oxc-parser";function y(n,t,i){return i!==void 0?{type:n,message:t,cause:i}:{type:n,message:t}}function un(n,t,i,e=Ot){try{let{program:r,errors:s,comments:m}=e(n,t,i);return{filePath:n,program:r,errors:s,comments:m,sourceText:t}}catch(r){return bt(y("parse",`Failed to parse file: ${n}`,r))}}class An{#t;#n=new Map;constructor(n){this.#t=Math.max(1,n)}get size(){return this.#n.size}has(n){return this.#n.has(n)}get(n){if(!this.#n.has(n))return;let t=this.#n.get(n);return this.#n.delete(n),this.#n.set(n,t),t}set(n,t){if(this.#n.has(n))this.#n.delete(n);if(this.#n.set(n,t),this.#n.size>this.#t){let i=this.#n.keys().next().value;if(i!==void 0)this.#n.delete(i)}}delete(n){return this.#n.delete(n)}clear(){this.#n.clear()}}class Dn{lru;constructor(n=500){this.lru=new An(n)}get(n){return this.lru.get(n)}set(n,t){this.lru.set(n,t)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Yn(n){let t=[0];for(let i=0;i<n.length;i++)if(n[i]===`
|
|
3
|
-
`)t.push(i+1);return t}function kn(n,t){let i=0,e=n.length-1;while(i<e){let r=i+e+1>>1;if(n[r]<=t)i=r;else e=r-1}return{line:i+1,column:t-n[i]}}import{err as Nt}from"@zipbul/result";import{parse as ht}from"comment-parser";function Zn(n){try{let t=n.trim();if(t.startsWith("/**"))t=t.slice(3);if(t.endsWith("*/"))t=t.slice(0,-2);let e=ht(`/** ${t} */`)[0]??{description:"",tags:[]};return{description:(e.description??"").trim(),tags:(e.tags??[]).map((r)=>({tag:r.tag??"",name:r.name??"",type:r.type??"",description:r.description??"",optional:r.optional??!1,...r.default!==void 0?{default:r.default}:{}}))}}catch(t){return Nt(y("parse","Failed to parse JSDoc comment",t))}}import{isErr as At}from"@zipbul/result";function ln(n){let{program:t,sourceText:i,comments:e}=n,r=Yn(i);function s(c,g){return{start:kn(r,c),end:kn(r,g)}}function m(c){let g=null;for(let o of e){if(o.type!=="Block")continue;if(o.end>c)continue;if(!o.value.startsWith("*"))continue;if(!g||o.end>g.end)g={value:`/*${o.value}*/`,end:o.end}}if(!g)return;for(let o of t.body){let f=o.start??0;if(f===c)continue;if(f>g.end&&f<c)return}return g.value}function u(c){if(!c)return;let g=c.typeAnnotation??c;return i.slice(g.start,g.end)}function a(c){if(!c||c.length===0)return[];return c.map((g)=>{let o=g.expression;if(!o)return{name:"unknown"};if(o.type==="CallExpression"){let f=o.callee?.name??o.callee?.property?.name??"unknown",x=(o.arguments??[]).map((b)=>i.slice(b.start,b.end));return{name:f,arguments:x.length>0?x:void 0}}if(o.type==="Identifier")return{name:o.name??"unknown"};return{name:i.slice(o.start,o.end)}})}function p(c){let g=c.type==="TSParameterProperty"?c.parameter:c;if(g?.type==="RestElement"){let h=`...${g.argument?.name??"unknown"}`,M=g.typeAnnotation,C=M?u(M):void 0,I={name:h,isOptional:!1};if(C)I.type=C;return I}if(g?.type==="AssignmentPattern"){let{left:k,right:h}=g,M=k?.name??"unknown",C=k?.typeAnnotation,I=C?u(C):void 0,L=i.slice(h.start,h.end),sn=a(k?.decorators??[]),Z={name:M,isOptional:!0,defaultValue:L};if(I)Z.type=I;if(sn.length>0)Z.decorators=sn;return Z}let o=g?.name??g?.pattern?.name??"unknown",f=!!g?.optional,x=g?.typeAnnotation,b=x?u(x):void 0,D=a(g?.decorators??[]),$={name:o,isOptional:f};if(b)$.type=b;if(D.length>0)$.decorators=D;return $}function l(c,g){let o=[];if(g?.async)o.push("async");if(c.static)o.push("static");if(c.abstract)o.push("abstract");if(c.readonly)o.push("readonly");if(c.override)o.push("override");if(c.declare)o.push("declare");if(c.const)o.push("const");let f=c.accessibility;if(f==="private")o.push("private");else if(f==="protected")o.push("protected");else if(f==="public")o.push("public");return o}function d(c){let g=[];if(c.superClass){let f=i.slice(c.superClass.start,c.superClass.end);g.push({kind:"extends",name:f})}let o=c.implements??[];for(let f of o){let x=f.expression??f,b=i.slice(x.start,x.end);g.push({kind:"implements",name:b})}return g}function S(c){let g=[];for(let o of c.extends??[]){let f=o.expression??o,x=i.slice(f.start,f.end);g.push({kind:"extends",name:x})}return g}function N(c){let g=[];for(let o of c)if(o.type==="MethodDefinition"){let f=o.key?.name??"unknown",x=o.value,b=o.kind??"method",D=b==="constructor"?"constructor":b==="get"?"getter":b==="set"?"setter":"method",$=l(o,x),k=(x?.params??[]).map(p),h=u(x?.returnType),M={kind:"method",name:f,span:s(o.start,o.end),isExported:!1,methodKind:D,modifiers:$,parameters:k.length>0?k:void 0,returnType:h};g.push(M)}else if(o.type==="PropertyDefinition"){let f=o.key?.name??"unknown",x=l(o),b={kind:"property",name:f,span:s(o.start,o.end),isExported:!1,modifiers:x};g.push(b)}return g}function J(c){let g=[];for(let o of c)if(o.type==="TSMethodSignature"){let f=o.key?.name??"unknown",x=(o.params??[]).map(p),b=u(o.returnType);g.push({kind:"method",name:f,span:s(o.start,o.end),isExported:!1,modifiers:[],methodKind:"method",parameters:x.length>0?x:void 0,returnType:b})}else if(o.type==="TSPropertySignature"){let f=o.key?.name??"unknown",x=u(o.typeAnnotation),b={kind:"property",name:f,span:s(o.start,o.end),isExported:!1,modifiers:o.readonly?["readonly"]:[],returnType:x};g.push(b)}return g}function A(c,g){let o=c.type??"";if(o==="FunctionDeclaration"){let f=c.id?.name??"default",x=(c.params??[]).map(p),b=u(c.returnType),D=l(c,c),$=a(c.decorators??[]),k=c.typeParameters?.params?.map((M)=>M.name?.name).filter(Boolean)||void 0,h={kind:"function",name:f,span:s(c.start,c.end),isExported:g,modifiers:D,parameters:x.length>0?x:void 0,returnType:b,decorators:$.length>0?$:void 0};if(k&&k.length>0)h.typeParameters=k;return h}if(o==="ClassDeclaration"||o==="ClassExpression"){let f=c.id?.name??"default",x=d(c),b=N(c.body?.body??[]),D=a(c.decorators??[]),$=l(c,c),k=c.typeParameters?.params?.map((M)=>M.name?.name).filter(Boolean)||void 0,h={kind:"class",name:f,span:s(c.start,c.end),isExported:g,modifiers:$,heritage:x.length>0?x:void 0,members:b.length>0?b:void 0,decorators:D.length>0?D:void 0};if(k&&k.length>0)h.typeParameters=k;return h}if(o==="VariableDeclaration"){let f=[];for(let x of c.declarations??[]){let{id:b,init:D}=x;if(b?.type==="ObjectPattern"){for(let I of b.properties??[]){let L=I.value?.name??I.key?.name??"unknown";f.push({kind:"variable",name:L,span:s(I.start??x.start,I.end??x.end),isExported:g,modifiers:[]})}continue}if(b?.type==="ArrayPattern"){for(let I of b.elements??[]){if(!I||I.type!=="Identifier")continue;let L=I.name??"unknown";f.push({kind:"variable",name:L,span:s(I.start??x.start,I.end??x.end),isExported:g,modifiers:[]})}continue}let $=b?.name??"unknown",k="variable",h,M;if(D?.type==="FunctionExpression"||D?.type==="ArrowFunctionExpression")k="function",h=(D.params??[]).map(p),M=u(D.returnType);let C=[];f.push({kind:k,name:$,span:s(x.start,x.end),isExported:g,modifiers:C,parameters:h,returnType:M})}if(f.length===0)return null;if(f.length===1)return f[0];return f}if(o==="TSTypeAliasDeclaration")return{kind:"type",name:c.id?.name??"unknown",span:s(c.start,c.end),isExported:g,modifiers:[]};if(o==="TSInterfaceDeclaration"){let f=c.id?.name??"unknown",x=S(c),b=J(c.body?.body??[]),D=c.typeParameters?.params?.map((k)=>k.name?.name).filter(Boolean)||void 0,$={kind:"interface",name:f,span:s(c.start,c.end),isExported:g,modifiers:[],heritage:x.length>0?x:void 0,members:b.length>0?b:void 0};if(D&&D.length>0)$.typeParameters=D;return $}if(o==="TSEnumDeclaration"){let f=c.id?.name??"unknown",x=l(c),D=(c.body?.members??[]).map(($)=>({kind:"property",name:$.id?.name??$.id?.value??"unknown",span:s($.start,$.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:f,span:s(c.start,c.end),isExported:g,modifiers:x,members:D.length>0?D:void 0}}return null}let F=[];for(let c of t.body){let g=null,o=c,f=typeof o.type==="string"?o.type:"";if(f==="ExportNamedDeclaration"){let b=c;if(b.declaration){if(g=A(b.declaration,!0),g&&!Array.isArray(g))g.span=s(b.start,b.end);else if(Array.isArray(g))for(let D of g)D.span=s(b.start,b.end)}}else if(f==="ExportDefaultDeclaration"){let b=c,D=b.declaration;if(D){if(g=A(D,!0),g&&!Array.isArray(g))g.name=D.id?.name??"default",g.isExported=!0,g.span=s(b.start,b.end)}}else g=A(c,!1);let x=Array.isArray(g)?g:g?[g]:[];for(let b of x){let D=c.start??0,$=m(D);if($){let k=Zn($);if(!At(k))b.jsDoc=k}F.push(b)}}return F}import{resolve as Fn,dirname as Dt,extname as kt}from"path";function _n(n,t,i){let e=(r)=>{let s=kt(r);if(s==="")return[r+".ts",r+"/index.ts",r+".mts",r+"/index.mts",r+".cts",r+"/index.cts"];if(s===".js")return[r.slice(0,-3)+".ts"];if(s===".mjs")return[r.slice(0,-4)+".mts"];if(s===".cjs")return[r.slice(0,-4)+".cts"];return[r]};if(t.startsWith(".")){let r=Fn(Dt(n),t);return e(r)}if(i)for(let[r,s]of i.paths){if(s.length===0)continue;let m=r.indexOf("*");if(m===-1){if(t===r){let u=[];for(let a of s)u.push(...e(Fn(i.baseUrl,a)));return u}}else{let u=r.slice(0,m),a=r.slice(m+1);if(t.startsWith(u)&&(a===""||t.endsWith(a))){let p=t.slice(u.length,a===""?void 0:t.length-a.length),l=[];for(let d of s)l.push(...e(Fn(i.baseUrl,d.replace("*",p))));return l}}}return[]}function vn(n,t,i,e=_n){let r=new Map,s=n.body??[];for(let m of s){if(m.type!=="ImportDeclaration")continue;let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.specifiers??[];for(let d of l)switch(d.type){case"ImportSpecifier":r.set(d.local.name,{path:p,importedName:d.imported.name});break;case"ImportDefaultSpecifier":r.set(d.local.name,{path:p,importedName:"default"});break;case"ImportNamespaceSpecifier":r.set(d.local.name,{path:p,importedName:"*"});break}}return r}var Ft=new Set(["loc","start","end","scope"]);function an(n,t){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let e of n)an(e,t);return}let i=n;t(i);for(let e of Object.keys(i)){if(Ft.has(e))continue;let r=i[e];if(r&&typeof r==="object")an(r,t)}}function Xn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if((t.type==="StringLiteral"||t.type==="Literal")&&typeof t.value==="string")return t.value;return null}function nn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.type==="Identifier"){let i=t.name;return{root:i,parts:[],full:i}}if(t.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(t.type==="Super")return{root:"super",parts:[],full:"super"};if(t.type==="MemberExpression"){let i=[],e=t;while(e.type==="MemberExpression"){let m=e.property;if(!m||typeof m.name!=="string")return null;i.unshift(m.name),e=e.object}let r;if(e.type==="Identifier")r=e.name;else if(e.type==="ThisExpression")r="this";else if(e.type==="Super")r="super";else return null;let s=[r,...i].join(".");return{root:r,parts:i,full:s}}return null}function Pn(n,t,i,e=_n){let r=[],s=n.body??[];for(let m of s){if(m.type==="ImportDeclaration"){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.importKind==="type",d=m.specifiers??[];if(d.length===0){let S={};if(l)S.isType=!0;r.push({type:l?"type-references":"imports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,...Object.keys(S).length>0?{metaJson:JSON.stringify(S)}:{}})}else for(let S of d){let N=S.type,J=l||S.importKind==="type",A={};if(J)A.isType=!0;let F,c;if(N==="ImportDefaultSpecifier")F="default",c=S.local.name;else if(N==="ImportNamespaceSpecifier")F="*",c=S.local.name,A.importKind="namespace";else F=S.imported.name,c=S.local.name;r.push({type:J?"type-references":"imports",srcFilePath:t,srcSymbolName:c,dstFilePath:p,dstSymbolName:F,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}continue}if(m.type==="ExportAllDeclaration"&&m.source){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.exportKind==="type",d={isReExport:!0};if(l)d.isType=!0;r.push({type:l?"type-references":"re-exports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify(d)});continue}if(m.type==="ExportNamedDeclaration"&&m.source){let u=m.source?.value??"",a=e(t,u,i);if(a.length===0)continue;let p=a[0],l=m.exportKind==="type",N={isReExport:!0,specifiers:(m.specifiers??[]).map((J)=>({local:J.local.name,exported:J.exported.name}))};if(l)N.isType=!0;r.push({type:l?"type-references":"re-exports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify(N)})}}return an(n,(m)=>{if(m.type!=="ImportExpression")return;let u=Xn(m.source);if(!u)return;let a=e(t,u,i);if(a.length===0)return;let p=a[0];r.push({type:"imports",srcFilePath:t,srcSymbolName:null,dstFilePath:p,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),r}function En(n,t,i){let e=[],r=[],s=[];function m(){if(r.length>0)return r[r.length-1]??null;return null}function u(p){if(!p)return null;let l=i.get(p.root);if(p.parts.length===0){if(l)return{dstFilePath:l.path,dstSymbolName:l.importedName,resolution:"import"};return{dstFilePath:t,dstSymbolName:p.root,resolution:"local"}}else{if(l&&l.importedName==="*"){let d=p.parts[p.parts.length-1];return{dstFilePath:l.path,dstSymbolName:d,resolution:"namespace"}}return{dstFilePath:t,dstSymbolName:p.full,resolution:"local-member"}}}function a(p){if(!p||typeof p!=="object")return;if(Array.isArray(p)){for(let S of p)a(S);return}let l=p,d=typeof l.type==="string"?l.type:"";if(d==="ClassDeclaration"||d==="ClassExpression"){let S=l,N=S.id?.name??"AnonymousClass";s.push(N),a(S.body),s.pop();return}if(d==="FunctionDeclaration"){let S=l,N=S.id?.name??"anonymous";r.push(N),a(S.body),r.pop();return}if(d==="VariableDeclarator"&&l.init&&(l.init?.type==="FunctionExpression"||l.init?.type==="ArrowFunctionExpression")){let S=l,N=S.id?.name??"anonymous";r.push(N),a(S.init?.body??S.init),r.pop();return}if(d==="MethodDefinition"&&l.value){let S=l,N=s[s.length-1]??"",J=S.key?.name??"anonymous",A=N?`${N}.${J}`:J;r.push(A),a(S.value?.body),r.pop();return}if(d==="FunctionExpression"||d==="ArrowFunctionExpression"){let S=m(),N=S?`${S}.<anonymous>`:"<anonymous>";r.push(N),a(l.body),r.pop();return}if(d==="CallExpression"){let S=l,N=nn(S.callee),J=u(N);if(J){let A=m(),F={};if(A===null)F.scope="module";e.push({type:"calls",srcFilePath:t,srcSymbolName:A,dstFilePath:J.dstFilePath,dstSymbolName:J.dstSymbolName,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}a(S.callee);for(let A of S.arguments??[])a(A);return}if(d==="NewExpression"){let S=l,N=nn(S.callee),J=u(N);if(J){let A=m(),F={isNew:!0};if(A===null)F.scope="module";e.push({type:"calls",srcFilePath:t,srcSymbolName:A,dstFilePath:J.dstFilePath,dstSymbolName:J.dstSymbolName,metaJson:JSON.stringify(F)})}for(let A of S.arguments??[])a(A);return}for(let S of Object.keys(l)){if(S==="loc"||S==="start"||S==="end"||S==="scope")continue;let N=l[S];if(N&&typeof N==="object")a(N)}}return a(n),e}function jn(n,t,i){let e=[];return an(n,(r)=>{if(r.type==="TSInterfaceDeclaration"){let u=r.id?.name??"AnonymousInterface",a=r.extends??[];for(let p of a){let l=p.expression??p,d=nn(l);if(!d)continue;let S=Jn(d,t,i);e.push({type:"extends",srcFilePath:t,srcSymbolName:u,...S})}return}if(r.type!=="ClassDeclaration"&&r.type!=="ClassExpression")return;let s=r.id?.name??"AnonymousClass";if(r.superClass){let u=nn(r.superClass);if(u){let a=Jn(u,t,i);e.push({type:"extends",srcFilePath:t,srcSymbolName:s,...a})}}let m=r.implements??[];for(let u of m){let a=u.expression??u,p=nn(a);if(!p)continue;let l=Jn(p,t,i);e.push({type:"implements",srcFilePath:t,srcSymbolName:s,...l})}}),e}function Jn(n,t,i){let e=i.get(n.root);if(e){if(e.importedName==="*"){let r=n.parts[n.parts.length-1]??n.root;return{dstFilePath:e.path,dstSymbolName:r,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:e.path,dstSymbolName:n.parts.length>0?n.full:e.importedName}}return{dstFilePath:t,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function pn(n,t,i){let e=vn(n,t,i),r=Pn(n,t,i),s=En(n,t,e),m=jn(n,t,e);return[...r,...s,...m]}import{err as qn,isErr as It}from"@zipbul/result";import{Database as Kt}from"bun:sqlite";import{mkdirSync as Rt,unlinkSync as nt,existsSync as tt}from"fs";import{dirname as Tt,join as it}from"path";import{drizzle as zt}from"drizzle-orm/bun-sqlite";import{migrate as Lt}from"drizzle-orm/bun-sqlite/migrator";var X=".gildash",gn="gildash.db";var $n={};St($n,{watcherOwner:()=>Ct,symbols:()=>_,relations:()=>w,files:()=>z});import{sql as _t}from"drizzle-orm";import{sqliteTable as xn,text as T,integer as H,real as Jt,index as tn,primaryKey as Mt,foreignKey as Mn,check as $t}from"drizzle-orm/sqlite-core";var z=xn("files",{project:T("project").notNull(),filePath:T("file_path").notNull(),mtimeMs:Jt("mtime_ms").notNull(),size:H("size").notNull(),contentHash:T("content_hash").notNull(),updatedAt:T("updated_at").notNull(),lineCount:H("line_count")},(n)=>[Mt({columns:[n.project,n.filePath]})]),_=xn("symbols",{id:H("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),kind:T("kind").notNull(),name:T("name").notNull(),startLine:H("start_line").notNull(),startColumn:H("start_column").notNull(),endLine:H("end_line").notNull(),endColumn:H("end_column").notNull(),isExported:H("is_exported").notNull().default(0),signature:T("signature"),fingerprint:T("fingerprint"),detailJson:T("detail_json"),contentHash:T("content_hash").notNull(),indexedAt:T("indexed_at").notNull()},(n)=>[tn("idx_symbols_project_file").on(n.project,n.filePath),tn("idx_symbols_project_kind").on(n.project,n.kind),tn("idx_symbols_project_name").on(n.project,n.name),tn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Mn({columns:[n.project,n.filePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade")]),w=xn("relations",{id:H("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),type:T("type").notNull(),srcFilePath:T("src_file_path").notNull(),srcSymbolName:T("src_symbol_name"),dstFilePath:T("dst_file_path").notNull(),dstSymbolName:T("dst_symbol_name"),metaJson:T("meta_json")},(n)=>[tn("idx_relations_src").on(n.project,n.srcFilePath),tn("idx_relations_dst").on(n.project,n.dstFilePath),tn("idx_relations_type").on(n.project,n.type),Mn({columns:[n.project,n.srcFilePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade"),Mn({columns:[n.project,n.dstFilePath],foreignColumns:[z.project,z.filePath]}).onDelete("cascade")]),Ct=xn("watcher_owner",{id:H("id").primaryKey(),pid:H("pid").notNull(),startedAt:T("started_at").notNull(),heartbeatAt:T("heartbeat_at").notNull()},(n)=>[$t("watcher_owner_singleton",_t`${n.id} = 1`)]);class Cn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=it(n.projectRoot,X,gn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Rt(Tt(this.dbPath),{recursive:!0}),this.client=new Kt(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = ON"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=zt(this.client,{schema:$n}),Lt(this.drizzle,{migrationsFolder:it(import.meta.dirname,"migrations")});let n=this.client;if(typeof n.function==="function")n.function.call(this.client,"regexp",(t,i)=>{try{return new RegExp(t).test(i)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&tt(this.dbPath)){this.closeClient(),nt(this.dbPath);for(let i of["-wal","-shm"]){let e=this.dbPath+i;if(tt(e))nt(e)}let t=this.open();if(It(t))return qn(y("store",`Failed to recover database at ${this.dbPath}`,t.data));return t}return qn(y("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let t=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return t.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;t.run(`SAVEPOINT "${i}"`);try{let e=n(this);return t.run(`RELEASE SAVEPOINT "${i}"`),e}catch(e){throw t.run(`ROLLBACK TO SAVEPOINT "${i}"`),t.run(`RELEASE SAVEPOINT "${i}"`),e}finally{this.txDepth--}}immediateTransaction(n){let t=this.requireClient();this.txDepth++,t.run("BEGIN IMMEDIATE");try{let i=n();return t.run("COMMIT"),i}catch(i){throw t.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let t=this.requireClient().prepare(n).get();if(!t)return null;return Object.values(t)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((t)=>t.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let t=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,t,t)}replaceOwner(n){let t=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,t,t)}touchOwner(n){let t=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(t,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let t=n.message.toLowerCase();return t.includes("malformed")||t.includes("corrupt")||t.includes("not a database")||t.includes("disk i/o error")||t.includes("sqlite_corrupt")}}import{eq as mn,and as et}from"drizzle-orm";class In{db;constructor(n){this.db=n}getFile(n,t){return this.db.drizzleDb.select().from(z).where(et(mn(z.project,n),mn(z.filePath,t))).get()??null}upsertFile(n){this.db.drizzleDb.insert(z).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[z.project,z.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(z).where(mn(z.project,n)).all()}getFilesMap(n){let t=this.getAllFiles(n),i=new Map;for(let e of t)i.set(e.filePath,e);return i}deleteFile(n,t){this.db.drizzleDb.delete(z).where(et(mn(z.project,n),mn(z.filePath,t))).run()}}import{eq as G,and as en,sql as yn,count as Gt}from"drizzle-orm";function dn(n){return n.trim().split(/\s+/).map((t)=>t.trim()).filter((t)=>t.length>0).map((t)=>`"${t.replaceAll('"','""')}"*`).join(" ")}class Kn{db;constructor(n){this.db=n}replaceFileSymbols(n,t,i,e){if(this.db.drizzleDb.delete(_).where(en(G(_.project,n),G(_.filePath,t))).run(),!e.length)return;let r=new Date().toISOString();for(let s of e)this.db.drizzleDb.insert(_).values({project:n,filePath:t,kind:s.kind??"unknown",name:s.name??"",startLine:s.startLine??0,startColumn:s.startColumn??0,endLine:s.endLine??0,endColumn:s.endColumn??0,isExported:s.isExported??0,signature:s.signature??null,fingerprint:s.fingerprint??null,detailJson:s.detailJson??null,contentHash:i,indexedAt:s.indexedAt??r}).run()}getFileSymbols(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.filePath,t))).all()}searchByName(n,t,i={}){let e=i.limit??50,r=dn(t);if(!r)return[];return this.db.drizzleDb.select().from(_).where(en(yn`${_.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${r})`,G(_.project,n),i.kind?G(_.kind,i.kind):void 0)).orderBy(_.name).limit(e).all()}searchByKind(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.kind,t))).orderBy(_.name).all()}getStats(n){let t=this.db.drizzleDb.select({symbolCount:Gt(),fileCount:yn`COUNT(DISTINCT ${_.filePath})`}).from(_).where(G(_.project,n)).get();return{symbolCount:t?.symbolCount??0,fileCount:t?.fileCount??0}}getByFingerprint(n,t){return this.db.drizzleDb.select().from(_).where(en(G(_.project,n),G(_.fingerprint,t))).all()}deleteFileSymbols(n,t){this.db.drizzleDb.delete(_).where(en(G(_.project,n),G(_.filePath,t))).run()}searchByQuery(n){let t=this.db.drizzleDb.select().from(_).where(en(n.ftsQuery?yn`${_.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?G(_.name,n.exactName):void 0,n.project!==void 0?G(_.project,n.project):void 0,n.kind?G(_.kind,n.kind):void 0,n.filePath!==void 0?G(_.filePath,n.filePath):void 0,n.isExported!==void 0?G(_.isExported,n.isExported?1:0):void 0,n.decorator?yn`${_.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0)).orderBy(_.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return t;try{let i=new RegExp(n.regex);return t.filter((e)=>i.test(e.name)).slice(0,n.limit)}catch{return[]}}}import{eq as R,and as Y,isNull as rt,or as Bt}from"drizzle-orm";class Rn{db;constructor(n){this.db=n}replaceFileRelations(n,t,i){if(this.db.drizzleDb.delete(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).run(),!i.length)return;for(let e of i)this.db.drizzleDb.insert(w).values({project:n,type:e.type??"unknown",srcFilePath:e.srcFilePath??t,srcSymbolName:e.srcSymbolName??null,dstFilePath:e.dstFilePath??"",dstSymbolName:e.dstSymbolName??null,metaJson:e.metaJson??null}).run()}getOutgoing(n,t,i){if(i!==void 0)return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.srcFilePath,t),Bt(R(w.srcSymbolName,i),rt(w.srcSymbolName)))).all();return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).all()}getIncoming(n,t){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.dstFilePath,t))).all()}getByType(n,t){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(R(w.project,n),R(w.type,t))).all()}deleteFileRelations(n,t){this.db.drizzleDb.delete(w).where(Y(R(w.project,n),R(w.srcFilePath,t))).run()}searchRelations(n){return this.db.drizzleDb.select({project:w.project,type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,metaJson:w.metaJson}).from(w).where(Y(n.project!==void 0?R(w.project,n.project):void 0,n.srcFilePath!==void 0?R(w.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?R(w.srcSymbolName,n.srcSymbolName):void 0,n.dstFilePath!==void 0?R(w.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?R(w.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?R(w.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n,t,i,e,r){let s=i===null?Y(R(w.project,n),R(w.dstFilePath,t),rt(w.dstSymbolName)):Y(R(w.project,n),R(w.dstFilePath,t),R(w.dstSymbolName,i));this.db.drizzleDb.update(w).set({dstFilePath:e,dstSymbolName:r}).where(s).run()}}import{err as st}from"@zipbul/result";import{subscribe as Wt}from"@parcel/watcher";import Tn from"path";var Ht=["**/.git/**",`**/${X}/**`,"**/dist/**","**/node_modules/**"],Ut=new Set(["package.json","tsconfig.json"]);function Vt(n){return n.replaceAll("\\","/")}function Qt(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class wn{#t;#n;#e;#r;#s;#i;constructor(n,t=Wt,i=console){this.#n=n.projectRoot,this.#e=[...Ht,...n.ignorePatterns??[]],this.#r=new Set((n.extensions??[".ts",".mts",".cts"]).map((e)=>e.toLowerCase())),this.#s=t,this.#i=i}async start(n){try{this.#t=await this.#s(this.#n,(t,i)=>{if(t){this.#i.error(y("watcher","Callback error",t));return}try{for(let e of i){let r=Vt(Tn.relative(this.#n,e.path));if(r.startsWith(".."))continue;let s=Tn.basename(r),m=Tn.extname(r).toLowerCase();if(!Ut.has(s)&&!this.#r.has(m))continue;if(r.endsWith(".d.ts"))continue;n({eventType:Qt(e.type),filePath:r})}}catch(e){this.#i.error(y("watcher","Callback error",e))}},{ignore:this.#e})}catch(t){return st(y("watcher","Failed to subscribe watcher",t))}}async close(){if(!this.#t)return;try{await this.#t.unsubscribe(),this.#t=void 0}catch(n){return st(y("watcher","Failed to close watcher",n))}}}import zn from"path";import{promises as Yt}from"fs";var Zt=["**/node_modules/**","**/.git/**",`**/${X}/**`,"**/dist/**"];async function Sn(n){let t=[];for await(let i of Yt.glob("**/package.json",{cwd:n,exclude:Zt})){let e=zn.dirname(i).replaceAll("\\","/"),r=zn.join(n,i),s=await Bun.file(r).json(),m=typeof s?.name==="string"&&s.name.length>0?s.name:zn.basename(e==="."?n:e);t.push({dir:e,project:m})}return t.sort((i,e)=>e.dir.length-i.dir.length),t}function U(n,t,i="default"){let e=n.replaceAll("\\","/");for(let r of t){if(r.dir===".")return r.project;if(e===r.dir||e.startsWith(`${r.dir}/`))return r.project}return i}import at from"path";var P=new Map;async function vt(n){let t=Bun.file(n);if(!await t.exists())return null;try{let i=await t.text(),e=Bun.JSONC.parse(i);return typeof e==="object"&&e!==null?e:null}catch{return null}}async function cn(n){if(P.has(n))return P.get(n)??null;let t=at.join(n,"tsconfig.json"),i=await vt(t);if(!i)return P.set(n,null),null;let e=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!e)return P.set(n,null),null;let r=typeof e.baseUrl==="string"?e.baseUrl:null,s=typeof e.paths==="object"&&e.paths!==null?e.paths:null;if(!r&&!s)return P.set(n,null),null;let m=r?at.resolve(n,r):n,u=new Map;if(s)for(let[p,l]of Object.entries(s)){if(!Array.isArray(l))continue;let d=l.filter((S)=>typeof S==="string");u.set(p,d)}let a={baseUrl:m,paths:u};return P.set(n,a),a}function bn(n){if(n){P.delete(n);return}P.clear()}import ot from"path";function Ln(n,t){return ot.relative(n,t).replaceAll("\\","/")}function on(n,t){return ot.resolve(n,t)}function E(n){let t=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(t)).toString(16).padStart(16,"0")}import{isErr as ct}from"@zipbul/result";import{promises as Xt}from"fs";import{join as Pt}from"path";async function ut(n){let{projectRoot:t,extensions:i,ignorePatterns:e,fileRepo:r}=n,s=r.getFilesMap(),m=new Set,u=[],a=[],p=e.map((d)=>new Bun.Glob(d));for await(let d of Xt.glob("**/*",{cwd:t})){if(!i.some((o)=>d.endsWith(o)))continue;if(p.some((o)=>o.match(d)))continue;m.add(d);let S=Pt(t,d),N=Bun.file(S),{size:J,lastModified:A}=N,F=s.get(d);if(!F){let o=await N.text(),f=E(o);u.push({filePath:d,contentHash:f,mtimeMs:A,size:J});continue}if(F.mtimeMs===A&&F.size===J){a.push({filePath:d,contentHash:F.contentHash,mtimeMs:A,size:J});continue}let c=await N.text(),g=E(c);if(g===F.contentHash)a.push({filePath:d,contentHash:g,mtimeMs:A,size:J});else u.push({filePath:d,contentHash:g,mtimeMs:A,size:J})}let l=[];for(let d of s.keys())if(!m.has(d))l.push(d);return{changed:u,unchanged:a,deleted:l}}function Et(n){if(n.kind==="function"||n.kind==="method"){let t=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${t}|async:${i}`}return null}function jt(n){let t={};if(n.jsDoc)t.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)t.parameters=n.parameters;if(n.returnType!==void 0)t.returnType=n.returnType}if(n.heritage?.length)t.heritage=n.heritage;if(n.decorators?.length)t.decorators=n.decorators;if(n.typeParameters?.length)t.typeParameters=n.typeParameters;if(n.modifiers?.length)t.modifiers=n.modifiers;if(n.members?.length)t.members=n.members.map((i)=>{let e=i.modifiers.find((r)=>r==="private"||r==="protected"||r==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:e,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(t).length>0?JSON.stringify(t):null}function mt(n,t,i,e,r){let s=Et(n),m=E(`${t}|${n.kind}|${s??""}`);return{project:i,filePath:e,kind:n.kind,name:t,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:s,fingerprint:m,detailJson:jt(n),contentHash:r,indexedAt:new Date().toISOString()}}function Gn(n){let{parsed:t,project:i,filePath:e,contentHash:r,symbolRepo:s}=n,m=ln(t),u=[];for(let a of m){u.push(mt(a,a.name,i,e,r));for(let p of a.members??[])u.push(mt(p,`${a.name}.${p.name}`,i,e,r))}s.replaceFileSymbols(i,e,r,u)}function Bn(n){let{ast:t,project:i,filePath:e,relationRepo:r,projectRoot:s,tsconfigPaths:m}=n,u=on(s,e),a=pn(t,u,m),p=[];for(let l of a){let d=Ln(s,l.dstFilePath);if(d.startsWith(".."))continue;let S=Ln(s,l.srcFilePath);p.push({project:i,type:l.type,srcFilePath:S,srcSymbolName:l.srcSymbolName??null,dstFilePath:d,dstSymbolName:l.dstSymbolName??null,metaJson:l.metaJson??null})}return r.replaceFileRelations(i,e,p),p.length}var qt=100;class fn{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=cn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){bn(this.opts.projectRoot),this.tsconfigPathsRaw=cn(this.opts.projectRoot),this.fullIndex().catch((t)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",t)});return}if(n.filePath.endsWith("package.json")){let t=this.opts.discoverProjectsFn??Sn;this.boundariesRefresh=t(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},qt)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,t){if(this.indexingLock){if(t)return this.pendingFullIndex=!0,new Promise((e,r)=>{this.pendingFullIndexWaiters.push({resolve:e,reject:r})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,t).then((e)=>{return this.fireCallbacks(e),e}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let e=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((r)=>{for(let s of e)s.resolve(r)}).catch((r)=>{for(let s of e)s.reject(r)})}else if(this.pendingEvents.length>0){let e=this.pendingEvents.splice(0);this.startIndex(e,!1).catch((r)=>this.logger.error("[IndexCoordinator] incremental drain error",r))}});return this.currentIndexing=i,i}async doIndex(n,t){let i=Date.now(),{fileRepo:e,symbolRepo:r,relationRepo:s,dbConnection:m}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let u,a;if(n!==void 0)u=n.filter((o)=>o.eventType==="create"||o.eventType==="change").map((o)=>({filePath:o.filePath,contentHash:"",mtimeMs:0,size:0})),a=n.filter((o)=>o.eventType==="delete").map((o)=>o.filePath);else{let o=new Map;for(let x of this.opts.boundaries)for(let[b,D]of e.getFilesMap(x.project))o.set(b,D);let f=await ut({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>o}});u=f.changed,a=f.deleted}let p=await this.tsconfigPathsRaw??void 0,l=new Map;for(let o of a){let f=U(o,this.opts.boundaries),x=r.getFileSymbols(f,o);l.set(o,x)}let d=new Map,S=new Map;if(t)for(let o of this.opts.boundaries)for(let f of e.getAllFiles(o.project))for(let x of r.getFileSymbols(o.project,f.filePath))d.set(`${x.filePath}::${x.name}`,{name:x.name,filePath:x.filePath,kind:x.kind,fingerprint:x.fingerprint});else{for(let o of u){let f=U(o.filePath,this.opts.boundaries);for(let x of r.getFileSymbols(f,o.filePath))d.set(`${x.filePath}::${x.name}`,{name:x.name,filePath:x.filePath,kind:x.kind,fingerprint:x.fingerprint})}for(let[,o]of l)for(let f of o)d.set(`${f.filePath}::${f.name}`,{name:f.name,filePath:f.filePath,kind:f.kind,fingerprint:f.fingerprint})}let N=()=>{for(let o of a){let f=U(o,this.opts.boundaries);r.deleteFileSymbols(f,o),s.deleteFileRelations(f,o),e.deleteFile(f,o)}},J=async()=>{let o=0,f=0,x=[];for(let b of u)try{let D=await this.processFile(b.filePath,b.contentHash||void 0,p);o+=D.symbolCount,f+=D.relCount}catch(D){this.logger.error(`[IndexCoordinator] Failed to index ${b.filePath}:`,D),x.push(b.filePath)}return{symbols:o,relations:f,failedFiles:x}},A=0,F=0,c=[];if(t){let{projectRoot:o,boundaries:f}=this.opts,{parseCache:x}=this.opts,b=await Promise.allSettled(u.map(async(k)=>{let h=on(o,k.filePath),M=Bun.file(h),C=await M.text(),I=k.contentHash||E(C);return{filePath:k.filePath,text:C,contentHash:I,mtimeMs:M.lastModified,size:M.size}})),D=b.filter((k)=>k.status==="fulfilled").map((k)=>k.value);for(let k of b)if(k.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",k.reason);let $=[];m.transaction(()=>{for(let h of D){let M=U(h.filePath,f);e.deleteFile(M,h.filePath)}for(let h of a){let M=U(h,f);r.deleteFileSymbols(M,h),s.deleteFileRelations(M,h),e.deleteFile(M,h)}for(let h of D){let M=U(h.filePath,f);e.upsertFile({project:M,filePath:h.filePath,mtimeMs:h.mtimeMs,size:h.size,contentHash:h.contentHash,updatedAt:new Date().toISOString(),lineCount:h.text.split(`
|
|
4
|
-
`).length})
|
|
5
|
-
`).length}),Gn({parsed:F,project:N,filePath:n,contentHash:S,symbolRepo:m});let c=Bn({ast:F.program,project:N,filePath:n,relationRepo:u,projectRoot:e,tsconfigPaths:i});return{symbolCount:m.getFileSymbols(N,n).length,relCount:c}}fireCallbacks(n){for(let t of this.callbacks)try{t(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((t)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",t))}}}function ni(n){try{return process.kill(n,0),!0}catch(t){if(typeof t==="object"&&t&&"code"in t)return t.code!=="ESRCH";return!0}}function ti(n){let t=new Date(n).getTime();return Number.isNaN(t)?0:t}function ft(n,t,i={}){let e=i.now??Date.now,r=i.isAlive??ni,s=i.staleAfterSeconds??90;return n.immediateTransaction(()=>{let m=n.selectOwner();if(!m)return n.insertOwner(t),"owner";let u=Math.floor((e()-ti(m.heartbeat_at))/1000);if(r(m.pid)&&u<s)return"reader";return n.replaceOwner(t),"owner"})}function lt(n,t){n.deleteOwner(t)}function pt(n,t){n.touchOwner(t)}function Wn(n){let{symbolRepo:t,project:i,query:e}=n,r=e.project??i,s=e.limit??100,m={kind:e.kind,filePath:e.filePath,isExported:e.isExported,project:r,limit:s};if(e.text)if(e.exact)m.exactName=e.text;else{let a=dn(e.text);if(a)m.ftsQuery=a}if(e.decorator)m.decorator=e.decorator;if(e.regex)m.regex=e.regex;return t.searchByQuery(m).map((a)=>({id:a.id,filePath:a.filePath,kind:a.kind,name:a.name,span:{start:{line:a.startLine,column:a.startColumn},end:{line:a.endLine,column:a.endColumn}},isExported:a.isExported===1,signature:a.signature,fingerprint:a.fingerprint,detail:a.detailJson?(()=>{try{return JSON.parse(a.detailJson)}catch{return{}}})():{}}))}function Hn(n){let{relationRepo:t,project:i,query:e}=n,r=e.project??i,s=e.limit??500;return t.searchRelations({srcFilePath:e.srcFilePath,srcSymbolName:e.srcSymbolName,dstFilePath:e.dstFilePath,dstSymbolName:e.dstSymbolName,type:e.type,project:r,limit:s}).map((u)=>{let a;if(u.metaJson)try{a=JSON.parse(u.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",u.metaJson)}return{type:u.type,srcFilePath:u.srcFilePath,srcSymbolName:u.srcSymbolName,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,metaJson:u.metaJson??void 0,meta:a}})}class On{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let n=[...this.options.relationRepo.getByType(this.options.project,"imports"),...this.options.relationRepo.getByType(this.options.project,"type-references"),...this.options.relationRepo.getByType(this.options.project,"re-exports")];for(let t of n){let{srcFilePath:i,dstFilePath:e}=t;if(!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(this.adjacencyList.get(i).add(e),!this.adjacencyList.has(e))this.adjacencyList.set(e,new Set);if(!this.reverseAdjacencyList.has(e))this.reverseAdjacencyList.set(e,new Set);this.reverseAdjacencyList.get(e).add(i)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let t=new Set,i=[n];while(i.length>0){let e=i.shift();for(let r of this.reverseAdjacencyList.get(e)??[])if(!t.has(r))t.add(r),i.push(r)}return Array.from(t)}hasCycle(){let n=new Set,t=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let e=[{node:i,entered:!1}];while(e.length>0){let r=e.pop();if(r.entered){t.delete(r.node);continue}if(t.has(r.node))return!0;if(n.has(r.node))continue;n.add(r.node),t.add(r.node),e.push({node:r.node,entered:!0});for(let s of this.adjacencyList.get(r.node)??[]){if(t.has(s))return!0;if(!n.has(s))e.push({node:s,entered:!1})}}}return!1}getAffectedByChange(n){let t=new Set;for(let i of n)for(let e of this.getTransitiveDependents(i))t.add(e);return Array.from(t)}getAdjacencyList(){let n=new Map;for(let[t,i]of this.adjacencyList)n.set(t,Array.from(i));return n}getTransitiveDependencies(n){let t=new Set,i=[n];while(i.length>0){let e=i.shift();for(let r of this.adjacencyList.get(e)??[])if(!t.has(r))t.add(r),i.push(r)}return Array.from(t)}getCyclePaths(n){let t=n?.maxCycles??1/0;if(t<=0)return[];let i=new Map;for(let[e,r]of this.adjacencyList)i.set(e,Array.from(r));return ai(i,t)}}var ii=(n,t)=>n.localeCompare(t);function ei(n){let t=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(t.length===0)return[];let i=t;for(let e=1;e<t.length;e++){let r=t.slice(e).concat(t.slice(0,e));if(r.join("::")<i.join("::"))i=r}return[...i]}function Un(n,t,i){let e=ei(i);if(e.length===0)return!1;let r=e.join("->");if(n.has(r))return!1;return n.add(r),t.push(e),!0}function ri(n){let t=0,i=[],e=new Set,r=new Map,s=new Map,m=[],u=(a)=>{r.set(a,t),s.set(a,t),t+=1,i.push(a),e.add(a);for(let p of n.get(a)??[])if(!r.has(p))u(p),s.set(a,Math.min(s.get(a)??0,s.get(p)??0));else if(e.has(p))s.set(a,Math.min(s.get(a)??0,r.get(p)??0));if(s.get(a)===r.get(a)){let p=[],l="";do l=i.pop()??"",e.delete(l),p.push(l);while(l!==a&&i.length>0);m.push(p)}};for(let a of n.keys())if(!r.has(a))u(a);return{components:m}}function si(n,t,i){let e=[],r=new Set,s=[...n].sort(ii),m=(u,a,p)=>{a.delete(u);let l=p.get(u);if(!l)return;for(let d of l)if(a.has(d))m(d,a,p);l.clear()};for(let u=0;u<s.length&&e.length<i;u++){let a=s[u]??"",p=new Set(s.slice(u)),l=new Set,d=new Map,S=[],N=(A)=>(t.get(A)??[]).filter((F)=>p.has(F)),J=(A)=>{if(e.length>=i)return!0;let F=!1;S.push(A),l.add(A);for(let c of N(A)){if(e.length>=i)break;if(c===a)Un(r,e,S.concat(a)),F=!0;else if(!l.has(c)){if(J(c))F=!0}}if(F)m(A,l,d);else for(let c of N(A)){let g=d.get(c)??new Set;g.add(A),d.set(c,g)}return S.pop(),F};J(a)}return e}function ai(n,t){let{components:i}=ri(n),e=[],r=new Set;for(let s of i){if(e.length>=t)break;if(s.length===0)continue;if(s.length===1){let a=s[0]??"";if((n.get(a)??[]).includes(a))Un(r,e,[a,a]);continue}let m=t-e.length,u=si(s,n,m);for(let a of u){if(e.length>=t)break;Un(r,e,a)}}return e}import{findInFiles as oi,Lang as ui}from"@ast-grep/napi";async function Vn(n){if(n.filePaths.length===0)return[];let t=[];return await oi(ui.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,e)=>{if(i)return;for(let r of e){let s=r.range();t.push({filePath:r.getRoot().filename(),startLine:s.start.line+1,endLine:s.end.line+1,matchedText:r.text()})}}),t}var gt=30000,xt=60000,ci=10;class Qn{projectRoot;db;symbolRepo;relationRepo;fileRepo;parseCache;coordinator;watcher;releaseWatcherRoleFn;parseSourceFn;extractSymbolsFn;extractRelationsFn;symbolSearchFn;relationSearchFn;patternSearchFn;readFileFn;unlinkFn;existsSyncFn;makeExternalCoordinatorFn;logger;defaultProject;role;timer=null;signalHandlers=[];closed=!1;tsconfigPaths=null;boundaries=[];onIndexedCallbacks=new Set;graphCache=null;graphCacheKey=null;constructor(n){this.projectRoot=n.projectRoot,this.db=n.db,this.symbolRepo=n.symbolRepo,this.relationRepo=n.relationRepo,this.fileRepo=n.fileRepo,this.parseCache=n.parseCache,this.coordinator=n.coordinator,this.watcher=n.watcher,this.releaseWatcherRoleFn=n.releaseWatcherRoleFn,this.parseSourceFn=n.parseSourceFn,this.extractSymbolsFn=n.extractSymbolsFn,this.extractRelationsFn=n.extractRelationsFn,this.symbolSearchFn=n.symbolSearchFn,this.relationSearchFn=n.relationSearchFn,this.patternSearchFn=n.patternSearchFn,this.readFileFn=n.readFileFn,this.unlinkFn=n.unlinkFn,this.existsSyncFn=n.existsSyncFn,this.makeExternalCoordinatorFn=n.makeExternalCoordinatorFn,this.logger=n.logger,this.defaultProject=n.defaultProject,this.role=n.role}static async open(n){let{projectRoot:t,extensions:i=[".ts",".mts",".cts"],ignorePatterns:e=[],parseCacheCapacity:r=500,logger:s=console,existsSyncFn:m=mi,dbConnectionFactory:u,watcherFactory:a,coordinatorFactory:p,repositoryFactory:l,acquireWatcherRoleFn:d=ft,releaseWatcherRoleFn:S=lt,updateHeartbeatFn:N=pt,discoverProjectsFn:J=Sn,parseSourceFn:A=un,extractSymbolsFn:F=ln,extractRelationsFn:c=pn,symbolSearchFn:g=Wn,relationSearchFn:o=Hn,patternSearchFn:f=Vn,loadTsconfigPathsFn:x=cn,makeExternalCoordinatorFn:b,readFileFn:D=async(C)=>Bun.file(C).text(),unlinkFn:$=async(C)=>{await Bun.file(C).unlink()},watchMode:k}=n;if(!Nn.isAbsolute(t))return O(y("validation",`Gildash: projectRoot must be an absolute path, got: "${t}"`));if(!m(t))return O(y("validation",`Gildash: projectRoot does not exist: "${t}"`));let h=u?u():new Cn({projectRoot:t}),M=h.open();if(rn(M))return M;try{let C=await J(t),I=C[0]?.project??Nn.basename(t),L=l?l():(()=>{let B=h;return{fileRepo:new In(B),symbolRepo:new Kn(B),relationRepo:new Rn(B),parseCache:new Dn(r)}})(),sn=k??!0,Z;if(sn)Z=await Promise.resolve(d(h,process.pid,{}));else Z="owner";let dt=null,yt=null,K=new Qn({projectRoot:t,db:h,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,fileRepo:L.fileRepo,parseCache:L.parseCache,coordinator:dt,watcher:yt,releaseWatcherRoleFn:S,parseSourceFn:A,extractSymbolsFn:F,extractRelationsFn:c,symbolSearchFn:g,relationSearchFn:o,patternSearchFn:f,readFileFn:D,unlinkFn:$,existsSyncFn:m,makeExternalCoordinatorFn:b,logger:s,defaultProject:I,role:Z});if(bn(t),K.tsconfigPaths=await x(t),K.boundaries=C,Z==="owner"){let B=p?p():new fn({projectRoot:t,boundaries:C,extensions:i,ignorePatterns:e,dbConnection:h,parseCache:L.parseCache,fileRepo:L.fileRepo,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,logger:s});if(K.coordinator=B,B.onIndexed(()=>K.invalidateGraphCache()),sn){let V=a?a():new wn({projectRoot:t,ignorePatterns:e,extensions:i},void 0,s);K.watcher=V,await V.start((Q)=>B.handleWatcherEvent?.(Q)).then((Q)=>{if(rn(Q))throw Q.data});let j=setInterval(()=>{N(h,process.pid)},gt);K.timer=j}await B.fullIndex()}else{let B=0,V=async()=>{try{let Q=await Promise.resolve(d(h,process.pid,{}));if(B=0,Q==="owner"){clearInterval(K.timer),K.timer=null;let q=null,v=null;try{q=a?a():new wn({projectRoot:t,ignorePatterns:e,extensions:i},void 0,s),v=p?p():new fn({projectRoot:t,boundaries:C,extensions:i,ignorePatterns:e,dbConnection:h,parseCache:L.parseCache,fileRepo:L.fileRepo,symbolRepo:L.symbolRepo,relationRepo:L.relationRepo,logger:s});for(let W of K.onIndexedCallbacks)v.onIndexed(W);v.onIndexed(()=>K.invalidateGraphCache()),await q.start((W)=>v?.handleWatcherEvent?.(W)).then((W)=>{if(rn(W))throw W.data});let hn=setInterval(()=>{N(h,process.pid)},gt);K.timer=hn,K.coordinator=v,K.watcher=q,await v.fullIndex()}catch(hn){if(s.error("[Gildash] owner promotion failed, reverting to reader",hn),q){let W=await q.close();if(rn(W))s.error("[Gildash] watcher close error during promotion rollback",W.data);K.watcher=null}if(v)await v.shutdown().catch((W)=>s.error("[Gildash] coordinator shutdown error during promotion rollback",W)),K.coordinator=null;if(K.timer===null)K.timer=setInterval(V,xt)}}}catch(Q){if(B++,s.error("[Gildash] healthcheck error",Q),B>=ci)s.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(K.timer),K.timer=null,K.close().catch((q)=>s.error("[Gildash] close error during healthcheck shutdown",q))}},j=setInterval(V,xt);K.timer=j}if(sn){let B=["SIGTERM","SIGINT","beforeExit"];for(let V of B){let j=()=>{K.close().catch((Q)=>s.error("[Gildash] close error during signal",V,Q))};if(V==="beforeExit")process.on("beforeExit",j);else process.on(V,j);K.signalHandlers.push([V,j])}}return K}catch(C){return h.close(),O(y("store","Gildash: initialization failed",C))}}async close(n){if(this.closed)return;this.closed=!0;let t=[];for(let[i,e]of this.signalHandlers)if(i==="beforeExit")process.off("beforeExit",e);else process.off(i,e);if(this.signalHandlers=[],this.coordinator)try{await this.coordinator.shutdown()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(this.watcher){let i=await this.watcher.close();if(rn(i))t.push(i.data)}if(this.timer!==null)clearInterval(this.timer),this.timer=null;try{this.releaseWatcherRoleFn(this.db,process.pid)}catch(i){t.push(i instanceof Error?i:Error(String(i)))}try{this.db.close()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(n?.cleanup)for(let i of["","-wal","-shm"])try{await this.unlinkFn(Nn.join(this.projectRoot,X,gn+i))}catch{}if(t.length>0)return O(y("close","Gildash: one or more errors occurred during close()",t))}onIndexed(n){if(this.onIndexedCallbacks.add(n),!this.coordinator)return()=>{this.onIndexedCallbacks.delete(n)};let t=this.coordinator.onIndexed(n);return()=>{this.onIndexedCallbacks.delete(n),t()}}parseSource(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));let e=this.parseSourceFn(n,t,i);if(rn(e))return e;return this.parseCache.set(n,e),e}extractSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));return this.extractSymbolsFn(n)}extractRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));return this.extractRelationsFn(n.program,n.filePath,this.tsconfigPaths??void 0)}invalidateGraphCache(){this.graphCache=null,this.graphCacheKey=null}getOrBuildGraph(n){let t=n??"__cross__";if(this.graphCache&&this.graphCacheKey===t)return this.graphCache;let i=new On({relationRepo:this.relationRepo,project:n??this.defaultProject});return i.build(),this.graphCache=i,this.graphCacheKey=t,i}async reindex(){if(this.closed)return O(y("closed","Gildash: instance is closed"));if(!this.coordinator)return O(y("closed","Gildash: reindex() is not available for readers"));try{let n=await this.coordinator.fullIndex();return this.invalidateGraphCache(),n}catch(n){return O(y("index","Gildash: reindex failed",n))}}get projects(){return[...this.boundaries]}getStats(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolRepo.getStats(n??this.defaultProject)}catch(t){return O(y("store","Gildash: getStats failed",t))}}searchSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolSearchFn({symbolRepo:this.symbolRepo,project:this.defaultProject,query:n})}catch(t){return O(y("search","Gildash: searchSymbols failed",t))}}searchRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:this.defaultProject,query:n})}catch(t){return O(y("search","Gildash: searchRelations failed",t))}}searchAllSymbols(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.symbolSearchFn({symbolRepo:this.symbolRepo,project:void 0,query:n})}catch(t){return O(y("search","Gildash: searchAllSymbols failed",t))}}searchAllRelations(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:void 0,query:n})}catch(t){return O(y("search","Gildash: searchAllRelations failed",t))}}listIndexedFiles(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.fileRepo.getAllFiles(n??this.defaultProject)}catch(t){return O(y("store","Gildash: listIndexedFiles failed",t))}}getInternalRelations(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{srcFilePath:n,dstFilePath:n,limit:1e4}})}catch(i){return O(y("search","Gildash: getInternalRelations failed",i))}}diffSymbols(n,t){let i=new Map(n.map((u)=>[`${u.name}::${u.filePath}`,u])),e=new Map(t.map((u)=>[`${u.name}::${u.filePath}`,u])),r=[],s=[],m=[];for(let[u,a]of e){let p=i.get(u);if(!p)r.push(a);else if(p.fingerprint!==a.fingerprint)m.push({before:p,after:a})}for(let[u,a]of i)if(!e.has(u))s.push(a);return{added:r,removed:s,modified:m}}getDependencies(n,t,i=1e4){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{srcFilePath:n,type:"imports",project:t??this.defaultProject,limit:i}}).map((e)=>e.dstFilePath)}catch(e){return O(y("search","Gildash: getDependencies failed",e))}}getDependents(n,t,i=1e4){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.relationSearchFn({relationRepo:this.relationRepo,project:t??this.defaultProject,query:{dstFilePath:n,type:"imports",project:t??this.defaultProject,limit:i}}).map((e)=>e.srcFilePath)}catch(e){return O(y("search","Gildash: getDependents failed",e))}}async getAffected(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(t).getAffectedByChange(n)}catch(i){return O(y("search","Gildash: getAffected failed",i))}}async hasCycle(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).hasCycle()}catch(t){return O(y("search","Gildash: hasCycle failed",t))}}async getImportGraph(n){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).getAdjacencyList()}catch(t){return O(y("search","Gildash: getImportGraph failed",t))}}async getTransitiveDependencies(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(t).getTransitiveDependencies(n)}catch(i){return O(y("search","Gildash: getTransitiveDependencies failed",i))}}async getCyclePaths(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.getOrBuildGraph(n).getCyclePaths(t)}catch(i){return O(y("search","Gildash: getCyclePaths failed",i))}}getFullSymbol(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=i??this.defaultProject,r=this.symbolSearchFn({symbolRepo:this.symbolRepo,project:e,query:{text:n,exact:!0,filePath:t,limit:1}});if(r.length===0)return O(y("search",`Gildash: symbol '${n}' not found in '${t}'`));let s=r[0],m=s.detail;return{...s,members:Array.isArray(m.members)?m.members:void 0,jsDoc:typeof m.jsDoc==="string"?m.jsDoc:void 0,parameters:typeof m.parameters==="string"?m.parameters:void 0,returnType:typeof m.returnType==="string"?m.returnType:void 0,heritage:Array.isArray(m.heritage)?m.heritage:void 0,decorators:Array.isArray(m.decorators)?m.decorators:void 0,typeParameters:typeof m.typeParameters==="string"?m.typeParameters:void 0}}catch(e){return O(y("search","Gildash: getFullSymbol failed",e))}}getFileStats(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=t??this.defaultProject,e=this.fileRepo.getFile(i,n);if(!e)return O(y("search",`Gildash: file '${n}' is not in the index`));let r=this.symbolRepo.getFileSymbols(i,n),s=this.relationRepo.getOutgoing(i,n);return{filePath:e.filePath,lineCount:e.lineCount??0,size:e.size,symbolCount:r.length,exportedSymbolCount:r.filter((m)=>m.isExported).length,relationCount:s.length}}catch(i){return O(y("store","Gildash: getFileStats failed",i))}}async getFanMetrics(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=this.getOrBuildGraph(t);return{filePath:n,fanIn:i.getDependents(n).length,fanOut:i.getDependencies(n).length}}catch(i){return O(y("search","Gildash: getFanMetrics failed",i))}}resolveSymbol(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));let e=i??this.defaultProject,r=new Set,s=[],m=n,u=t;for(;;){let a=`${u}::${m}`;if(r.has(a))return O(y("search","Gildash: resolveSymbol detected circular re-export chain"));r.add(a);let p=this.relationSearchFn({relationRepo:this.relationRepo,project:e,query:{type:"re-exports",srcFilePath:u,limit:500}}),l,d;for(let S of p){let N;if(S.metaJson)try{let A=JSON.parse(S.metaJson);if(Array.isArray(A.specifiers))N=A.specifiers}catch{}if(!N)continue;let J=N.find((A)=>A.exported===m);if(!J)continue;l=S.dstFilePath,d=J.local;break}if(!l||!d)return{originalName:m,originalFilePath:u,reExportChain:s};s.push({filePath:u,exportedAs:m}),u=l,m=d}}async findPattern(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let i=t?.project??this.defaultProject,e=t?.filePaths?t.filePaths:this.fileRepo.getAllFiles(i).map((r)=>r.filePath);return await this.patternSearchFn({pattern:n,filePaths:e})}catch(i){return O(y("search","Gildash: findPattern failed",i))}}async indexExternalPackages(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));if(this.role!=="owner")return O(y("closed","Gildash: indexExternalPackages() is not available for readers"));try{let i=[];for(let e of n){let r=Nn.resolve(this.projectRoot,"node_modules",e);if(!this.existsSyncFn(r))return O(y("validation",`Gildash: package not found in node_modules: ${e}`));let s=`@external/${e}`,u=await(this.makeExternalCoordinatorFn?this.makeExternalCoordinatorFn(r,s):new fn({projectRoot:r,boundaries:[{dir:".",project:s}],extensions:[".d.ts"],ignorePatterns:[],dbConnection:this.db,parseCache:this.parseCache,fileRepo:this.fileRepo,symbolRepo:this.symbolRepo,relationRepo:this.relationRepo,logger:this.logger})).fullIndex();i.push(u)}return i}catch(i){return O(y("store","Gildash: indexExternalPackages failed",i))}}async batchParse(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));let i=new Map;return await Promise.all(n.map(async(e)=>{try{let r=await this.readFileFn(e),s=this.parseSourceFn(e,r,t);if(!rn(s))i.set(e,s)}catch{}})),i}getModuleInterface(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=this.symbolSearchFn({symbolRepo:this.symbolRepo,project:t??this.defaultProject,query:{filePath:n,isExported:!0}}).map((r)=>({name:r.name,kind:r.kind,parameters:r.detail.parameters??void 0,returnType:r.detail.returnType??void 0,jsDoc:r.detail.jsDoc??void 0}));return{filePath:n,exports:e}}catch(i){return O(y("search","Gildash: getModuleInterface failed",i))}}async getHeritageChain(n,t,i){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{let e=i??this.defaultProject,r=new Set,s=(m,u,a)=>{let p=`${m}::${u}`;if(r.has(p))return{symbolName:m,filePath:u,kind:a,children:[]};r.add(p);let S=this.relationSearchFn({relationRepo:this.relationRepo,project:e,query:{srcFilePath:u,srcSymbolName:m,limit:1000}}).filter((N)=>N.type==="extends"||N.type==="implements").filter((N)=>N.dstSymbolName!=null).map((N)=>s(N.dstSymbolName,N.dstFilePath,N.type));return{symbolName:m,filePath:u,kind:a,children:S}};return s(n,t)}catch(e){return O(y("search","Gildash: getHeritageChain failed",e))}}getParsedAst(n){if(this.closed)return;return this.parseCache.get(n)}getFileInfo(n,t){if(this.closed)return O(y("closed","Gildash: instance is closed"));try{return this.fileRepo.getFile(t??this.defaultProject,n)}catch(i){return O(y("store","Gildash: getFileInfo failed",i))}}getSymbolsByFile(n,t){return this.searchSymbols({filePath:n,project:t??void 0,limit:1e4})}}export{Wn as symbolSearch,Hn as relationSearch,Vn as patternSearch,y as gildashError,Qn as Gildash,On as DependencyGraph};
|
|
2
|
+
var Ht=Object.defineProperty;var Kt=(n)=>n;function Vt(n,u){this[n]=Kt.bind(null,u)}var Bt=(n,u)=>{for(var t in u)Ht(n,t,{get:u[t],enumerable:!0,configurable:!0,set:Vt.bind(u,t)})};var Su=import.meta.require;import{isErr as Nn}from"@zipbul/result";import Mn from"path";import{existsSync as Bi}from"fs";import{err as fu,isErr as Xt}from"@zipbul/result";import{Database as Tt}from"bun:sqlite";import{mkdirSync as Ct,unlinkSync as au,existsSync as su}from"fs";import{dirname as bt,join as Au}from"path";import{drizzle as Rt}from"drizzle-orm/bun-sqlite";import{migrate as yt}from"drizzle-orm/bun-sqlite/migrator";class a extends Error{type;constructor(n,u,t){super(u,t);this.type=n;this.name="GildashError"}}function v(n,u,t){return new a(n,u,t!==void 0?{cause:t}:void 0)}var e=".gildash",Wn="gildash.db";var bn={};Bt(bn,{watcherOwner:()=>Zt,symbols:()=>U,relations:()=>W,files:()=>R});import{sql as Qt}from"drizzle-orm";import{sqliteTable as Dn,text as b,integer as j,real as Ut,index as tn,primaryKey as Lt,foreignKey as Cn,check as Yt}from"drizzle-orm/sqlite-core";var R=Dn("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:Ut("mtime_ms").notNull(),size:j("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:j("line_count")},(n)=>[Lt({columns:[n.project,n.filePath]})]),U=Dn("symbols",{id:j("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:j("start_line").notNull(),startColumn:j("start_column").notNull(),endLine:j("end_line").notNull(),endColumn:j("end_column").notNull(),isExported:j("is_exported").notNull().default(0),signature:b("signature"),fingerprint:b("fingerprint"),detailJson:b("detail_json"),contentHash:b("content_hash").notNull(),indexedAt:b("indexed_at").notNull(),resolvedType:b("resolved_type")},(n)=>[tn("idx_symbols_project_file").on(n.project,n.filePath),tn("idx_symbols_project_kind").on(n.project,n.kind),tn("idx_symbols_project_name").on(n.project,n.name),tn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Cn({columns:[n.project,n.filePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),W=Dn("relations",{id:j("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),type:b("type").notNull(),srcFilePath:b("src_file_path").notNull(),srcSymbolName:b("src_symbol_name"),dstProject:b("dst_project").notNull(),dstFilePath:b("dst_file_path").notNull(),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json")},(n)=>[tn("idx_relations_src").on(n.project,n.srcFilePath),tn("idx_relations_dst").on(n.dstProject,n.dstFilePath),tn("idx_relations_type").on(n.project,n.type),Cn({columns:[n.project,n.srcFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade"),Cn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),Zt=Dn("watcher_owner",{id:j("id").primaryKey(),pid:j("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull()},(n)=>[Yt("watcher_owner_singleton",Qt`${n.id} = 1`)]);class Rn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Au(n.projectRoot,e,Wn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Ct(bt(this.dbPath),{recursive:!0}),this.client=new Tt(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=Rt(this.client,{schema:bn}),yt(this.drizzle,{migrationsFolder:Au(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(t,i)=>{try{return new RegExp(t).test(i)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&su(this.dbPath)){this.closeClient(),au(this.dbPath);for(let t of["-wal","-shm"]){let i=this.dbPath+t;if(su(i))au(i)}let u=this.open();if(Xt(u))return fu(v("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return fu(v("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let t=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${t}"`);try{let i=n(this);return u.run(`RELEASE SAVEPOINT "${t}"`),i}catch(i){throw u.run(`ROLLBACK TO SAVEPOINT "${t}"`),u.run(`RELEASE SAVEPOINT "${t}"`),i}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let t=n();return u.run("COMMIT"),t}catch(t){throw u.run("ROLLBACK"),t}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}replaceOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as an,and as _u}from"drizzle-orm";class yn{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(R).where(_u(an(R.project,n),an(R.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(R).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[R.project,R.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(R).where(an(R.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),t=new Map;for(let i of u)t.set(i.filePath,i);return t}deleteFile(n,u){this.db.drizzleDb.delete(R).where(_u(an(R.project,n),an(R.filePath,u))).run()}}import{eq as y,and as gn,sql as zn,count as pt}from"drizzle-orm";function kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class pn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,t,i){if(this.db.drizzleDb.delete(U).where(gn(y(U.project,n),y(U.filePath,u))).run(),!i.length)return;let g=new Date().toISOString();for(let m of i)this.db.drizzleDb.insert(U).values({project:n,filePath:u,kind:m.kind??"unknown",name:m.name??"",startLine:m.startLine??0,startColumn:m.startColumn??0,endLine:m.endLine??0,endColumn:m.endColumn??0,isExported:m.isExported??0,signature:m.signature??null,fingerprint:m.fingerprint??null,detailJson:m.detailJson??null,contentHash:t,indexedAt:m.indexedAt??g,resolvedType:m.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.filePath,u))).all()}searchByName(n,u,t={}){let i=t.limit??50,g=kn(u);if(!g)return[];return this.db.drizzleDb.select().from(U).where(gn(zn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${g})`,y(U.project,n),t.kind?y(U.kind,t.kind):void 0)).orderBy(U.name).limit(i).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.kind,u))).orderBy(U.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:pt(),fileCount:zn`COUNT(DISTINCT ${U.filePath})`}).from(U).where(y(U.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(U).where(gn(y(U.project,n),y(U.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(U).where(gn(n.ftsQuery?zn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?y(U.name,n.exactName):void 0,n.project!==void 0?y(U.project,n.project):void 0,n.kind?y(U.kind,n.kind):void 0,n.filePath!==void 0?y(U.filePath,n.filePath):void 0,n.isExported!==void 0?y(U.isExported,n.isExported?1:0):void 0,n.decorator?zn`${U.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?y(U.resolvedType,n.resolvedType):void 0)).orderBy(U.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let t=new RegExp(n.regex);return u.filter((i)=>t.test(i.name)).slice(0,n.limit)}catch{return[]}}}import{eq as C,and as x,isNull as Ju,or as Ft}from"drizzle-orm";class Fn{db;constructor(n){this.db=n}replaceFileRelations(n,u,t){this.db.transaction((i)=>{if(i.drizzleDb.delete(W).where(x(C(W.project,n),C(W.srcFilePath,u))).run(),!t.length)return;for(let g of t)i.drizzleDb.insert(W).values({project:n,type:g.type??"unknown",srcFilePath:g.srcFilePath??u,srcSymbolName:g.srcSymbolName??null,dstProject:g.dstProject??n,dstFilePath:g.dstFilePath??"",dstSymbolName:g.dstSymbolName??null,metaJson:g.metaJson??null}).run()})}getOutgoing(n,u,t){if(t!==void 0)return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.srcFilePath,u),Ft(C(W.srcSymbolName,t),Ju(W.srcSymbolName)))).all();return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:t}=n;return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.dstProject,u),C(W.dstFilePath,t))).all()}getByType(n,u){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(W).where(x(C(W.project,n),C(W.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(n.project!==void 0?C(W.project,n.project):void 0,n.srcFilePath!==void 0?C(W.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?C(W.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?C(W.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?C(W.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?C(W.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?C(W.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:t,oldSymbol:i,newFile:g,newSymbol:m,newDstProject:O}=n,r=i===null?x(C(W.dstProject,u),C(W.dstFilePath,t),Ju(W.dstSymbolName)):x(C(W.dstProject,u),C(W.dstFilePath,t),C(W.dstSymbolName,i)),w={dstFilePath:g,dstSymbolName:m};if(O!==void 0)w.dstProject=O;this.db.drizzleDb.update(W).set(w).where(r).run()}}import{err as Nu}from"@zipbul/result";import{subscribe as vt}from"@parcel/watcher";import vn from"path";var Et=["**/.git/**",`**/${e}/**`,"**/dist/**","**/node_modules/**"],qt=new Set(["package.json","tsconfig.json"]);function Gt(n){return n.replaceAll("\\","/")}function jt(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class En{#n;#u;#t;#g;#i;#m;constructor(n,u=vt,t=console){this.#u=n.projectRoot,this.#t=[...Et,...n.ignorePatterns??[]],this.#g=new Set((n.extensions??[".ts",".mts",".cts"]).map((i)=>i.toLowerCase())),this.#i=u,this.#m=t}async start(n){try{this.#n=await this.#i(this.#u,(u,t)=>{if(u){this.#m.error(v("watcher","Callback error",u));return}try{for(let i of t){let g=Gt(vn.relative(this.#u,i.path));if(g.startsWith(".."))continue;let m=vn.basename(g),O=vn.extname(g).toLowerCase();if(!qt.has(m)&&!this.#g.has(O))continue;if(g.endsWith(".d.ts"))continue;n({eventType:jt(i.type),filePath:g})}}catch(i){this.#m.error(v("watcher","Callback error",i))}},{ignore:this.#t})}catch(u){return Nu(v("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Nu(v("watcher","Failed to close watcher",n))}}}import qn from"path";import{promises as Pt}from"fs";var dt=["**/node_modules/**","**/.git/**",`**/${e}/**`,"**/dist/**"];async function In(n){let u=[];for await(let t of Pt.glob("**/package.json",{cwd:n,exclude:dt})){let i=qn.dirname(t).replaceAll("\\","/"),g=qn.join(n,t),m=await Bun.file(g).json(),O=typeof m?.name==="string"&&m.name.length>0?m.name:qn.basename(i==="."?n:i);u.push({dir:i,project:O})}return u.sort((t,i)=>i.dir.length-t.dir.length),u}function q(n,u,t="default"){let i=n.replaceAll("\\","/");for(let g of u){if(g.dir===".")return g.project;if(i===g.dir||i.startsWith(`${g.dir}/`))return g.project}return t}import Mu from"path";var c=new Map;async function ht(n){let u=Bun.file(n);if(!await u.exists())return null;try{let t=await u.text(),i=Bun.JSONC.parse(t);return typeof i==="object"&&i!==null?i:null}catch{return null}}async function sn(n){if(c.has(n))return c.get(n)??null;let u=Mu.join(n,"tsconfig.json"),t=await ht(u);if(!t)return c.set(n,null),null;let i=typeof t.compilerOptions==="object"&&t.compilerOptions!==null?t.compilerOptions:null;if(!i)return c.set(n,null),null;let g=typeof i.baseUrl==="string"?i.baseUrl:null,m=typeof i.paths==="object"&&i.paths!==null?i.paths:null;if(!g&&!m)return c.set(n,null),null;let O=g?Mu.resolve(n,g):n,r=new Map;if(m)for(let[f,s]of Object.entries(m)){if(!Array.isArray(s))continue;let A=s.filter((M)=>typeof M==="string");r.set(f,A)}let w={baseUrl:O,paths:r};return c.set(n,w),w}function Hn(n){if(n){c.delete(n);return}c.clear()}import $u from"path";function Kn(n,u){return $u.relative(n,u).replaceAll("\\","/")}function wn(n,u){return $u.resolve(n,u)}function nn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Qu}from"@zipbul/result";import{err as xt}from"@zipbul/result";import{parseSync as lt}from"oxc-parser";function An(n,u,t,i=lt){try{let{program:g,errors:m,comments:O}=i(n,u,t);return{filePath:n,program:g,errors:m,comments:O,sourceText:u}}catch(g){return xt(v("parse",`Failed to parse file: ${n}`,g))}}import{promises as ot}from"fs";import{join as et}from"path";async function Wu(n){let{projectRoot:u,extensions:t,ignorePatterns:i,fileRepo:g}=n,m=g.getFilesMap(),O=new Set,r=[],w=[],f=i.map((A)=>new Bun.Glob(A));for await(let A of ot.glob("**/*",{cwd:u})){if(!t.some((S)=>A.endsWith(S)))continue;if(A.startsWith("node_modules/")||A.includes("/node_modules/"))continue;if(f.some((S)=>S.match(A)))continue;O.add(A);let M=et(u,A),k=Bun.file(M),{size:I,lastModified:H}=k,B=m.get(A);if(!B){let S=await k.text(),J=nn(S);r.push({filePath:A,contentHash:J,mtimeMs:H,size:I});continue}if(B.mtimeMs===H&&B.size===I){w.push({filePath:A,contentHash:B.contentHash,mtimeMs:H,size:I});continue}let _=await k.text(),N=nn(_);if(N===B.contentHash)w.push({filePath:A,contentHash:N,mtimeMs:H,size:I});else r.push({filePath:A,contentHash:N,mtimeMs:H,size:I})}let s=[];for(let A of m.keys())if(!O.has(A))s.push(A);return{changed:r,unchanged:w,deleted:s}}function Du(n){let u=[0];for(let t=0;t<n.length;t++)if(n[t]===`
|
|
3
|
+
`)u.push(t+1);return u}function Gn(n,u){let t=0,i=n.length-1;while(t<i){let g=t+i+1>>1;if(n[g]<=u)t=g;else i=g-1}return{line:t+1,column:u-n[t]}}import{err as ct}from"@zipbul/result";import{parse as ni}from"comment-parser";function ku(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let i=ni(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(i.description??"").trim(),tags:(i.tags??[]).map((g)=>({tag:g.tag??"",name:g.name??"",type:g.type??"",description:g.description??"",optional:g.optional??!1,...g.default!==void 0?{default:g.default}:{}}))}}catch(u){return ct(v("parse","Failed to parse JSDoc comment",u))}}import{isErr as ui}from"@zipbul/result";function Vn(n){let{program:u,sourceText:t,comments:i}=n,g=Du(t);function m(_,N){return{start:Gn(g,_),end:Gn(g,N)}}function O(_){let N=null;for(let S of i){if(S.type!=="Block")continue;if(S.end>_)continue;if(!S.value.startsWith("*"))continue;if(!N||S.end>N.end)N={value:`/*${S.value}*/`,end:S.end}}if(!N)return;for(let S of u.body){let J=S.start??0;if(J===_)continue;if(J>N.end&&J<_)return}return N.value}function r(_){if(!_)return;let N=_.typeAnnotation??_;return t.slice(N.start,N.end)}function w(_){if(!_||_.length===0)return[];return _.map((N)=>{let S=N.expression;if(!S)return{name:"unknown"};if(S.type==="CallExpression"){let J=S.callee?.name??S.callee?.property?.name??"unknown",$=(S.arguments??[]).map((z)=>t.slice(z.start,z.end));return{name:J,arguments:$.length>0?$:void 0}}if(S.type==="Identifier")return{name:S.name??"unknown"};return{name:t.slice(S.start,S.end)}})}function f(_){let N=_.type==="TSParameterProperty"?_.parameter:_;if(N?.type==="RestElement"){let T=`...${N.argument?.name??"unknown"}`,D=N.typeAnnotation,Y=D?r(D):void 0,Q={name:T,isOptional:!1};if(Y)Q.type=Y;return Q}if(N?.type==="AssignmentPattern"){let{left:K,right:T}=N,D=K?.name??"unknown",Y=K?.typeAnnotation,Q=Y?r(Y):void 0,E=t.slice(T.start,T.end),P=w(K?.decorators??[]),d={name:D,isOptional:!0,defaultValue:E};if(Q)d.type=Q;if(P.length>0)d.decorators=P;return d}let S=N?.name??N?.pattern?.name??"unknown",J=!!N?.optional,$=N?.typeAnnotation,z=$?r($):void 0,V=w(N?.decorators??[]),L={name:S,isOptional:J};if(z)L.type=z;if(V.length>0)L.decorators=V;return L}function s(_,N){let S=[];if(N?.async)S.push("async");if(_.static)S.push("static");if(_.abstract)S.push("abstract");if(_.readonly)S.push("readonly");if(_.override)S.push("override");if(_.declare)S.push("declare");if(_.const)S.push("const");let J=_.accessibility;if(J==="private")S.push("private");else if(J==="protected")S.push("protected");else if(J==="public")S.push("public");return S}function A(_){let N=[];if(_.superClass){let J=t.slice(_.superClass.start,_.superClass.end);N.push({kind:"extends",name:J})}let S=_.implements??[];for(let J of S){let $=J.expression??J,z=t.slice($.start,$.end);N.push({kind:"implements",name:z})}return N}function M(_){let N=[];for(let S of _.extends??[]){let J=S.expression??S,$=t.slice(J.start,J.end);N.push({kind:"extends",name:$})}return N}function k(_){let N=[];for(let S of _)if(S.type==="MethodDefinition"){let J=S.key?.name??"unknown",$=S.value,z=S.kind??"method",V=z==="constructor"?"constructor":z==="get"?"getter":z==="set"?"setter":"method",L=s(S,$),K=($?.params??[]).map(f),T=r($?.returnType),D={kind:"method",name:J,span:m(S.start,S.end),isExported:!1,methodKind:V,modifiers:L,parameters:K.length>0?K:void 0,returnType:T};N.push(D)}else if(S.type==="PropertyDefinition"){let J=S.key?.name??"unknown",$=s(S),z={kind:"property",name:J,span:m(S.start,S.end),isExported:!1,modifiers:$};N.push(z)}return N}function I(_){let N=[];for(let S of _)if(S.type==="TSMethodSignature"){let J=S.key?.name??"unknown",$=(S.params??[]).map(f),z=r(S.returnType);N.push({kind:"method",name:J,span:m(S.start,S.end),isExported:!1,modifiers:[],methodKind:"method",parameters:$.length>0?$:void 0,returnType:z})}else if(S.type==="TSPropertySignature"){let J=S.key?.name??"unknown",$=r(S.typeAnnotation),z={kind:"property",name:J,span:m(S.start,S.end),isExported:!1,modifiers:S.readonly?["readonly"]:[],returnType:$};N.push(z)}return N}function H(_,N){let S=_.type??"";if(S==="FunctionDeclaration"){let J=_.id?.name??"default",$=(_.params??[]).map(f),z=r(_.returnType),V=s(_,_),L=w(_.decorators??[]),K=_.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,T={kind:"function",name:J,span:m(_.start,_.end),isExported:N,modifiers:V,parameters:$.length>0?$:void 0,returnType:z,decorators:L.length>0?L:void 0};if(K&&K.length>0)T.typeParameters=K;return T}if(S==="ClassDeclaration"||S==="ClassExpression"){let J=_.id?.name??"default",$=A(_),z=k(_.body?.body??[]),V=w(_.decorators??[]),L=s(_,_),K=_.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,T={kind:"class",name:J,span:m(_.start,_.end),isExported:N,modifiers:L,heritage:$.length>0?$:void 0,members:z.length>0?z:void 0,decorators:V.length>0?V:void 0};if(K&&K.length>0)T.typeParameters=K;return T}if(S==="VariableDeclaration"){let J=[];for(let $ of _.declarations??[]){let{id:z,init:V}=$;if(z?.type==="ObjectPattern"){for(let Q of z.properties??[]){let E=Q.value?.name??Q.key?.name??"unknown";J.push({kind:"variable",name:E,span:m(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}if(z?.type==="ArrayPattern"){for(let Q of z.elements??[]){if(!Q||Q.type!=="Identifier")continue;let E=Q.name??"unknown";J.push({kind:"variable",name:E,span:m(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}let L=z?.name??"unknown",K="variable",T,D;if(V?.type==="FunctionExpression"||V?.type==="ArrowFunctionExpression")K="function",T=(V.params??[]).map(f),D=r(V.returnType);let Y=[];J.push({kind:K,name:L,span:m($.start,$.end),isExported:N,modifiers:Y,parameters:T,returnType:D})}if(J.length===0)return null;if(J.length===1)return J[0];return J}if(S==="TSTypeAliasDeclaration")return{kind:"type",name:_.id?.name??"unknown",span:m(_.start,_.end),isExported:N,modifiers:[]};if(S==="TSInterfaceDeclaration"){let J=_.id?.name??"unknown",$=M(_),z=I(_.body?.body??[]),V=_.typeParameters?.params?.map((K)=>K.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:J,span:m(_.start,_.end),isExported:N,modifiers:[],heritage:$.length>0?$:void 0,members:z.length>0?z:void 0};if(V&&V.length>0)L.typeParameters=V;return L}if(S==="TSEnumDeclaration"){let J=_.id?.name??"unknown",$=s(_),V=(_.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:m(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:J,span:m(_.start,_.end),isExported:N,modifiers:$,members:V.length>0?V:void 0}}return null}let B=[];for(let _ of u.body){let N=null,S=_,J=typeof S.type==="string"?S.type:"";if(J==="ExportNamedDeclaration"){let z=_;if(z.declaration){if(N=H(z.declaration,!0),N&&!Array.isArray(N))N.span=m(z.start,z.end);else if(Array.isArray(N))for(let V of N)V.span=m(z.start,z.end)}}else if(J==="ExportDefaultDeclaration"){let z=_,V=z.declaration;if(V){if(N=H(V,!0),N&&!Array.isArray(N))N.name=V.id?.name??"default",N.isExported=!0,N.span=m(z.start,z.end)}}else N=H(_,!1);let $=Array.isArray(N)?N:N?[N]:[];for(let z of $){let V=_.start??0,L=O(V);if(L){let K=ku(L);if(!ui(K))z.jsDoc=K}B.push(z)}}return B}function ti(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,t=n.modifiers.includes("async")?1:0;return`params:${u}|async:${t}`}return null}function ii(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((t)=>{let i=t.modifiers.find((g)=>g==="private"||g==="protected"||g==="public");return{name:t.name,kind:t.methodKind??t.kind,type:t.returnType,visibility:i,isStatic:t.modifiers.includes("static")||void 0,isReadonly:t.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function zu(n,u,t,i,g){let m=ti(n),O=nn(`${u}|${n.kind}|${m??""}`);return{project:t,filePath:i,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:m,fingerprint:O,detailJson:ii(n),contentHash:g,indexedAt:new Date().toISOString()}}function jn(n){let{parsed:u,project:t,filePath:i,contentHash:g,symbolRepo:m}=n,O=Vn(u),r=[];for(let w of O){r.push(zu(w,w.name,t,i,g));for(let f of w.members??[])r.push(zu(f,`${w.name}.${f.name}`,t,i,g))}m.replaceFileSymbols(t,i,g,r)}import{resolve as Pn,dirname as gi,extname as mi}from"path";function mn(n,u,t){let i=(g)=>{let m=mi(g);if(m==="")return[g+".ts",g+".d.ts",g+"/index.ts",g+"/index.d.ts",g+".mts",g+"/index.mts",g+".cts",g+"/index.cts"];if(m===".js")return[g.slice(0,-3)+".ts"];if(m===".mjs")return[g.slice(0,-4)+".mts"];if(m===".cjs")return[g.slice(0,-4)+".cts"];return[g]};if(u.startsWith(".")){let g=Pn(gi(n),u);return i(g)}if(t)for(let[g,m]of t.paths){if(m.length===0)continue;let O=g.indexOf("*");if(O===-1){if(u===g){let r=[];for(let w of m)r.push(...i(Pn(t.baseUrl,w)));return r}}else{let r=g.slice(0,O),w=g.slice(O+1);if(u.startsWith(r)&&(w===""||u.endsWith(w))){let f=u.slice(r.length,w===""?void 0:u.length-w.length),s=[];for(let A of m)s.push(...i(Pn(t.baseUrl,A.replace("*",f))));return s}}}return[]}function Iu(n,u,t,i=mn){let g=new Map,m=n.body??[];for(let O of m){if(O.type!=="ImportDeclaration")continue;let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.specifiers??[];for(let A of s)switch(A.type){case"ImportSpecifier":g.set(A.local.name,{path:f,importedName:A.imported.name});break;case"ImportDefaultSpecifier":g.set(A.local.name,{path:f,importedName:"default"});break;case"ImportNamespaceSpecifier":g.set(A.local.name,{path:f,importedName:"*"});break}}return g}var ri=new Set(["loc","start","end","scope"]);function On(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let i of n)On(i,u);return}let t=n;u(t);for(let i of Object.keys(t)){if(ri.has(i))continue;let g=t[i];if(g&&typeof g==="object")On(g,u)}}function Hu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function rn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let t=u.name;return{root:t,parts:[],full:t}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let t=[],i=u;while(i.type==="MemberExpression"){let O=i.property;if(!O||typeof O.name!=="string")return null;t.unshift(O.name),i=i.object}let g;if(i.type==="Identifier")g=i.name;else if(i.type==="ThisExpression")g="this";else if(i.type==="Super")g="super";else return null;let m=[g,...t].join(".");return{root:g,parts:t,full:m}}return null}function Ku(n,u,t,i=mn){let g=[],m=n.body??[];for(let O of m){if(O.type==="ImportDeclaration"){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.importKind==="type",A=O.specifiers??[];if(A.length===0){let M={};if(s)M.isType=!0;g.push({type:s?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of A){let k=M.type,I=s||M.importKind==="type",H={};if(I)H.isType=!0;let B,_;if(k==="ImportDefaultSpecifier")B="default",_=M.local.name;else if(k==="ImportNamespaceSpecifier")B="*",_=M.local.name,H.importKind="namespace";else B=M.imported.name,_=M.local.name;g.push({type:I?"type-references":"imports",srcFilePath:u,srcSymbolName:_,dstFilePath:f,dstSymbolName:B,...Object.keys(H).length>0?{metaJson:JSON.stringify(H)}:{}})}continue}if(O.type==="ExportAllDeclaration"&&O.source){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.exportKind==="type",A={isReExport:!0};if(s)A.isType=!0;g.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify(A)});continue}if(O.type==="ExportNamedDeclaration"&&O.source){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.exportKind==="type",k={isReExport:!0,specifiers:(O.specifiers??[]).map((I)=>({local:I.local.name,exported:I.exported.name}))};if(s)k.isType=!0;g.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify(k)})}}return On(n,(O)=>{if(O.type!=="ImportExpression")return;let r=Hu(O.source);if(!r)return;let w=i(u,r,t);if(w.length===0)return;let f=w[0];g.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),g}function Vu(n,u,t){let i=[],g=[],m=[];function O(){if(g.length>0)return g[g.length-1]??null;return null}function r(f){if(!f)return null;let s=t.get(f.root);if(f.parts.length===0){if(s)return{dstFilePath:s.path,dstSymbolName:s.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:f.root,resolution:"local"}}else{if(s&&s.importedName==="*"){let A=f.parts[f.parts.length-1];return{dstFilePath:s.path,dstSymbolName:A,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:f.full,resolution:"local-member"}}}function w(f){if(!f||typeof f!=="object")return;if(Array.isArray(f)){for(let M of f)w(M);return}let s=f,A=typeof s.type==="string"?s.type:"";if(A==="ClassDeclaration"||A==="ClassExpression"){let M=s,k=M.id?.name??"AnonymousClass";m.push(k),w(M.body),m.pop();return}if(A==="FunctionDeclaration"){let M=s,k=M.id?.name??"anonymous";g.push(k),w(M.body),g.pop();return}if(A==="VariableDeclarator"&&s.init&&(s.init?.type==="FunctionExpression"||s.init?.type==="ArrowFunctionExpression")){let M=s,k=M.id?.name??"anonymous";g.push(k),w(M.init?.body??M.init),g.pop();return}if(A==="MethodDefinition"&&s.value){let M=s,k=m[m.length-1]??"",I=M.key?.name??"anonymous",H=k?`${k}.${I}`:I;g.push(H),w(M.value?.body),g.pop();return}if(A==="FunctionExpression"||A==="ArrowFunctionExpression"){let M=O(),k=M?`${M}.<anonymous>`:"<anonymous>";g.push(k),w(s.body),g.pop();return}if(A==="CallExpression"){let M=s,k=rn(M.callee),I=r(k);if(I){let H=O(),B={};if(H===null)B.scope="module";i.push({type:"calls",srcFilePath:u,srcSymbolName:H,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}w(M.callee);for(let H of M.arguments??[])w(H);return}if(A==="NewExpression"){let M=s,k=rn(M.callee),I=r(k);if(I){let H=O(),B={isNew:!0};if(H===null)B.scope="module";i.push({type:"calls",srcFilePath:u,srcSymbolName:H,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(B)})}for(let H of M.arguments??[])w(H);return}for(let M of Object.keys(s)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let k=s[M];if(k&&typeof k==="object")w(k)}}return w(n),i}function Bu(n,u,t){let i=[];return On(n,(g)=>{if(g.type==="TSInterfaceDeclaration"){let r=g.id?.name??"AnonymousInterface",w=g.extends??[];for(let f of w){let s=f.expression??f,A=rn(s);if(!A)continue;let M=dn(A,u,t);i.push({type:"extends",srcFilePath:u,srcSymbolName:r,...M})}return}if(g.type!=="ClassDeclaration"&&g.type!=="ClassExpression")return;let m=g.id?.name??"AnonymousClass";if(g.superClass){let r=rn(g.superClass);if(r){let w=dn(r,u,t);i.push({type:"extends",srcFilePath:u,srcSymbolName:m,...w})}}let O=g.implements??[];for(let r of O){let w=r.expression??r,f=rn(w);if(!f)continue;let s=dn(f,u,t);i.push({type:"implements",srcFilePath:u,srcSymbolName:m,...s})}}),i}function dn(n,u,t){let i=t.get(n.root);if(i){if(i.importedName==="*"){let g=n.parts[n.parts.length-1]??n.root;return{dstFilePath:i.path,dstSymbolName:g,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:i.path,dstSymbolName:n.parts.length>0?n.full:i.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Bn(n,u,t,i=mn){let g=Iu(n,u,t,i),m=Ku(n,u,t,i),O=Vu(n,u,g),r=Bu(n,u,g);return[...m,...O,...r]}function hn(n){let{ast:u,project:t,filePath:i,relationRepo:g,projectRoot:m,tsconfigPaths:O,knownFiles:r,boundaries:w}=n,f=wn(m,i),A=Bn(u,f,O,r?(k,I,H)=>{let B=mn(k,I,H);for(let _ of B){let N=Kn(m,_);if(w){let S=q(N,w);if(r.has(`${S}::${N}`))return[_]}else if(r.has(`${t}::${N}`))return[_]}return[]}:void 0),M=[];for(let k of A){let I=Kn(m,k.dstFilePath);if(I.startsWith(".."))continue;let H=Kn(m,k.srcFilePath),B=w?q(I,w):t;M.push({project:t,type:k.type,srcFilePath:H,srcSymbolName:k.srcSymbolName??null,dstProject:B,dstFilePath:I,dstSymbolName:k.dstSymbolName??null,metaJson:k.metaJson??null})}return g.replaceFileRelations(t,i,M),M.length}var wi=100;class xn{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=sn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Hn(this.opts.projectRoot),this.tsconfigPathsRaw=sn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??In;this.boundariesRefresh=u(this.opts.projectRoot).then((t)=>{this.opts.boundaries=t})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},wi)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((i,g)=>{this.pendingFullIndexWaiters.push({resolve:i,reject:g})});return this.currentIndexing}this.indexingLock=!0;let t=this.doIndex(n,u).then((i)=>{return this.fireCallbacks(i),i}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let i=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((g)=>{for(let m of i)m.resolve(g)}).catch((g)=>{for(let m of i)m.reject(g)})}else if(this.pendingEvents.length>0){let i=this.pendingEvents.splice(0);this.startIndex(i,!1).catch((g)=>this.logger.error("[IndexCoordinator] incremental drain error",g))}});return this.currentIndexing=t,t}async doIndex(n,u){let t=Date.now(),{fileRepo:i,symbolRepo:g,relationRepo:m,dbConnection:O}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let r,w;if(n!==void 0)r=n.filter((S)=>S.eventType==="create"||S.eventType==="change").map((S)=>({filePath:S.filePath,contentHash:"",mtimeMs:0,size:0})),w=n.filter((S)=>S.eventType==="delete").map((S)=>S.filePath);else{let S=new Map;for(let $ of this.opts.boundaries)for(let[z,V]of i.getFilesMap($.project))S.set(z,V);let J=await Wu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>S}});r=J.changed,w=J.deleted}let f=await this.tsconfigPathsRaw??void 0,s=new Map;for(let S of w){let J=q(S,this.opts.boundaries),$=g.getFileSymbols(J,S);s.set(S,$)}let A=new Map,M=new Map;if(u)for(let S of this.opts.boundaries)for(let J of i.getAllFiles(S.project))for(let $ of g.getFileSymbols(S.project,J.filePath))A.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint});else{for(let S of r){let J=q(S.filePath,this.opts.boundaries);for(let $ of g.getFileSymbols(J,S.filePath))A.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}for(let[,S]of s)for(let J of S)A.set(`${J.filePath}::${J.name}`,{name:J.name,filePath:J.filePath,kind:J.kind,fingerprint:J.fingerprint})}let k=()=>{for(let S of w){let J=q(S,this.opts.boundaries);g.deleteFileSymbols(J,S),m.deleteFileRelations(J,S),i.deleteFile(J,S)}},I=async()=>{let{projectRoot:S,boundaries:J}=this.opts,{parseCache:$}=this.opts,z=0,V=0,L=[],K=[];for(let D of r)try{let Y=wn(S,D.filePath),Q=Bun.file(Y),E=await Q.text(),P=D.contentHash||nn(E),d=q(D.filePath,J);i.upsertFile({project:d,filePath:D.filePath,mtimeMs:Q.lastModified,size:Q.size,contentHash:P,updatedAt:new Date().toISOString(),lineCount:E.split(`
|
|
4
|
+
`).length});let Z=(this.opts.parseSourceFn??An)(Y,E);if(Qu(Z))throw Z.data;let G=Z;K.push({filePath:D.filePath,text:E,contentHash:P,parsed:G,project:d})}catch(Y){this.logger.error(`[IndexCoordinator] Failed to prepare ${D.filePath}:`,Y),L.push(D.filePath)}let T=new Set;for(let D of J)for(let[Y]of i.getFilesMap(D.project))T.add(`${D.project}::${Y}`);return O.transaction(()=>{for(let D of K)jn({parsed:D.parsed,project:D.project,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:g}),V+=hn({ast:D.parsed.program,project:D.project,filePath:D.filePath,relationRepo:m,projectRoot:S,tsconfigPaths:f,knownFiles:T,boundaries:J}),$.set(D.filePath,D.parsed),z+=g.getFileSymbols(D.project,D.filePath).length}),{symbols:z,relations:V,failedFiles:L}},H=0,B=0,_=[];if(u){let{projectRoot:S,boundaries:J}=this.opts,{parseCache:$}=this.opts,z=await Promise.allSettled(r.map(async(K)=>{let T=wn(S,K.filePath),D=Bun.file(T),Y=await D.text(),Q=K.contentHash||nn(Y);return{filePath:K.filePath,text:Y,contentHash:Q,mtimeMs:D.lastModified,size:D.size}})),V=z.filter((K)=>K.status==="fulfilled").map((K)=>K.value);for(let K of z)if(K.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",K.reason);let L=[];O.transaction(()=>{for(let D of V){let Y=q(D.filePath,J);i.deleteFile(Y,D.filePath)}for(let D of w){let Y=q(D,J);g.deleteFileSymbols(Y,D),m.deleteFileRelations(Y,D),i.deleteFile(Y,D)}for(let D of V){let Y=q(D.filePath,J);i.upsertFile({project:Y,filePath:D.filePath,mtimeMs:D.mtimeMs,size:D.size,contentHash:D.contentHash,updatedAt:new Date().toISOString(),lineCount:D.text.split(`
|
|
5
|
+
`).length})}let K=new Set;for(let D of J)for(let[Y]of i.getFilesMap(D.project))K.add(`${D.project}::${Y}`);let T=this.opts.parseSourceFn??An;for(let D of V){let Y=q(D.filePath,J),Q=T(wn(S,D.filePath),D.text);if(Qu(Q))throw Q.data;let E=Q;L.push({filePath:D.filePath,parsed:E}),jn({parsed:E,project:Y,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:g}),B+=hn({ast:E.program,project:Y,filePath:D.filePath,relationRepo:m,projectRoot:S,tsconfigPaths:f,knownFiles:K,boundaries:J}),H+=g.getFileSymbols(Y,D.filePath).length}});for(let K of L)$.set(K.filePath,K.parsed)}else{k();let S=await I();H=S.symbols,B=S.relations,_=S.failedFiles}for(let S of r){let J=q(S.filePath,this.opts.boundaries);for(let $ of g.getFileSymbols(J,S.filePath))M.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}let N={added:[],modified:[],removed:[]};for(let[S,J]of M){let $=A.get(S);if(!$)N.added.push({name:J.name,filePath:J.filePath,kind:J.kind});else if($.fingerprint!==J.fingerprint)N.modified.push({name:J.name,filePath:J.filePath,kind:J.kind})}for(let[S,J]of A)if(!M.has(S))N.removed.push({name:J.name,filePath:J.filePath,kind:J.kind});if(!u)for(let[S,J]of s)for(let $ of J){if(!$.fingerprint)continue;let z=q(S,this.opts.boundaries),V=g.getByFingerprint(z,$.fingerprint);if(V.length===1){let L=V[0];m.retargetRelations({dstProject:z,oldFile:S,oldSymbol:$.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:r.length,removedFiles:w.length,totalSymbols:H,totalRelations:B,durationMs:Date.now()-t,changedFiles:r.map((S)=>S.filePath),deletedFiles:[...w],failedFiles:_,changedSymbols:N}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(t){this.logger.error("[IndexCoordinator] onIndexed callback threw:",t)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function Oi(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Si(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Uu(n,u,t={}){let i=t.now??Date.now,g=t.isAlive??Oi,m=t.staleAfterSeconds??90;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u),"owner";let r=Math.floor((i()-Si(O.heartbeat_at))/1000);if(g(O.pid)&&r<m)return"reader";return n.replaceOwner(u),"owner"})}function Lu(n,u){n.deleteOwner(u)}function Yu(n,u){n.touchOwner(u)}class _n{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let t=this.#u.keys().next().value;if(t!==void 0)this.#u.delete(t)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class ln{lru;constructor(n=500){this.lru=new _n(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function on(n){let{symbolRepo:u,project:t,query:i}=n,g=i.project??t,m=i.limit??100,O={kind:i.kind,filePath:i.filePath,isExported:i.isExported,project:g,limit:m,resolvedType:i.resolvedType};if(i.text)if(i.exact)O.exactName=i.text;else{let w=kn(i.text);if(w)O.ftsQuery=w}if(i.decorator)O.decorator=i.decorator;if(i.regex)O.regex=i.regex;return u.searchByQuery(O).map((w)=>({id:w.id,filePath:w.filePath,kind:w.kind,name:w.name,span:{start:{line:w.startLine,column:w.startColumn},end:{line:w.endLine,column:w.endColumn}},isExported:w.isExported===1,signature:w.signature,fingerprint:w.fingerprint,detail:w.detailJson?(()=>{try{return JSON.parse(w.detailJson)}catch{return{}}})():{}}))}function en(n){let{relationRepo:u,project:t,query:i}=n,g=i.project??t,m=i.limit??500;return u.searchRelations({srcFilePath:i.srcFilePath,srcSymbolName:i.srcSymbolName,dstFilePath:i.dstFilePath,dstSymbolName:i.dstSymbolName,dstProject:i.dstProject,type:i.type,project:g,limit:m}).map((r)=>{let w;if(r.metaJson)try{w=JSON.parse(r.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",r.metaJson)}return{type:r.type,srcFilePath:r.srcFilePath,srcSymbolName:r.srcSymbolName,dstFilePath:r.dstFilePath,dstSymbolName:r.dstSymbolName,dstProject:r.dstProject,metaJson:r.metaJson??void 0,meta:w}})}import{findInFiles as fi,Lang as ai}from"@ast-grep/napi";async function cn(n){if(n.filePaths.length===0)return[];let u=[];return await fi(ai.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(t,i)=>{if(t)return;for(let g of i){let m=g.range();u.push({filePath:g.getRoot().filename(),startLine:m.start.line+1,endLine:m.end.line+1,matchedText:g.text()})}}),u}import p from"typescript";import{isErr as Ki}from"@zipbul/result";import l from"typescript";import si from"path";import{err as nu}from"@zipbul/result";function Ai(n){try{return Su("fs").readFileSync(n,"utf-8")}catch{return}}function _i(n){try{return Su("fs").readFileSync(n,"utf-8")}catch{return}}class Qn{#n;#u;#t=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let t=u.readConfigFile??Ai,i=u.resolveNonTrackedFile??_i,g=si.dirname(n),m=t(n);if(m===void 0)return nu(v("semantic",`tsconfig not found: ${n}`));let O=l.parseJsonText(n,m),r=O.parseDiagnostics;if(r&&r.length>0){let A=r.map((M)=>l.flattenDiagnosticMessageText(M.messageText,`
|
|
6
|
+
`)).join("; ");return nu(v("semantic",`tsconfig parse error: ${A}`))}let w=l.parseJsonSourceFileConfigFileContent(O,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(A)=>t(A)!==void 0||i(A)!==void 0,readFile:(A)=>t(A)??i(A)},g);if(w.errors.length>0){let A=w.errors.filter((M)=>M.category===l.DiagnosticCategory.Error&&M.code!==18003);if(A.length>0){let M=A.map((k)=>l.flattenDiagnosticMessageText(k.messageText,`
|
|
7
|
+
`)).join("; ");return nu(v("semantic",`tsconfig compile error: ${M}`))}}let f=new Zu(w.fileNames,w.options,g,i),s=l.createLanguageService(f);return new Qn(s,f)}get isDisposed(){return this.#t}getProgram(){this.#g();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#g(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#g(),this.#n}notifyFileChanged(n,u){if(this.#t)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#t)return;this.#u.removeFile(n)}dispose(){if(this.#t)return;this.#t=!0,this.#n.dispose()}#g(){if(this.#t)throw Error("TscProgram is disposed")}}class Zu{#n;#u;#t;#g;#i=new Map;constructor(n,u,t,i){this.#n=[...n],this.#u=u,this.#t=t,this.#g=i}updateFile(n,u){let t=this.#i.get(n);if(t)t.version+=1,t.content=u;else this.#i.set(n,{version:1,content:u})}removeFile(n){this.#i.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#i.keys()];return[...this.#n.filter((t)=>!this.#i.has(t)),...n]}getScriptVersion(n){let u=this.#i.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#i.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let t=this.#g(n);if(t!==void 0)return l.ScriptSnapshot.fromString(t);return}getCurrentDirectory(){return this.#t}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#i.has(n))return!0;return this.#g(n)!==void 0}readFile(n){let u=this.#i.get(n);if(u)return u.content;return this.#g(n)}}import F from"typescript";import Ji from"typescript";function o(n,u){if(u<0||u>=n.getEnd())return;function t(i){let g=i.getStart(n,!1),m=i.getEnd();if(u<g||u>=m)return;let O;return Ji.forEachChild(i,(r)=>{if(!O)O=t(r)}),O??i}return t(n)}function Ni(n){return!!(n.flags&F.TypeFlags.Object)&&!!(n.objectFlags&F.ObjectFlags.Reference)}function Jn(n,u,t=0){let i=n.typeToString(u),g=u.flags,m=!!(g&F.TypeFlags.Union),O=!!(g&F.TypeFlags.Intersection),r;if(t<8&&Ni(u)){let A=n.getTypeArguments(u);if(A.length>0)r=A}let w=!!(g&F.TypeFlags.TypeParameter)||r!==void 0&&r.length>0,f;if(m&&t<8)f=u.types.map((A)=>Jn(n,A,t+1));else if(O&&t<8)f=u.types.map((A)=>Jn(n,A,t+1));let s;if(r&&r.length>0)s=r.map((A)=>Jn(n,A,t+1));return{text:i,flags:g,isUnion:m,isIntersection:O,isGeneric:w,members:f,typeArguments:s}}function Mi(n){return F.isFunctionDeclaration(n)||F.isVariableDeclaration(n)||F.isClassDeclaration(n)||F.isInterfaceDeclaration(n)||F.isTypeAliasDeclaration(n)||F.isEnumDeclaration(n)||F.isMethodDeclaration(n)||F.isPropertyDeclaration(n)||F.isPropertySignature(n)||F.isMethodSignature(n)}class uu{program;constructor(n){this.program=n}collectAt(n,u){let t=this.program.getProgram(),i=this.program.getChecker();if(u<0)return null;let g=t.getSourceFile(n);if(!g)return null;if(u>=g.getEnd())return null;let m=o(g,u);if(!m)return null;if(!F.isIdentifier(m))return null;try{let O=i.getTypeAtLocation(m);return Jn(i,O)}catch{return null}}collectFile(n){let u=new Map,t=this.program.getProgram(),i=this.program.getChecker(),g=t.getSourceFile(n);if(!g)return u;function m(O){if(Mi(O)&&O.name&&F.isIdentifier(O.name)){let r=O.name;try{let w=i.getTypeAtLocation(r),f=r.getStart(g);u.set(f,Jn(i,w))}catch{}}F.forEachChild(O,m)}return m(g),u}}import un from"typescript";var $i=1000,Wi=1;function Di(n){let u=n.declarations?.[0],t=u?.getSourceFile(),i=u?un.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:t?.fileName??"",position:i?.getStart(t,!1)??u?.getStart(t,!1)??0}}function Un(n,u=0){let t=n.declarations?.[0],i=t?.getSourceFile(),g=t?un.getNameOfDeclaration(t):void 0,m=i?.fileName??"",O=g?.getStart(i,!1)??t?.getStart(i,!1)??0,r={name:n.getName(),filePath:m,position:O},w=n;if(w.parent)r.parent=Di(w.parent);if(u<Wi){let f=n.flags,s=!!(f&un.SymbolFlags.Enum),A=!!(f&(un.SymbolFlags.NamespaceModule|un.SymbolFlags.ValueModule)),M=!!(f&(un.SymbolFlags.Class|un.SymbolFlags.Interface));if(s&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((I)=>{k.push(Un(I,u+1))}),r.members=k}else if(M&&n.members&&n.members.size>0){let k=[];n.members.forEach((I)=>{k.push(Un(I,u+1))}),r.members=k}if(A&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((I)=>{k.push(Un(I,u+1))}),r.exports=k}}return r}class tu{#n;#u;#t=new Map;constructor(n,u=$i){this.#n=n,this.#u=new _n(u)}get(n,u){if(this.#n.isDisposed)return null;let t=`${n}:${u}`,i=this.#u.get(t);if(i!==void 0)return i;let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let O=o(m,u);if(!O||!un.isIdentifier(O))return null;let w=this.#n.getChecker().getSymbolAtLocation(O);if(!w)return null;let f=Un(w);this.#u.set(t,f);let s=this.#t.get(n);if(!s)s=new Set,this.#t.set(n,s);return s.add(t),f}invalidate(n){let u=this.#t.get(n);if(u){for(let t of u)this.#u.delete(t);this.#t.delete(n)}}clear(){this.#u.clear(),this.#t.clear()}}import ki from"typescript";class iu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let t=this.#n.getProgram(),i=t.getSourceFile(n);if(!i)return[];let g=o(i,u);if(!g||!ki.isIdentifier(g))return[];let O=this.#n.getLanguageService().findReferences(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O)for(let f of w.references){let s=t.getSourceFile(f.fileName);if(!s)continue;let{line:A,character:M}=s.getLineAndCharacterOfPosition(f.textSpan.start);r.push({filePath:f.fileName,position:f.textSpan.start,line:A+1,column:M,isDefinition:f.isDefinition??!1,isWrite:f.isWriteAccess??!1})}return r}}import X from"typescript";function zi(n,u){let t=o(n,u);if(!t)return;if(Xu(t))return t;let i=t.parent;for(let g=0;g<5&&i;g++){if(Xu(i))return i;i=i.parent}return t}function Xu(n){return X.isClassDeclaration(n)||X.isClassExpression(n)||X.isFunctionDeclaration(n)||X.isFunctionExpression(n)||X.isArrowFunction(n)||X.isVariableDeclaration(n)||X.isObjectLiteralExpression(n)}function Tu(n){if(X.isClassDeclaration(n)||X.isClassExpression(n))return"class";if(X.isFunctionDeclaration(n)||X.isFunctionExpression(n)||X.isArrowFunction(n))return"function";if(X.isObjectLiteralExpression(n))return"object";if(X.isVariableDeclaration(n)&&n.initializer)return Tu(n.initializer);return"class"}function Ii(n,u){if(X.isClassDeclaration(n)||X.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(X.isClassExpression(n))return n.name?.getText(u)??"";if(X.isVariableDeclaration(n)&&X.isIdentifier(n.name))return n.name.getText(u);if(X.isFunctionExpression(n))return n.name?.getText(u)??"";if(X.isArrowFunction(n)&&n.parent&&X.isVariableDeclaration(n.parent)){if(X.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(X.isObjectLiteralExpression(n)&&n.parent&&X.isVariableDeclaration(n.parent)){if(X.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Hi(n){if(!X.isClassDeclaration(n)&&!X.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((t)=>t.token===X.SyntaxKind.ImplementsKeyword)}class gu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let t=this.#n.getProgram(),i=t.getSourceFile(n);if(!i)return[];let g=o(i,u);if(!g||!X.isIdentifier(g))return[];let O=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O){if(w.kind===X.ScriptElementKind.interfaceElement||w.kind===X.ScriptElementKind.typeElement)continue;let f=t.getSourceFile(w.fileName);if(!f)continue;let s=zi(f,w.textSpan.start);if(!s)continue;let A=Tu(s),M=Ii(s,f),k=Hi(s);r.push({filePath:w.fileName,symbolName:M,position:w.textSpan.start,kind:A,isExplicit:k})}return r}}function Cu(n){return p.canHaveModifiers(n)&&p.getModifiers(n)?.some((u)=>u.kind===p.SyntaxKind.ExportKeyword)===!0}function Vi(n){if(p.isFunctionDeclaration(n))return"function";if(p.isClassDeclaration(n))return"class";if(p.isInterfaceDeclaration(n))return"interface";if(p.isTypeAliasDeclaration(n))return"type";if(p.isEnumDeclaration(n))return"enum";if(p.isVariableDeclaration(n))return"const";if(p.isVariableStatement(n))return"const";return"unknown"}function bu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Ln{#n;#u;#t;#g;#i;#m=!1;constructor(n,u,t,i,g){this.#n=n,this.#u=u,this.#t=t,this.#g=i,this.#i=g}static create(n,u={}){let t=Qn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(Ki(t))return t;let i=t,g=u.typeCollector??new uu(i),m=u.symbolGraph??new tu(i),O=u.referenceResolver??new iu(i),r=u.implementationFinder??new gu(i);return new Ln(i,g,m,O,r)}get isDisposed(){return this.#m}collectTypeAt(n,u){return this.#r(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#r(),this.#u.collectFile(n)}findReferences(n,u){return this.#r(),this.#g.findAt(n,u)}findImplementations(n,u){return this.#r(),this.#i.findAt(n,u)}getSymbolNode(n,u){return this.#r(),this.#t.get(n,u)}getModuleInterface(n){this.#r();let u=this.#u.collectFile(n),t=[],g=this.#n.getProgram().getSourceFile(n);if(!g)return{filePath:n,exports:t};function m(O){if(p.isVariableStatement(O)&&Cu(O)){for(let r of O.declarationList.declarations)if(p.isIdentifier(r.name)){let w=r.name.getStart(g),f=u.get(w)??null;t.push({name:r.name.text,kind:"const",resolvedType:f})}return}if((p.isFunctionDeclaration(O)||p.isClassDeclaration(O)||p.isInterfaceDeclaration(O)||p.isTypeAliasDeclaration(O)||p.isEnumDeclaration(O))&&Cu(O)&&O.name){let r=O.name,w=r.getStart(g),f=u.get(w)??null;t.push({name:r.text,kind:Vi(O),resolvedType:f});return}p.forEachChild(O,m)}return m(g),{filePath:n,exports:t}}notifyFileChanged(n,u){if(this.#m)return;this.#n.notifyFileChanged(n,u),this.#t.invalidate(n)}notifyFileDeleted(n){if(this.#m)return;this.#n.removeFile(n),this.#t.invalidate(n)}lineColumnToPosition(n,u,t){this.#r();let i=this.#n.getProgram().getSourceFile(n);if(!i)return null;try{return p.getPositionOfLineAndCharacter(i,u-1,t)}catch{return null}}findNamePosition(n,u,t){this.#r();let i=this.#n.getProgram().getSourceFile(n);if(!i)return null;let g=i.getFullText(),m=u;while(m<g.length){let O=g.indexOf(t,m);if(O<0)return null;let r=O>0?g.charCodeAt(O-1):32,w=O+t.length<g.length?g.charCodeAt(O+t.length):32;if(!bu(r)&&!bu(w))return O;m=O+1}return null}dispose(){if(this.#m)return;this.#m=!0,this.#n.dispose(),this.#t.clear()}#r(){if(this.#m)throw Error("SemanticLayer is disposed")}}var Qi=30000,Ru=60000,Ui=10;function Li(n,u){return(t)=>{if(u.handleWatcherEvent?.(t),n.semanticLayer)if(t.eventType==="delete")n.semanticLayer.notifyFileDeleted(t.filePath);else n.readFileFn(t.filePath).then((i)=>{n.semanticLayer?.notifyFileChanged(t.filePath,i)}).catch(()=>{})}}async function Yi(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(t)=>{try{let i=Mn.resolve(n.projectRoot,t.filePath),g=await n.readFileFn(i);n.semanticLayer?.notifyFileChanged(i,g)}catch{}}))}async function yu(n,u){let t=n.coordinatorFactory?n.coordinatorFactory():new xn({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=t;for(let i of n.onIndexedCallbacks)t.onIndexed(i);if(t.onIndexed(()=>{n.graphCache=null,n.graphCacheKey=null}),u.isWatchMode){let i=n.watcherFactory?n.watcherFactory():new En({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await i.start(Li(n,t)).then((g)=>{if(Nn(g))throw g.data}),n.watcher=i,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Qi)}await t.fullIndex(),await Yi(n)}function Zi(n,u){let t=["SIGTERM","SIGINT","beforeExit"];for(let i of t){let g=()=>{u().catch((m)=>n.logger.error("[Gildash] close error during signal",i,m))};if(i==="beforeExit")process.on("beforeExit",g);else process.on(i,g);n.signalHandlers.push([i,g])}}async function pu(n){let{projectRoot:u,extensions:t=[".ts",".mts",".cts"],ignorePatterns:i=["**/node_modules/**"],parseCacheCapacity:g=500,logger:m=console,existsSyncFn:O=Bi,dbConnectionFactory:r,watcherFactory:w,coordinatorFactory:f,repositoryFactory:s,acquireWatcherRoleFn:A=Uu,releaseWatcherRoleFn:M=Lu,updateHeartbeatFn:k=Yu,discoverProjectsFn:I=In,parseSourceFn:H=An,extractSymbolsFn:B=Vn,extractRelationsFn:_=Bn,symbolSearchFn:N=on,relationSearchFn:S=en,patternSearchFn:J=cn,loadTsconfigPathsFn:$=sn,readFileFn:z=async(Q)=>Bun.file(Q).text(),unlinkFn:V=async(Q)=>{await Bun.file(Q).unlink()},watchMode:L,semantic:K,semanticLayerFactory:T}=n;if(!Mn.isAbsolute(u))throw new a("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!O(u))throw new a("validation",`Gildash: projectRoot does not exist: "${u}"`);let D=r?r():new Rn({projectRoot:u}),Y=D.open();if(Nn(Y))throw Y.data;try{let Q=await I(u),E=Q[0]?.project??Mn.basename(u),P=s?s():(()=>{let G=D;return{fileRepo:new yn(G),symbolRepo:new pn(G),relationRepo:new Fn(G),parseCache:new ln(g)}})(),d=L??!0,fn;if(d)fn=await Promise.resolve(A(D,process.pid,{}));else fn="owner";let Z={projectRoot:u,extensions:t,ignorePatterns:i,logger:m,defaultProject:E,role:fn,db:D,symbolRepo:P.symbolRepo,relationRepo:P.relationRepo,fileRepo:P.fileRepo,parseCache:P.parseCache,releaseWatcherRoleFn:M,parseSourceFn:H,extractSymbolsFn:B,extractRelationsFn:_,symbolSearchFn:N,relationSearchFn:S,patternSearchFn:J,readFileFn:z,unlinkFn:V,existsSyncFn:O,acquireWatcherRoleFn:A,updateHeartbeatFn:k,watcherFactory:w,coordinatorFactory:f,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:Q,onIndexedCallbacks:new Set,graphCache:null,graphCacheKey:null,semanticLayer:null};if(Hn(u),Z.tsconfigPaths=await $(u),K){let G=Mn.join(u,"tsconfig.json");try{if(T)Z.semanticLayer=T(G);else{let h=Ln.create(G);if(Nn(h))throw h.data;Z.semanticLayer=h}}catch(h){if(h instanceof a)throw h;throw new a("semantic","Gildash: semantic layer creation failed",{cause:h})}}if(fn==="owner")await yu(Z,{isWatchMode:d});else{let G=0,h=async()=>{try{let Xn=await Promise.resolve(Z.acquireWatcherRoleFn(Z.db,process.pid,{}));if(G=0,Xn==="owner"){clearInterval(Z.timer),Z.timer=null;try{await yu(Z,{isWatchMode:!0})}catch(Tn){if(Z.logger.error("[Gildash] owner promotion failed, reverting to reader",Tn),Z.watcher){let $n=await Z.watcher.close();if(Nn($n))Z.logger.error("[Gildash] watcher close error during promotion rollback",$n.data);Z.watcher=null}if(Z.coordinator)await Z.coordinator.shutdown().catch(($n)=>Z.logger.error("[Gildash] coordinator shutdown error during promotion rollback",$n)),Z.coordinator=null;if(Z.timer===null)Z.timer=setInterval(h,Ru)}}}catch(Xn){if(G++,Z.logger.error("[Gildash] healthcheck error",Xn),G>=Ui)Z.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(Z.timer),Z.timer=null,Yn(Z).catch((Tn)=>Z.logger.error("[Gildash] close error during healthcheck shutdown",Tn))}};Z.timer=setInterval(h,Ru)}if(d)Zi(Z,()=>Yn(Z));return Z}catch(Q){if(D.close(),Q instanceof a)throw Q;throw new a("store","Gildash: initialization failed",{cause:Q})}}async function Yn(n,u){if(n.closed)return;n.closed=!0;let t=[];for(let[i,g]of n.signalHandlers)if(i==="beforeExit")process.off("beforeExit",g);else process.off(i,g);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(n.watcher){let i=await n.watcher.close();if(Nn(i))t.push(i.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(i){t.push(i instanceof Error?i:Error(String(i)))}try{n.db.close()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(u?.cleanup)for(let i of["","-wal","-shm"])try{await n.unlinkFn(Mn.join(n.projectRoot,e,Wn+i))}catch{}if(t.length>0)throw new a("close","Gildash: one or more errors occurred during close()",{cause:t})}import{isErr as Fu}from"@zipbul/result";function vu(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");let g=n.parseSourceFn(u,t,i);if(Fu(g))throw g.data;return n.parseCache.set(u,g),g}async function Eu(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");let i=new Map;return await Promise.all(u.map(async(g)=>{try{let m=await n.readFileFn(g),O=n.parseSourceFn(g,m,t);if(!Fu(O))i.set(g,O)}catch{}})),i}function qu(n,u){if(n.closed)return;return n.parseCache.get(u)}function Gu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function ju(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import Pu from"path";function du(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(t){if(t instanceof a)throw t;throw new a("store","Gildash: getStats failed",{cause:t})}}function mu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchSymbols failed",{cause:t})}}function hu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchRelations failed",{cause:t})}}function xu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchAllSymbols failed",{cause:t})}}function lu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchAllRelations failed",{cause:t})}}function ou(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(t){if(t instanceof a)throw t;throw new a("store","Gildash: listIndexedFiles failed",{cause:t})}}function eu(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getInternalRelations failed",{cause:i})}}function cu(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g,query:{text:u,exact:!0,filePath:t,limit:1}});if(m.length===0)return null;let O=m[0],r=O.detail,w={...O,members:Array.isArray(r.members)?r.members:void 0,jsDoc:typeof r.jsDoc==="string"?r.jsDoc:void 0,parameters:typeof r.parameters==="string"?r.parameters:void 0,returnType:typeof r.returnType==="string"?r.returnType:void 0,heritage:Array.isArray(r.heritage)?r.heritage:void 0,decorators:Array.isArray(r.decorators)?r.decorators:void 0,typeParameters:typeof r.typeParameters==="string"?r.typeParameters:void 0};if(n.semanticLayer)try{let f=Pu.isAbsolute(t)?t:Pu.resolve(n.projectRoot,t),s=n.semanticLayer.lineColumnToPosition(f,O.span.start.line,O.span.start.column);if(s!==null){let A=n.semanticLayer.findNamePosition(f,s,O.name)??s,M=n.semanticLayer.collectTypeAt(f,A);if(M)w.resolvedType=M}}catch{}return w}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getFullSymbol failed",{cause:g})}}function nt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=t??n.defaultProject,g=n.fileRepo.getFile(i,u);if(!g)throw new a("search",`Gildash: file '${u}' is not in the index`);let m=n.symbolRepo.getFileSymbols(i,u),O=n.relationRepo.getOutgoing(i,u);return{filePath:g.filePath,lineCount:g.lineCount??0,size:g.size,symbolCount:m.length,exportedSymbolCount:m.filter((r)=>r.isExported).length,relationCount:O.length}}catch(i){if(i instanceof a)throw i;throw new a("store","Gildash: getFileStats failed",{cause:i})}}function ut(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(t??n.defaultProject,u)}catch(i){if(i instanceof a)throw i;throw new a("store","Gildash: getFileInfo failed",{cause:i})}}function tt(n,u,t){return mu(n,{filePath:u,project:t??void 0,limit:1e4})}function it(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t??n.defaultProject,query:{filePath:u,isExported:!0}}).map((m)=>({name:m.name,kind:m.kind,parameters:m.detail.parameters??void 0,returnType:m.detail.returnType??void 0,jsDoc:m.detail.jsDoc??void 0}));return{filePath:u,exports:g}}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getModuleInterface failed",{cause:i})}}class Zn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((t)=>[...this.options.relationRepo.getByType(t,"imports"),...this.options.relationRepo.getByType(t,"type-references"),...this.options.relationRepo.getByType(t,"re-exports")]);for(let t of u){let{srcFilePath:i,dstFilePath:g}=t;if(!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(this.adjacencyList.get(i).add(g),!this.adjacencyList.has(g))this.adjacencyList.set(g,new Set);if(!this.reverseAdjacencyList.has(g))this.reverseAdjacencyList.set(g,new Set);this.reverseAdjacencyList.get(g).add(i)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,t=[n];while(t.length>0){let i=t.shift();for(let g of this.reverseAdjacencyList.get(i)??[])if(!u.has(g))u.add(g),t.push(g)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let t of this.adjacencyList.keys()){if(n.has(t))continue;let i=[{node:t,entered:!1}];while(i.length>0){let g=i.pop();if(g.entered){u.delete(g.node);continue}if(u.has(g.node))return!0;if(n.has(g.node))continue;n.add(g.node),u.add(g.node),i.push({node:g.node,entered:!0});for(let m of this.adjacencyList.get(g.node)??[]){if(u.has(m))return!0;if(!n.has(m))i.push({node:m,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let t of n)for(let i of this.getTransitiveDependents(t))u.add(i);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,t]of this.adjacencyList)n.set(u,Array.from(t));return n}getTransitiveDependencies(n){let u=new Set,t=[n];while(t.length>0){let i=t.shift();for(let g of this.adjacencyList.get(i)??[])if(!u.has(g))u.add(g),t.push(g)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let t=new Map;for(let[i,g]of this.adjacencyList)t.set(i,Array.from(g));return Fi(t,u)}}var bi=(n,u)=>n.localeCompare(u);function Ri(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let t=u;for(let i=1;i<u.length;i++){let g=u.slice(i).concat(u.slice(0,i));if(g.join("::")<t.join("::"))t=g}return[...t]}function ru(n,u,t){let i=Ri(t);if(i.length===0)return!1;let g=i.join("->");if(n.has(g))return!1;return n.add(g),u.push(i),!0}function yi(n){let u=0,t=[],i=new Set,g=new Map,m=new Map,O=[],r=(w)=>{g.set(w,u),m.set(w,u),u+=1,t.push(w),i.add(w);for(let f of n.get(w)??[])if(!g.has(f))r(f),m.set(w,Math.min(m.get(w)??0,m.get(f)??0));else if(i.has(f))m.set(w,Math.min(m.get(w)??0,g.get(f)??0));if(m.get(w)===g.get(w)){let f=[],s="";do s=t.pop()??"",i.delete(s),f.push(s);while(s!==w&&t.length>0);O.push(f)}};for(let w of n.keys())if(!g.has(w))r(w);return{components:O}}function pi(n,u,t){let i=[],g=new Set,m=[...n].sort(bi),O=(r,w,f)=>{w.delete(r);let s=f.get(r);if(!s)return;for(let A of s)if(w.has(A))O(A,w,f);s.clear()};for(let r=0;r<m.length&&i.length<t;r++){let w=m[r]??"",f=new Set(m.slice(r)),s=new Set,A=new Map,M=[],k=(H)=>(u.get(H)??[]).filter((B)=>f.has(B)),I=(H)=>{if(i.length>=t)return!0;let B=!1;M.push(H),s.add(H);for(let _ of k(H)){if(i.length>=t)break;if(_===w)ru(g,i,M.concat(w)),B=!0;else if(!s.has(_)){if(I(_))B=!0}}if(B)O(H,s,A);else for(let _ of k(H)){let N=A.get(_)??new Set;N.add(H),A.set(_,N)}return M.pop(),B};I(w)}return i}function Fi(n,u){let{components:t}=yi(n),i=[],g=new Set;for(let m of t){if(i.length>=u)break;if(m.length===0)continue;if(m.length===1){let w=m[0]??"";if((n.get(w)??[]).includes(w))ru(g,i,[w,w]);continue}let O=u-i.length,r=pi(m,n,O);for(let w of r){if(i.length>=u)break;ru(g,i,w)}}return i}function gt(n){n.graphCache=null,n.graphCacheKey=null}function Sn(n,u){let t=u??"__cross__";if(n.graphCache&&n.graphCacheKey===t)return n.graphCache;let i=new Zn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((g)=>g.project)});return i.build(),n.graphCache=i,n.graphCacheKey=t,i}function mt(n,u,t,i=1e4){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{srcFilePath:u,type:"imports",project:t??n.defaultProject,limit:i}}).map((g)=>g.dstFilePath)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getDependencies failed",{cause:g})}}function rt(n,u,t,i=1e4){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{dstFilePath:u,type:"imports",project:t??n.defaultProject,limit:i}}).map((g)=>g.srcFilePath)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getDependents failed",{cause:g})}}async function wt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,t).getAffectedByChange(u)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getAffected failed",{cause:i})}}async function Ot(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).hasCycle()}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: hasCycle failed",{cause:t})}}async function St(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).getAdjacencyList()}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: getImportGraph failed",{cause:t})}}async function ft(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,t).getTransitiveDependencies(u)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getTransitiveDependencies failed",{cause:i})}}async function at(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).getCyclePaths(t)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getCyclePaths failed",{cause:i})}}async function st(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=Sn(n,t);return{filePath:u,fanIn:i.getDependents(u).length,fanOut:i.getDependencies(u).length}}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getFanMetrics failed",{cause:i})}}import At from"path";function wu(n,u,t,i){let g=i??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g,query:{text:u,exact:!0,filePath:t,limit:1}});if(m.length===0)return null;let O=m[0],r=At.isAbsolute(t)?t:At.resolve(n.projectRoot,t),w=n.semanticLayer.lineColumnToPosition(r,O.span.start.line,O.span.start.column);if(w===null)return null;let f=n.semanticLayer.findNamePosition(r,w,O.name)??w;return{sym:O,position:f,absPath:r}}function _t(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)return null;return n.semanticLayer.collectTypeAt(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getResolvedType failed",{cause:g})}}function Jt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)throw new a("search",`Gildash: symbol '${u}' not found in '${t}'`);return n.semanticLayer.findReferences(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getSemanticReferences failed",{cause:g})}}function Nt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)throw new a("search",`Gildash: symbol '${u}' not found in '${t}'`);return n.semanticLayer.findImplementations(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getImplementations failed",{cause:g})}}function Mt(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: getSemanticModuleInterface failed",{cause:t})}}function $t(n,u){let t=new Map(n.map((r)=>[`${r.name}::${r.filePath}`,r])),i=new Map(u.map((r)=>[`${r.name}::${r.filePath}`,r])),g=[],m=[],O=[];for(let[r,w]of i){let f=t.get(r);if(!f)g.push(w);else if(f.fingerprint!==w.fingerprint)O.push({before:f,after:w})}for(let[r,w]of t)if(!i.has(r))m.push(w);return{added:g,removed:m,modified:O}}function Wt(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let t=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),t()}}async function Dt(n){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.coordinator)throw new a("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return gt(n),u}catch(u){if(u instanceof a)throw u;throw new a("index","Gildash: reindex failed",{cause:u})}}function kt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");let g=i??n.defaultProject,m=new Set,O=[],r=u,w=t;for(;;){let f=`${w}::${r}`;if(m.has(f))return{originalName:r,originalFilePath:w,reExportChain:O,circular:!0};m.add(f);let s=n.relationSearchFn({relationRepo:n.relationRepo,project:g,query:{type:"re-exports",srcFilePath:w,limit:500}}),A,M;for(let k of s){let I;if(k.metaJson)try{let B=JSON.parse(k.metaJson);if(Array.isArray(B.specifiers))I=B.specifiers}catch{}if(!I)continue;let H=I.find((B)=>B.exported===r);if(!H)continue;A=k.dstFilePath,M=H.local;break}if(!A||!M)return{originalName:r,originalFilePath:w,reExportChain:O,circular:!1};O.push({filePath:w,exportedAs:r}),w=A,r=M}}async function zt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=t?.project??n.defaultProject,g=t?.filePaths?t.filePaths:n.fileRepo.getAllFiles(i).map((m)=>m.filePath);return await n.patternSearchFn({pattern:u,filePaths:g})}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: findPattern failed",{cause:i})}}async function It(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,m=new Set,O=(r,w,f)=>{let s=`${r}::${w}`;if(m.has(s))return{symbolName:r,filePath:w,kind:f,children:[]};m.add(s);let k=n.relationSearchFn({relationRepo:n.relationRepo,project:g,query:{srcFilePath:w,srcSymbolName:r,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>O(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:r,filePath:w,kind:f,children:k}};return O(u,t)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getHeritageChain failed",{cause:g})}}class Ou{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await pu(n);return new Ou(u)}async close(n){return Yn(this._ctx,n)}parseSource(n,u,t){return vu(this._ctx,n,u,t)}async batchParse(n,u){return Eu(this._ctx,n,u)}getParsedAst(n){return qu(this._ctx,n)}extractSymbols(n){return Gu(this._ctx,n)}extractRelations(n){return ju(this._ctx,n)}getStats(n){return du(this._ctx,n)}searchSymbols(n){return mu(this._ctx,n)}searchRelations(n){return hu(this._ctx,n)}searchAllSymbols(n){return xu(this._ctx,n)}searchAllRelations(n){return lu(this._ctx,n)}listIndexedFiles(n){return ou(this._ctx,n)}getInternalRelations(n,u){return eu(this._ctx,n,u)}getFullSymbol(n,u,t){return cu(this._ctx,n,u,t)}getFileStats(n,u){return nt(this._ctx,n,u)}getFileInfo(n,u){return ut(this._ctx,n,u)}getSymbolsByFile(n,u){return tt(this._ctx,n,u)}getModuleInterface(n,u){return it(this._ctx,n,u)}getDependencies(n,u,t=1e4){return mt(this._ctx,n,u,t)}getDependents(n,u,t=1e4){return rt(this._ctx,n,u,t)}async getAffected(n,u){return wt(this._ctx,n,u)}async hasCycle(n){return Ot(this._ctx,n)}async getImportGraph(n){return St(this._ctx,n)}async getTransitiveDependencies(n,u){return ft(this._ctx,n,u)}async getCyclePaths(n,u){return at(this._ctx,n,u)}async getFanMetrics(n,u){return st(this._ctx,n,u)}getResolvedType(n,u,t){return _t(this._ctx,n,u,t)}getSemanticReferences(n,u,t){return Jt(this._ctx,n,u,t)}getImplementations(n,u,t){return Nt(this._ctx,n,u,t)}getSemanticModuleInterface(n){return Mt(this._ctx,n)}diffSymbols(n,u){return $t(n,u)}onIndexed(n){return Wt(this._ctx,n)}async reindex(){return Dt(this._ctx)}resolveSymbol(n,u,t){return kt(this._ctx,n,u,t)}async findPattern(n,u){return zt(this._ctx,n,u)}async getHeritageChain(n,u,t){return It(this._ctx,n,u,t)}}export{on as symbolSearch,en as relationSearch,cn as patternSearch,v as gildashError,a as GildashError,Ou as Gildash,Zn as DependencyGraph};
|
|
6
8
|
|
|
7
|
-
//# debugId=
|
|
9
|
+
//# debugId=2B12BAE74427975264756E2164756E21
|
|
8
10
|
//# sourceMappingURL=index.js.map
|