pando-ai 1.1.7 → 1.1.9
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.md +11 -75
- package/dist/cli.js +202 -202
- package/dist/watcher-process.js +2 -2
- package/dist/workers/{chunk-WYR734MG.mjs → chunk-6CRK2JH6.mjs} +1 -1
- package/dist/workers/chunk-CGVA3QGF.mjs +4 -0
- package/dist/workers/indexer-worker.mjs +1 -1
- package/dist/workers/snapshot-worker.mjs +1 -1
- package/dist/workers/sqlite-writer-worker.mjs +1 -1
- package/package.json +1 -1
- package/tools/clojure-editor/lib/pando-clojure-editor-standalone.jar +0 -0
- package/tools/clojure-indexer/lib/pando-clojure-indexer-standalone.jar +0 -0
- package/dist/workers/chunk-MGQRPDUI.mjs +0 -4
package/dist/watcher-process.js
CHANGED
|
@@ -32184,7 +32184,7 @@ Project '${p.projectName}' (${XQ[p.projectKind]}) ${a}
|
|
|
32184
32184
|
Additional information: BADCLIENT: Bad error code, ${N} not found in range ${d}..${p} (found: ${D.join(", ")})`),x}return t?h.map(y=>this.mapCodeFixAction(y)):h}getCombinedCodeFix({scope:e,fixId:t},r){B.assert(e.type==="file");let{file:s,project:a}=this.getFileAndProject(e.args),d=a.getLanguageService().getCombinedCodeFix({type:"file",fileName:s},t,this.getFormatOptions(s),this.getPreferences(s));return r?{changes:this.mapTextChangesToCodeEdits(d.changes),commands:d.commands}:d}applyCodeActionCommand(e){let t=e.command;for(let r of kp(t)){let{file:s,project:a}=this.getFileAndProject(r);a.getLanguageService().applyCodeActionCommand(r,this.getFormatOptions(s)).then(d=>{},d=>{})}return{}}getStartAndEndPosition(e,t){let r,s;return e.startPosition!==void 0?r=e.startPosition:(r=t.lineOffsetToPosition(e.startLine,e.startOffset),e.startPosition=r),e.endPosition!==void 0?s=e.endPosition:(s=t.lineOffsetToPosition(e.endLine,e.endOffset),e.endPosition=s),{startPosition:r,endPosition:s}}mapCodeAction({description:e,changes:t,commands:r}){return{description:e,changes:this.mapTextChangesToCodeEdits(t),commands:r}}mapCodeFixAction({fixName:e,description:t,changes:r,commands:s,fixId:a,fixAllDescription:d}){return{fixName:e,description:t,changes:this.mapTextChangesToCodeEdits(r),commands:s,fixId:a,fixAllDescription:d}}mapPasteEditsAction({edits:e,fixId:t}){return{edits:this.mapTextChangesToCodeEdits(e),fixId:t}}mapTextChangesToCodeEdits(e){return e.map(t=>this.mapTextChangeToCodeEdit(t))}mapTextChangeToCodeEdit(e){let t=this.projectService.getScriptInfoOrConfig(e.fileName);return!!e.isNewFile==!!t&&(t||this.projectService.logErrorForScriptInfoNotFound(e.fileName),B.fail("Expected isNewFile for (only) new files. "+JSON.stringify({isNewFile:!!e.isNewFile,hasScriptInfo:!!t}))),t?{fileName:e.fileName,textChanges:e.textChanges.map(r=>lHe(r,t))}:vPt(e)}convertTextChangeToCodeEdit(e,t){return{start:t.positionToLineOffset(e.span.start),end:t.positionToLineOffset(e.span.start+e.span.length),newText:e.newText?e.newText:""}}getBraceMatching(e,t){let{file:r,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(e),a=this.projectService.getScriptInfoForNormalizedPath(r),d=this.getPosition(e,a),p=s.getBraceMatchingAtPosition(r,d);return p?t?p.map(h=>Ik(h,a)):p:void 0}getDiagnosticsForProject(e,t,r){if(this.suppressDiagnosticEvents)return;let{fileNames:s,languageServiceDisabled:a}=this.getProjectInfoWorker(r,void 0,!0,void 0,!0);if(a)return;let d=s.filter(F=>!F.includes("lib.d.ts"));if(d.length===0)return;let p=[],h=[],y=[],x=[],E=vp(r),D=this.projectService.ensureDefaultProjectForFile(E);for(let F of d)this.getCanonicalFileName(F)===this.getCanonicalFileName(r)?p.push(F):this.projectService.getScriptInfo(F).isScriptOpen()?h.push(F):Hb(F)?x.push(F):y.push(F);let R=[...p,...h,...y,...x].map(F=>({fileName:F,project:D}));this.updateErrorCheck(e,R,t,!1)}configurePlugin(e){this.projectService.configurePlugin(e)}getSmartSelectionRange(e,t){let{locations:r}=e,{file:s,languageService:a}=this.getFileAndLanguageServiceForSyntacticOperation(e),d=B.checkDefined(this.projectService.getScriptInfo(s));return At(r,p=>{let h=this.getPosition(p,d),y=a.getSmartSelectionRange(s,h);return t?this.mapSelectionRange(y,d):y})}toggleLineComment(e,t){let{file:r,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(e),a=this.projectService.getScriptInfo(r),d=this.getRange(e,a),p=s.toggleLineComment(r,d);if(t){let h=this.projectService.getScriptInfoForNormalizedPath(r);return p.map(y=>this.convertTextChangeToCodeEdit(y,h))}return p}toggleMultilineComment(e,t){let{file:r,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(e),a=this.projectService.getScriptInfoForNormalizedPath(r),d=this.getRange(e,a),p=s.toggleMultilineComment(r,d);if(t){let h=this.projectService.getScriptInfoForNormalizedPath(r);return p.map(y=>this.convertTextChangeToCodeEdit(y,h))}return p}commentSelection(e,t){let{file:r,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(e),a=this.projectService.getScriptInfoForNormalizedPath(r),d=this.getRange(e,a),p=s.commentSelection(r,d);if(t){let h=this.projectService.getScriptInfoForNormalizedPath(r);return p.map(y=>this.convertTextChangeToCodeEdit(y,h))}return p}uncommentSelection(e,t){let{file:r,languageService:s}=this.getFileAndLanguageServiceForSyntacticOperation(e),a=this.projectService.getScriptInfoForNormalizedPath(r),d=this.getRange(e,a),p=s.uncommentSelection(r,d);if(t){let h=this.projectService.getScriptInfoForNormalizedPath(r);return p.map(y=>this.convertTextChangeToCodeEdit(y,h))}return p}mapSelectionRange(e,t){let r={textSpan:Ik(e.textSpan,t)};return e.parent&&(r.parent=this.mapSelectionRange(e.parent,t)),r}getScriptInfoFromProjectService(e){let t=vp(e),r=this.projectService.getScriptInfoForNormalizedPath(t);return r||(this.projectService.logErrorForScriptInfoNotFound(t),HL.ThrowNoProject())}toProtocolCallHierarchyItem(e){let t=this.getScriptInfoFromProjectService(e.file);return{name:e.name,kind:e.kind,kindModifiers:e.kindModifiers,file:e.file,containerName:e.containerName,span:Ik(e.span,t),selectionSpan:Ik(e.selectionSpan,t)}}toProtocolCallHierarchyIncomingCall(e){let t=this.getScriptInfoFromProjectService(e.from.file);return{from:this.toProtocolCallHierarchyItem(e.from),fromSpans:e.fromSpans.map(r=>Ik(r,t))}}toProtocolCallHierarchyOutgoingCall(e,t){return{to:this.toProtocolCallHierarchyItem(e.to),fromSpans:e.fromSpans.map(r=>Ik(r,t))}}prepareCallHierarchy(e){let{file:t,project:r}=this.getFileAndProject(e),s=this.projectService.getScriptInfoForNormalizedPath(t);if(s){let a=this.getPosition(e,s),d=r.getLanguageService().prepareCallHierarchy(t,a);return d&&Ale(d,p=>this.toProtocolCallHierarchyItem(p))}}provideCallHierarchyIncomingCalls(e){let{file:t,project:r}=this.getFileAndProject(e),s=this.getScriptInfoFromProjectService(t);return r.getLanguageService().provideCallHierarchyIncomingCalls(t,this.getPosition(e,s)).map(d=>this.toProtocolCallHierarchyIncomingCall(d))}provideCallHierarchyOutgoingCalls(e){let{file:t,project:r}=this.getFileAndProject(e),s=this.getScriptInfoFromProjectService(t);return r.getLanguageService().provideCallHierarchyOutgoingCalls(t,this.getPosition(e,s)).map(d=>this.toProtocolCallHierarchyOutgoingCall(d,s))}getCanonicalFileName(e){let t=this.host.useCaseSensitiveFileNames?e:Ni(e);return sl(t)}exit(){}notRequired(e){return e&&this.doOutput(void 0,e.command,e.seq,!0,this.performanceData),{responseRequired:!1,performanceData:this.performanceData}}requiredResponse(e){return{response:e,responseRequired:!0,performanceData:this.performanceData}}addProtocolHandler(e,t){if(this.handlers.has(e))throw new Error(`Protocol handler already exists for command "${e}"`);this.handlers.set(e,t)}setCurrentRequest(e){B.assert(this.currentRequestId===void 0),this.currentRequestId=e,this.cancellationToken.setRequest(e)}resetCurrentRequest(e){B.assert(this.currentRequestId===e),this.currentRequestId=void 0,this.cancellationToken.resetRequest(e)}executeWithRequestId(e,t,r){let s=this.performanceData;try{return this.performanceData=r,this.setCurrentRequest(e),t()}finally{this.resetCurrentRequest(e),this.performanceData=s}}executeCommand(e){let t=this.handlers.get(e.command);if(t){let r=this.executeWithRequestId(e.seq,()=>t(e),void 0);return this.projectService.enableRequestedPlugins(),r}else return this.logger.msg(`Unrecognized JSON command:${Z9(e)}`,"Err"),this.doOutput(void 0,"unknown",e.seq,!1,void 0,`Unrecognized JSON command: ${e.command}`),{responseRequired:!1}}onMessage(e){var t,r,s,a,d,p,h;this.gcTimer.scheduleCollect();let y,x=this.performanceData;this.logger.hasLevel(2)&&(y=this.hrtime(),this.logger.hasLevel(3)&&this.logger.info(`request:${ene(this.toStringMessage(e))}`));let E,D;try{E=this.parseMessage(e),D=E.arguments&&E.arguments.file?E.arguments:void 0,(t=oi)==null||t.instant(oi.Phase.Session,"request",{seq:E.seq,command:E.command}),(r=oi)==null||r.push(oi.Phase.Session,"executeCommand",{seq:E.seq,command:E.command},!0);let{response:N,responseRequired:R,performanceData:F}=this.executeCommand(E);if((s=oi)==null||s.pop(),this.logger.hasLevel(2)){let z=lot(this.hrtime(y)).toFixed(4);R?this.logger.perftrc(`${E.seq}::${E.command}: elapsed time (in milliseconds) ${z}`):this.logger.perftrc(`${E.seq}::${E.command}: async elapsed time (in milliseconds) ${z}`)}(a=oi)==null||a.instant(oi.Phase.Session,"response",{seq:E.seq,command:E.command,success:!!N}),N?this.doOutput(N,E.command,E.seq,!0,F):R&&this.doOutput(void 0,E.command,E.seq,!1,F,"No content available.")}catch(N){if((d=oi)==null||d.popAll(),N instanceof aR){(p=oi)==null||p.instant(oi.Phase.Session,"commandCanceled",{seq:E?.seq,command:E?.command}),this.doOutput({canceled:!0},E.command,E.seq,!0,this.performanceData);return}this.logErrorWorker(N,this.toStringMessage(e),D),(h=oi)==null||h.instant(oi.Phase.Session,"commandError",{seq:E?.seq,command:E?.command,message:N.message}),this.doOutput(void 0,E?E.command:"unknown",E?E.seq:0,!1,this.performanceData,"Error processing request. "+N.message+`
|
|
32185
32185
|
`+N.stack)}finally{this.performanceData=x}}parseMessage(e){return JSON.parse(e)}toStringMessage(e){return e}getFormatOptions(e){return this.projectService.getFormatCodeOptions(e)}getPreferences(e){return this.projectService.getPreferences(e)}getHostFormatOptions(){return this.projectService.getHostFormatCodeOptions()}getHostPreferences(){return this.projectService.getHostPreferences()}};function oHe(n){let e=n.diagnosticsDuration&&Ga(n.diagnosticsDuration,([t,r])=>({...r,file:t}));return{...n,diagnosticsDuration:e}}function Ik(n,e){return{start:e.positionToLineOffset(n.start),end:e.positionToLineOffset(mu(n))}}function iN(n,e,t){let r=Ik(n,t),s=e&&Ik(e,t);return s?{...r,contextStart:s.start,contextEnd:s.end}:r}function lHe(n,e){return{start:Sot(e,n.span.start),end:Sot(e,mu(n.span)),newText:n.newText}}function Sot(n,e){return tHe(n)?yPt(n.getLineAndCharacterOfPosition(e)):n.positionToLineOffset(e)}function xot(n,e){let t=n.ranges.map(r=>({start:e.positionToLineOffset(r.start),end:e.positionToLineOffset(r.start+r.length)}));return n.wordPattern?{ranges:t,wordPattern:n.wordPattern}:{ranges:t}}function yPt(n){return{line:n.line+1,offset:n.character+1}}function vPt(n){B.assert(n.textChanges.length===1);let e=jo(n.textChanges);return B.assert(e.span.start===0&&e.span.length===0),{fileName:n.fileName,textChanges:[{start:{line:0,offset:0},end:{line:0,offset:0},newText:e.newText}]}}function cHe(n,e,t,r){let s=uHe(n,e,r),{line:a,character:d}=ND(zN(s),t);return{line:a+1,offset:d+1}}function uHe(n,e,t){for(let{fileName:r,textChanges:s}of t)if(r===e)for(let a=s.length-1;a>=0;a--){let{newText:d,span:{start:p,length:h}}=s[a];n=n.slice(0,p)+d+n.slice(p+h)}return n}function Eot(n,{fileName:e,textSpan:t,contextSpan:r,isWriteAccess:s,isDefinition:a},{disableLineTextInReferences:d}){let p=B.checkDefined(n.getScriptInfo(e)),h=iN(t,r,p),y=d?void 0:Tot(p,h);return{file:e,...h,lineText:y,isWriteAccess:s,isDefinition:a}}function Tot(n,e){let t=n.lineToTextSpan(e.start.line-1);return n.getSnapshot().getText(t.start,mu(t)).replace(/\r|\n/g,"")}function bPt(n){return n===void 0||n&&typeof n=="object"&&typeof n.exportName=="string"&&(n.fileName===void 0||typeof n.fileName=="string")&&(n.ambientModuleName===void 0||typeof n.ambientModuleName=="string"&&(n.isPackageJsonImport===void 0||typeof n.isPackageJsonImport=="boolean"))}var nre=4,VK=(n=>(n[n.PreStart=0]="PreStart",n[n.Start=1]="Start",n[n.Entire=2]="Entire",n[n.Mid=3]="Mid",n[n.End=4]="End",n[n.PostEnd=5]="PostEnd",n))(VK||{}),dHe=class{constructor(){this.goSubtree=!0,this.lineIndex=new Mce,this.endBranch=[],this.state=2,this.initialText="",this.trailingText="",this.lineIndex.root=new DB,this.startPath=[this.lineIndex.root],this.stack=[this.lineIndex.root]}get done(){return!1}insertLines(n,e){e&&(this.trailingText=""),n?n=this.initialText+n+this.trailingText:n=this.initialText+this.trailingText;let r=Mce.linesFromText(n).lines;r.length>1&&r[r.length-1]===""&&r.pop();let s,a;for(let p=this.endBranch.length-1;p>=0;p--)this.endBranch[p].updateCounts(),this.endBranch[p].charCount()===0&&(a=this.endBranch[p],p>0?s=this.endBranch[p-1]:s=this.branchNode);a&&s.remove(a);let d=this.startPath[this.startPath.length-1];if(r.length>0)if(d.text=r[0],r.length>1){let p=new Array(r.length-1),h=d;for(let E=1;E<r.length;E++)p[E-1]=new Pj(r[E]);let y=this.startPath.length-2;for(;y>=0;){let E=this.startPath[y];p=E.insertAt(h,p),y--,h=E}let x=p.length;for(;x>0;){let E=new DB;E.add(this.lineIndex.root),p=E.insertAt(this.lineIndex.root,p),x=p.length,this.lineIndex.root=E}this.lineIndex.root.updateCounts()}else for(let p=this.startPath.length-2;p>=0;p--)this.startPath[p].updateCounts();else{this.startPath[this.startPath.length-2].remove(d);for(let h=this.startPath.length-2;h>=0;h--)this.startPath[h].updateCounts()}return this.lineIndex}post(n,e,t){t===this.lineCollectionAtBranch&&(this.state=4),this.stack.pop()}pre(n,e,t,r,s){let a=this.stack[this.stack.length-1];this.state===2&&s===1&&(this.state=1,this.branchNode=a,this.lineCollectionAtBranch=t);let d;function p(h){return h.isLeaf()?new Pj(""):new DB}switch(s){case 0:this.goSubtree=!1,this.state!==4&&a.add(t);break;case 1:this.state===4?this.goSubtree=!1:(d=p(t),a.add(d),this.startPath.push(d));break;case 2:this.state!==4?(d=p(t),a.add(d),this.startPath.push(d)):t.isLeaf()||(d=p(t),a.add(d),this.endBranch.push(d));break;case 3:this.goSubtree=!1;break;case 4:this.state!==4?this.goSubtree=!1:t.isLeaf()||(d=p(t),a.add(d),this.endBranch.push(d));break;case 5:this.goSubtree=!1,this.state!==1&&a.add(t);break}this.goSubtree&&this.stack.push(d)}leaf(n,e,t){this.state===1?this.initialText=t.text.substring(0,n):this.state===2?(this.initialText=t.text.substring(0,n),this.trailingText=t.text.substring(n+e)):this.trailingText=t.text.substring(n+e)}},SPt=class{constructor(n,e,t){this.pos=n,this.deleteLen=e,this.insertedText=t}getTextChangeRange(){return Y7(qp(this.pos,this.deleteLen),this.insertedText?this.insertedText.length:0)}},FMe=class yie{constructor(){this.changes=[],this.versions=new Array(yie.maxVersions),this.minVersion=0,this.currentVersion=0}versionToIndex(e){if(!(e<this.minVersion||e>this.currentVersion))return e%yie.maxVersions}currentVersionToIndex(){return this.currentVersion%yie.maxVersions}edit(e,t,r){this.changes.push(new SPt(e,t,r)),(this.changes.length>yie.changeNumberThreshold||t>yie.changeLengthThreshold||r&&r.length>yie.changeLengthThreshold)&&this.getSnapshot()}getSnapshot(){return this._getSnapshot()}_getSnapshot(){let e=this.versions[this.currentVersionToIndex()];if(this.changes.length>0){let t=e.index;for(let r of this.changes)t=t.edit(r.pos,r.deleteLen,r.insertedText);e=new sTe(this.currentVersion+1,this,t,this.changes),this.currentVersion=e.version,this.versions[this.currentVersionToIndex()]=e,this.changes=[],this.currentVersion-this.minVersion>=yie.maxVersions&&(this.minVersion=this.currentVersion-yie.maxVersions+1)}return e}getSnapshotVersion(){return this._getSnapshot().version}getAbsolutePositionAndLineText(e){return this._getSnapshot().index.lineNumberToInfo(e)}lineOffsetToPosition(e,t){return this._getSnapshot().index.absolutePositionOfStartOfLine(e)+(t-1)}positionToLineOffset(e){return this._getSnapshot().index.positionToLineOffset(e)}lineToTextSpan(e){let t=this._getSnapshot().index,{lineText:r,absolutePosition:s}=t.lineNumberToInfo(e+1),a=r!==void 0?r.length:t.absolutePositionOfStartOfLine(e+2)-s;return qp(s,a)}getTextChangesBetweenVersions(e,t){if(e<t)if(e>=this.minVersion){let r=[];for(let s=e+1;s<=t;s++){let a=this.versions[this.versionToIndex(s)];for(let d of a.changesSincePreviousVersion)r.push(d.getTextChangeRange())}return ise(r)}else return;else return Mz}getLineCount(){return this._getSnapshot().index.getLineCount()}static fromString(e){let t=new yie,r=new sTe(0,t,new Mce);t.versions[t.currentVersion]=r;let s=Mce.linesFromText(e);return r.index.load(s.lines),t}};FMe.changeNumberThreshold=8,FMe.changeLengthThreshold=256,FMe.maxVersions=8;var Rce=FMe,sTe=class eJt{constructor(e,t,r,s=qv){this.version=e,this.cache=t,this.index=r,this.changesSincePreviousVersion=s}getText(e,t){return this.index.getText(e,t-e)}getLength(){return this.index.getLength()}getChangeRange(e){if(e instanceof eJt&&this.cache===e.cache)return this.version<=e.version?Mz:this.cache.getTextChangesBetweenVersions(e.version,this.version)}},Mce=class m4t{constructor(){this.checkEdits=!1}absolutePositionOfStartOfLine(e){return this.lineNumberToInfo(e).absolutePosition}positionToLineOffset(e){let{oneBasedLine:t,zeroBasedColumn:r}=this.root.charOffsetToLineInfo(1,e);return{line:t,offset:r+1}}positionToColumnAndLineText(e){return this.root.charOffsetToLineInfo(1,e)}getLineCount(){return this.root.lineCount()}lineNumberToInfo(e){let t=this.getLineCount();if(e<=t){let{position:r,leaf:s}=this.root.lineNumberToInfo(e,0);return{absolutePosition:r,lineText:s&&s.text}}else return{absolutePosition:this.root.charCount(),lineText:void 0}}load(e){if(e.length>0){let t=[];for(let r=0;r<e.length;r++)t[r]=new Pj(e[r]);this.root=m4t.buildTreeFromBottom(t)}else this.root=new DB}walk(e,t,r){this.root.walk(e,t,r)}getText(e,t){let r="";return t>0&&e<this.root.charCount()&&this.walk(e,t,{goSubtree:!0,done:!1,leaf:(s,a,d)=>{r=r.concat(d.text.substring(s,s+a))}}),r}getLength(){return this.root.charCount()}every(e,t,r){r||(r=this.root.charCount());let s={goSubtree:!0,done:!1,leaf(a,d,p){e(p,a,d)||(this.done=!0)}};return this.walk(t,r-t,s),!s.done}edit(e,t,r){if(this.root.charCount()===0)return B.assert(t===0),r!==void 0?(this.load(m4t.linesFromText(r).lines),this):void 0;{let s;if(this.checkEdits){let p=this.getText(0,this.root.charCount());s=p.slice(0,e)+r+p.slice(e+t)}let a=new dHe,d=!1;if(e>=this.root.charCount()){e=this.root.charCount()-1;let p=this.getText(e,1);r?r=p+r:r=p,t=0,d=!0}else if(t>0){let p=e+t,{zeroBasedColumn:h,lineText:y}=this.positionToColumnAndLineText(p);h===0&&(t+=y.length,r=r?r+y:y)}if(this.root.walk(e,t,a),a.insertLines(r,d),this.checkEdits){let p=a.lineIndex.getText(0,a.lineIndex.getLength());B.assert(s===p,"buffer edit mismatch")}return a.lineIndex}}static buildTreeFromBottom(e){if(e.length<nre)return new DB(e);let t=new Array(Math.ceil(e.length/nre)),r=0;for(let s=0;s<t.length;s++){let a=Math.min(r+nre,e.length);t[s]=new DB(e.slice(r,a)),r=a}return this.buildTreeFromBottom(t)}static linesFromText(e){let t=zN(e);if(t.length===0)return{lines:[],lineMap:t};let r=new Array(t.length),s=t.length-1;for(let d=0;d<s;d++)r[d]=e.substring(t[d],t[d+1]);let a=e.substring(t[s]);return a.length>0?r[s]=a:r.pop(),{lines:r,lineMap:t}}},DB=class h4t{constructor(e=[]){this.children=e,this.totalChars=0,this.totalLines=0,e.length&&this.updateCounts()}isLeaf(){return!1}updateCounts(){this.totalChars=0,this.totalLines=0;for(let e of this.children)this.totalChars+=e.charCount(),this.totalLines+=e.lineCount()}execWalk(e,t,r,s,a){return r.pre&&r.pre(e,t,this.children[s],this,a),r.goSubtree?(this.children[s].walk(e,t,r),r.post&&r.post(e,t,this.children[s],this,a)):r.goSubtree=!0,r.done}skipChild(e,t,r,s,a){s.pre&&!s.done&&(s.pre(e,t,this.children[r],this,a),s.goSubtree=!0)}walk(e,t,r){if(this.children.length===0)return;let s=0,a=this.children[s].charCount(),d=e;for(;d>=a;)this.skipChild(d,t,s,r,0),d-=a,s++,a=this.children[s].charCount();if(d+t<=a){if(this.execWalk(d,t,r,s,2))return}else{if(this.execWalk(d,a-d,r,s,1))return;let p=t-(a-d);for(s++,a=this.children[s].charCount();p>a;){if(this.execWalk(0,a,r,s,3))return;p-=a,s++,a=this.children[s].charCount()}if(p>0&&this.execWalk(0,p,r,s,4))return}if(r.pre){let p=this.children.length;if(s<p-1)for(let h=s+1;h<p;h++)this.skipChild(0,0,h,r,5)}}charOffsetToLineInfo(e,t){if(this.children.length===0)return{oneBasedLine:e,zeroBasedColumn:t,lineText:void 0};for(let a of this.children){if(a.charCount()>t)return a.isLeaf()?{oneBasedLine:e,zeroBasedColumn:t,lineText:a.text}:a.charOffsetToLineInfo(e,t);t-=a.charCount(),e+=a.lineCount()}let r=this.lineCount();if(r===0)return{oneBasedLine:1,zeroBasedColumn:0,lineText:void 0};let s=B.checkDefined(this.lineNumberToInfo(r,0).leaf);return{oneBasedLine:r,zeroBasedColumn:s.charCount(),lineText:void 0}}lineNumberToInfo(e,t){for(let r of this.children){let s=r.lineCount();if(s>=e)return r.isLeaf()?{position:t,leaf:r}:r.lineNumberToInfo(e,t);e-=s,t+=r.charCount()}return{position:t,leaf:void 0}}splitAfter(e){let t,r=this.children.length;e++;let s=e;if(e<r){for(t=new h4t;e<r;)t.add(this.children[e]),e++;t.updateCounts()}return this.children.length=s,t}remove(e){let t=this.findChildIndex(e),r=this.children.length;if(t<r-1)for(let s=t;s<r-1;s++)this.children[s]=this.children[s+1];this.children.pop()}findChildIndex(e){let t=this.children.indexOf(e);return B.assert(t!==-1),t}insertAt(e,t){let r=this.findChildIndex(e),s=this.children.length,a=t.length;if(s<nre&&r===s-1&&a===1)return this.add(t[0]),this.updateCounts(),[];{let d=this.splitAfter(r),p=0;for(r++;r<nre&&p<a;)this.children[r]=t[p],r++,p++;let h=[],y=0;if(p<a){y=Math.ceil((a-p)/nre),h=new Array(y);let x=0;for(let D=0;D<y;D++)h[D]=new h4t;let E=h[0];for(;p<a;)E.add(t[p]),p++,E.children.length===nre&&(x++,E=h[x]);for(let D=h.length-1;D>=0;D--)h[D].children.length===0&&h.pop()}d&&h.push(d),this.updateCounts();for(let x=0;x<y;x++)h[x].updateCounts();return h}}add(e){this.children.push(e),B.assert(this.children.length<=nre)}charCount(){return this.totalChars}lineCount(){return this.totalLines}},Pj=class{constructor(n){this.text=n}isLeaf(){return!0}walk(n,e,t){t.leaf(n,e,this)}charCount(){return this.text.length}lineCount(){return 1}},Phe=class tJt{constructor(e,t,r,s,a,d){this.telemetryEnabled=e,this.logger=t,this.host=r,this.globalTypingsCacheLocation=s,this.event=a,this.maxActiveRequestCount=d,this.activeRequestCount=0,this.requestQueue=Ab(),this.requestMap=new Map,this.requestedRegistry=!1,this.packageInstallId=0}isKnownTypesPackageName(e){var t;return $R.validatePackageName(e)!==$R.NameValidationResult.Ok?!1:(this.requestedRegistry||(this.requestedRegistry=!0,this.installer.send({kind:"typesRegistry"})),!!((t=this.typesRegistryCache)!=null&&t.has(e)))}installPackage(e){this.packageInstallId++;let t={kind:"installPackage",...e,id:this.packageInstallId},r=new Promise((s,a)=>{(this.packageInstalledPromise??(this.packageInstalledPromise=new Map)).set(this.packageInstallId,{resolve:s,reject:a})});return this.installer.send(t),r}attach(e){this.projectService=e,this.installer=this.createInstallerProcess()}onProjectClosed(e){this.installer.send({projectName:e.getProjectName(),kind:"closeProject"})}enqueueInstallTypingsRequest(e,t,r){let s=NEe(e,t,r);this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling throttled operation:${Z9(s)}`),this.activeRequestCount<this.maxActiveRequestCount?this.scheduleRequest(s):(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Deferring request for: ${s.projectName}`),this.requestQueue.enqueue(s),this.requestMap.set(s.projectName,s))}handleMessage(e){var t,r;switch(this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Received response:${Z9(e)}`),e.kind){case mSe:this.typesRegistryCache=new Map(Object.entries(e.typesRegistry));break;case x_e:{let s=(t=this.packageInstalledPromise)==null?void 0:t.get(e.id);B.assertIsDefined(s,"Should find the promise for package install"),(r=this.packageInstalledPromise)==null||r.delete(e.id),e.success?s.resolve({successMessage:e.message}):s.reject(e.message),this.projectService.updateTypingsForProject(e),this.event(e,"setTypings");break}case X8:{let s={message:e.message};this.event(s,"typesInstallerInitializationFailed");break}case hSe:{let s={eventId:e.eventId,packages:e.packagesToInstall};this.event(s,"beginInstallTypes");break}case oK:{if(this.telemetryEnabled){let d={telemetryEventName:"typingsInstalled",payload:{installedPackages:e.packagesToInstall.join(","),installSuccess:e.installSuccess,typingsInstallerVersion:e.typingsInstallerVersion}};this.event(d,"telemetry")}let s={eventId:e.eventId,packages:e.packagesToInstall,success:e.installSuccess};this.event(s,"endInstallTypes");break}case S_e:{this.projectService.updateTypingsForProject(e);break}case Zte:{for(this.activeRequestCount>0?this.activeRequestCount--:B.fail("TIAdapter:: Received too many responses");!this.requestQueue.isEmpty();){let s=this.requestQueue.dequeue();if(this.requestMap.get(s.projectName)===s){this.requestMap.delete(s.projectName),this.scheduleRequest(s);break}this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Skipping defunct request for: ${s.projectName}`)}this.projectService.updateTypingsForProject(e),this.event(e,"setTypings");break}case Qoe:this.projectService.watchTypingLocations(e);break;default:}}scheduleRequest(e){this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Scheduling request for: ${e.projectName}`),this.activeRequestCount++,this.host.setTimeout(()=>{this.logger.hasLevel(3)&&this.logger.info(`TIAdapter:: Sending request:${Z9(e)}`),this.installer.send(e)},tJt.requestDelayMillis,`${e.projectName}::${e.kind}`)}};Phe.requestDelayMillis=100;var fHe=Phe,pHe={};T(pHe,{ActionInvalidate:()=>S_e,ActionPackageInstalled:()=>x_e,ActionSet:()=>Zte,ActionWatchTypingLocations:()=>Qoe,Arguments:()=>gSe,AutoImportProviderProject:()=>HEe,AuxiliaryProject:()=>UEe,CharRangeSection:()=>VK,CloseFileWatcherEvent:()=>Ice,CommandNames:()=>fot,ConfigFileDiagEvent:()=>Tce,ConfiguredProject:()=>JEe,ConfiguredProjectLoadKind:()=>Che,CreateDirectoryWatcherEvent:()=>Dce,CreateFileWatcherEvent:()=>bhe,Errors:()=>HL,EventBeginInstallTypes:()=>hSe,EventEndInstallTypes:()=>oK,EventInitializationFailed:()=>X8,EventTypesRegistry:()=>mSe,ExternalProject:()=>yhe,GcTimer:()=>FEe,InferredProject:()=>HVe,LargeFileReferencedEvent:()=>Ece,LineIndex:()=>Mce,LineLeaf:()=>Pj,LineNode:()=>DB,LogLevel:()=>yMe,Msg:()=>$v,OpenFileInfoTelemetryEvent:()=>vhe,Project:()=>QQ,ProjectInfoTelemetryEvent:()=>Ace,ProjectKind:()=>XQ,ProjectLanguageServiceStateEvent:()=>Cce,ProjectLoadingFinishEvent:()=>xce,ProjectLoadingStartEvent:()=>ere,ProjectService:()=>wMe,ProjectsUpdatedInBackgroundEvent:()=>Zne,ScriptInfo:()=>$Q,ScriptVersionCache:()=>Rce,Session:()=>bot,TextStorage:()=>SMe,ThrottledOperations:()=>OEe,TypingsInstallerAdapter:()=>fHe,allFilesAreJsOrDts:()=>jEe,allRootFilesAreJsOrDts:()=>VVe,asNormalizedPath:()=>KQ,convertCompilerOptions:()=>Ij,convertFormatOptions:()=>zK,convertScriptKindName:()=>Pce,convertTypeAcquisition:()=>tre,convertUserPreferences:()=>xhe,convertWatchOptions:()=>GK,countEachFileTypes:()=>Dj,createInstallTypingsRequest:()=>NEe,createModuleSpecifierCache:()=>tTe,createNormalizedPathMap:()=>RVe,createPackageJsonCache:()=>nTe,createSortedArray:()=>LEe,emptyArray:()=>qv,findArgument:()=>qet,formatDiagnosticToProtocol:()=>AB,formatMessage:()=>kMe,getBaseConfigFileName:()=>mhe,getDetailWatchInfo:()=>XEe,getLocationInNewDocument:()=>cHe,hasArgument:()=>Ket,hasNoTypeScriptSource:()=>zEe,indent:()=>ene,isBackgroundProject:()=>VU,isConfigFile:()=>tHe,isConfiguredProject:()=>Vw,isDynamicFileName:()=>qQ,isExternalProject:()=>Dk,isInferredProject:()=>UU,isInferredProjectName:()=>vMe,isProjectDeferredClose:()=>HU,makeAutoImportProviderProjectName:()=>REe,makeAuxiliaryProjectName:()=>MEe,makeInferredProjectName:()=>kEe,maxFileSize:()=>Sce,maxProgramSizeForNonTsFiles:()=>ZQ,normalizedPathToPath:()=>y_,nowString:()=>$et,nullCancellationToken:()=>NMe,nullTypingsInstaller:()=>The,protocol:()=>hhe,scriptInfoIsContainedByBackgroundProject:()=>UVe,scriptInfoIsContainedByDeferredClosedProject:()=>WEe,stringifyIndented:()=>Z9,toEvent:()=>rHe,toNormalizedPath:()=>vp,tryConvertScriptKindName:()=>She,typingsInstaller:()=>gMe,updateProjectIfDirty:()=>mI}),typeof console<"u"&&(B.loggingHost={log(n,e){switch(n){case 1:return console.error(e);case 2:return console.warn(e);case 3:return console.log(e);case 4:return console.log(e)}}})})({get exports(){return qHt},set exports(u){qHt=u,typeof bvt<"u"&&bvt.exports&&(bvt.exports=u)}})});function Svt(u){if(!qmn)return()=>{};let i=u||"Profiler",l=process.hrtime.bigint(),_=l;return(v,T)=>{let P=process.hrtime.bigint(),O=Number(P-l)/1e6,V=Number(P-_)/1e6;_=P;let K={stage:v,sinceStartMs:O,sinceLastMs:V,...T||{}};try{console.log(`[${i}][PROFILE]`,JSON.stringify(K))}catch{console.log(`[${i}][PROFILE]`,K)}}}var qmn,g4t=_c(()=>{"use strict";qmn=process.env.AST_FIND_NODES_PROFILING==="1"});var xvt,sXe,nJt,$mn,rZ,aXe=_c(()=>{"use strict";xvt=ll(MI()),sXe=ll(v6e()),nJt=ll(require("fs"));g4t();$mn={target:sXe.default.ScriptTarget.ESNext,module:sXe.default.ModuleKind.ESNext,moduleResolution:sXe.default.ModuleResolutionKind.NodeNext,jsx:sXe.default.JsxEmit.React,allowJs:!0,checkJs:!1,skipLibCheck:!0,skipDefaultLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,resolveJsonModule:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,useDefineForClassFields:!1,noEmit:!0},rZ=class u{static getDefaultCompilerOptions(){return{...$mn}}static getSupportedEditCompilerOptions(){return{allowJs:!0}}static initializeProject(i,l){let _=Svt("ProjectInit");if(_("start",{projectPath:i}),l)return _("usingTestProject"),l;let v=`${i}/tsconfig.json`,T={},P=!1;try{nJt.existsSync(v)?(P=!0,T.tsConfigFilePath=v,T.skipAddingFilesFromTsConfig=!0,T.compilerOptions=u.getSupportedEditCompilerOptions()):T.compilerOptions=u.getDefaultCompilerOptions()}catch{T.useInMemoryFileSystem=!0,T.compilerOptions=u.getDefaultCompilerOptions()}_("tsconfigChecked",{hasTsconfig:P});let O;try{_("projectConstruct.start"),O=new xvt.Project(T),_("projectConstruct.complete")}catch(V){console.log("Failed to load tsconfig, using defaults:",V.message),delete T.tsConfigFilePath,T.compilerOptions=u.getDefaultCompilerOptions(),_("projectConstruct.retry.start",{reason:V?.message}),O=new xvt.Project(T),_("projectConstruct.retry.complete")}return _("lazyMode.enabled",{hasTsconfig:P}),_("complete",{sourceFiles:O.getSourceFiles().length}),O}static createProject(i){return new xvt.Project(i)}static getProjectStats(i){let l=i.getSourceFiles(),_=0,v=0,T=0;for(let P of l)_+=P.getFunctions().length,v+=P.getClasses().length,T+=P.getInterfaces().length;return{sourceFiles:l.length,functions:_,classes:v,interfaces:T}}}});function y4t(u,i){return{...u,allowJs:!0,jsx:u.jsx??TD.default.JsxEmit.React,skipLibCheck:u.skipLibCheck??!0,skipDefaultLibCheck:u.skipDefaultLibCheck??!0,baseUrl:u.baseUrl??i}}function Qmn(u){let i=TD.default.findConfigFile(u,TD.default.sys.fileExists,"tsconfig.json");if(!i)return{options:y4t({},u),fileNames:[]};let l=TD.default.readConfigFile(i,TD.default.sys.readFile),_={...l.config||{},compilerOptions:{...l.config&&l.config.compilerOptions||{},allowJs:!0}},v=TD.default.parseJsonConfigFileContent(_,TD.default.sys,vO.dirname(i));return{options:y4t(v.options,vO.dirname(i)),fileNames:v.fileNames}}function b4t(u,i,l,_,v){let T={getCompilationSettings:()=>u,getScriptFileNames:()=>Array.from(i),getScriptVersion:P=>l.get(vO.resolve(P))||"0",getScriptSnapshot:P=>{try{let O=vO.resolve(P);if(!b6e.existsSync(O))return;if(v>0)try{if(b6e.statSync(O).size>v)return}catch{return}return TD.default.ScriptSnapshot.fromString(b6e.readFileSync(O,"utf8"))}catch{return}},fileExists:TD.default.sys.fileExists,readFile:TD.default.sys.readFile,readDirectory:TD.default.sys.readDirectory,getDirectories:TD.default.sys.getDirectories,directoryExists:TD.default.sys.directoryExists,getCurrentDirectory:()=>vO.resolve(_),getDefaultLibFileName:P=>TD.default.getDefaultLibFilePath(P),realpath:TD.default.sys.realpath?TD.default.sys.realpath.bind(TD.default.sys):void 0};return TD.default.createLanguageService(T,TD.default.createDocumentRegistry())}function Ymn(u){let i=vO.resolve(u),l=rJt.get(i);if(l)return l;let{options:_,fileNames:v}=Qmn(i),T=v.map(te=>vO.resolve(te)),P=new Set(T),O=new Map,K={ls:b4t(_,P,O,i,v4t),options:_,fileNames:T,versions:O,filesSet:P};return rJt.set(i,K),K}function Zmn(u){let i=TD.default.readConfigFile(u,TD.default.sys.readFile),l={...i.config||{},compilerOptions:{...i.config&&i.config.compilerOptions||{},allowJs:!0}},_=TD.default.parseJsonConfigFileContent(l,TD.default.sys,vO.dirname(u));return{options:y4t(_.options,vO.dirname(u)),fileNames:_.fileNames}}function sJt(u){let i=vO.dirname(u);try{return TD.default.findConfigFile(i,TD.default.sys.fileExists,"tsconfig.json")||void 0}catch{return}}function Evt(u,i){let l=sJt(i);if(!l)return Ymn(u);let _=vO.resolve(l),v=iJt.get(_);if(v)return v;let{options:T,fileNames:P}=Zmn(_),O=new Set(P.map(oe=>vO.resolve(oe))),V=new Map,te={ls:b4t(T,O,V,vO.dirname(_),v4t),options:T,fileNames:Array.from(O),versions:V,filesSet:O};return iJt.set(_,te),te}function aJt(u,i){let l=Evt(u,i),_=vO.resolve(i);if(!l.filesSet.has(_)){l.filesSet.add(_),l.versions.has(_)||l.versions.set(_,"0"),l.ls.dispose?.();let v=sJt(_),T=v?vO.dirname(v):u;l.ls=b4t(l.options,l.filesSet,l.versions,T,v4t)}}function oJt(u,i){let l=Evt(u,i),_=vO.resolve(i),v=l.versions.get(_)||"0",T=String(Number(v)+1);l.versions.set(_,T)}var TD,vO,b6e,Xmn,v4t,rJt,iJt,lJt=_c(()=>{"use strict";TD=ll(v6e()),vO=ll(require("path")),b6e=ll(require("fs"));aXe();Xmn=10*1024*1024,v4t=(()=>{let u=process.env.PANDO_LS_MAX_FILE_BYTES??process.env.AST_LS_MAX_FILE_BYTES,i=u?Number(u):NaN;return Number.isFinite(i)&&i>0?i:Xmn})(),rJt=new Map,iJt=new Map});function thn(u){return[oW.default.join(u,".ssh"),oW.default.join(u,".aws"),oW.default.join(u,".gnupg"),oW.default.join(u,".config"),oW.default.join(u,".pando-ai"),oW.default.join(u,".pando-data"),oW.default.join(u,"Library")]}function nhn(u){return["/",u,"/Users","/home"]}function oXe(u){let i=oW.default.resolve(u);return i.length>1&&i.endsWith(oW.default.sep)?i.slice(0,-1):i}function S4t(u,i){if(u===i)return!0;let l=oW.default.relative(i,u);return l!==""&&!l.startsWith("..")&&!oW.default.isAbsolute(l)}function rhn(u,i){let l=oXe(i?.home??uJt.default.homedir()),_=oXe(u),v=process.env.PANDO_ALLOW_TEMP_ROOTS==="1",T=new Set(["/var","/private/var"]),P=nhn(l).map(oXe);for(let V of P)if(_===V)return V;for(let V of P)if(S4t(V,_))return V;let O=[...v?cJt.filter(V=>!T.has(V)):cJt,...v?[]:ehn,...thn(l)].map(oXe);for(let V of O)if(S4t(_,V)||S4t(V,_))return V;for(let V of["/Users","/home"].map(oXe)){let K=oW.default.relative(V,_);if(K&&!K.startsWith("..")&&!oW.default.isAbsolute(K)&&K.split(oW.default.sep).filter(Boolean).length===1)return V}return null}function x4t(u,i){return rhn(u,i)!==null}var uJt,oW,cJt,ehn,dJt=_c(()=>{"use strict";uJt=ll(require("os")),oW=ll(require("path")),cJt=["/usr","/bin","/sbin","/System","/Library","/etc","/private/etc","/var","/private/var","/opt","/dev","/Applications"],ehn=["/Volumes","/mnt","/media","/srv","/tmp","/private/tmp","/private/var/folders"]});var vJt={};SD(vJt,{PANDO_DATA_DIRNAME:()=>lXe,addWorkspaceExtraRoot:()=>yhn,canonicalizeProjectRoot:()=>k7,computeWorkspaceIdentity:()=>Que,getCanonicalRepoRoot:()=>E4t,getCanonicalStorageRoot:()=>uhn,getPandoDataDir:()=>Sy,getPandoFtsChunkPath:()=>xhn,getPandoHistoryDir:()=>cXe,getPandoHomeDir:()=>x6e,getPandoIndexChunkPath:()=>bO,getPandoMetaDbPath:()=>E6e,getPandoSnapshotsDbPath:()=>uXe,getWorkspaceExtraRoots:()=>ghn,getWorkspaceId:()=>bhn,removeWorkspaceExtraRoot:()=>vhn,workspaceDataDirForRoot:()=>Shn});function x6e(){return process.env.PANDO_DATA_DIR||qT.default.join(fJt.default.homedir(),lXe)}function _Jt(u){let i=u,l=qT.default.parse(i);for(;i.length>l.root.length&&/[\\/]+$/.test(i);)i=i.replace(/[\\/]+$/,"");return i}function k7(u){let i=qT.default.resolve(u),l=i;try{let _=sz.default.realpathSync.native;l=typeof _=="function"?_(i):sz.default.realpathSync(i)}catch{}return _Jt(l)}function ihn(u){let i=u.trim().replace(/\.git$/,"");if(!i)return null;let l=i.match(/^git@([^:]+):(.+)$/);if(l){let _=l[1],T=l[2].replace(/^\/+/,"").split("/");if(T.length>=2)return`${_}/${T[0]}/${T[1]}`}try{let _=new URL(i),v=_.hostname,P=_.pathname.replace(/^\/+/,"").split("/");if(v&&P.length>=2)return`${v}/${P[0]}/${P[1]}`}catch{}return null}function Tvt(u){return pJt.default.createHash("sha1").update(u).digest("hex").slice(0,12)}function shn(u){return u.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function ahn(u,i){let l=qT.default.basename(_Jt(u));return`${shn(l)}-${i}`}function mJt(){return qT.default.join(x6e(),"workspace-registry.json")}function hJt(u){return qT.default.join(x6e(),"workspaces",u.dirName,"workspace-state.json")}function S6e(u){try{return sz.default.readFileSync(u,"utf8").trim()}catch{return null}}function gJt(u){let i=qT.default.join(u,".git");try{let l=sz.default.statSync(i);if(l.isDirectory())return i;if(l.isFile()){let v=S6e(i)?.match(/^gitdir:\s*(.+)$/i);if(v){let T=v[1].trim();return qT.default.isAbsolute(T)?T:qT.default.resolve(u,T)}}}catch{return null}return null}function ohn(u){let i=qT.default.join(u,"commondir"),l=S6e(i);if(!l)return k7(u);let _=qT.default.isAbsolute(l)?l:qT.default.resolve(u,l);return k7(_)}function lhn(u){return k7(qT.default.join(u,"objects"))}function chn(u){let i=k7(u);for(;;){let l=qT.default.join(i,".git");if(sz.default.existsSync(l))return i;let _=qT.default.dirname(i);if(_===i)break;i=_}return null}function E4t(u){let i=k7(u),l=chn(i);return l?k7(l):null}function uhn(u){return E4t(u)??k7(u)}function dhn(u){let i=qT.default.join(u,"config"),l=S6e(i);if(!l)return null;let _=l.split(/\r?\n/),v=!1,T=null;for(let P of _){if(P.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){v=!0;continue}if(P.startsWith("[")&&(v=!1),v){let V=P.match(/^\s*url\s*=\s*(.+)$/);if(V&&(T=V[1].trim(),T))return T}}return T}function fhn(u){let i=qT.default.join(u,"HEAD"),l=S6e(i);if(!l)return{branch:null,commit:null};if(l.startsWith("ref:")){let _=l.replace("ref:","").trim(),v=_.split("/").slice(-1)[0]||null,T=qT.default.join(u,_),P=S6e(T);if(!P){let O=S6e(qT.default.join(u,"packed-refs"));if(O){let V=O.split(/\r?\n/).find(K=>K.endsWith(` ${_}`));V&&(P=V.split(" ")[0])}}return{branch:v,commit:P||null}}return{branch:"HEAD",commit:l||null}}function phn(){try{let u=sz.default.readFileSync(mJt(),"utf8"),i=JSON.parse(u);if(i&&i.version===1&&i.entries&&typeof i.entries=="object")return{version:1,entries:i.entries}}catch{}return{version:1,entries:{}}}function _hn(u){let i=mJt(),l=qT.default.dirname(i);sz.default.mkdirSync(l,{recursive:!0});let _=`${i}.${process.pid}.${Date.now()}.tmp`;sz.default.writeFileSync(_,`${JSON.stringify(u,null,2)}
|
|
32186
32186
|
`,"utf8"),sz.default.renameSync(_,i)}function T4t(u){try{let i=sz.default.readFileSync(hJt(u),"utf8"),l=JSON.parse(i);if(l&&l.version===1&&(l.extraRoots===void 0||Array.isArray(l.extraRoots)))return{version:1,extraRoots:l.extraRoots,updatedAt:typeof l.updatedAt=="string"?l.updatedAt:void 0}}catch{}return{version:1,extraRoots:[]}}function yJt(u,i){let l=hJt(u),_=qT.default.dirname(l);sz.default.mkdirSync(_,{recursive:!0});let v=`${l}.${process.pid}.${Date.now()}.tmp`;sz.default.writeFileSync(v,`${JSON.stringify(i,null,2)}
|
|
32187
|
-
`,"utf8"),sz.default.renameSync(v,l)}function mhn(u,i){if(!i)return{canonicalRepoRoot:u,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${u}`};let l=gJt(i),_=l?ohn(l):null,v=_?lhn(_):null;return{canonicalRepoRoot:i,gitCommonDir:_,gitObjectDir:v,fingerprint:["git",`root:${i}`,`common:${_??""}`,`objects:${v??""}`].join("|")}}function hhn(u){
|
|
32187
|
+
`,"utf8"),sz.default.renameSync(v,l)}function mhn(u,i){if(!i)return{canonicalRepoRoot:u,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${u}`};let l=gJt(i),_=l?ohn(l):null,v=_?lhn(_):null;return{canonicalRepoRoot:i,gitCommonDir:_,gitObjectDir:v,fingerprint:["git",`root:${i}`,`common:${_??""}`,`objects:${v??""}`].join("|")}}function hhn(u){try{let i=phn();i.entries[u.storageRoot]={workspaceId:u.id,workspaceDirName:u.dirName,locationId:u.locationId,incarnationId:u.incarnationId,canonicalProjectRoot:u.canonicalProjectRoot,canonicalRepoRoot:u.canonicalRepoRoot,storageRoot:u.storageRoot,repoIdentity:u.repoIdentity??null,gitCommonDir:u.gitCommonDir??null,gitObjectDir:u.gitObjectDir??null,remote:u.remote??null,branch:u.branch??null,commit:u.commit??null,updatedAt:new Date().toISOString()},_hn(i)}catch{}}function ghn(u){try{let i=Que(u),_=T4t(i).extraRoots;if(!Array.isArray(_))return[];let v=i.canonicalProjectRoot,T=new Set,P=[];for(let O of _){if(typeof O!="string")continue;let V=k7(O);V===v||T.has(V)||x4t(V)||(T.add(V),P.push(V))}return P}catch{return[]}}function yhn(u,i){let l=Que(u),_=k7(i);if(_===l.canonicalProjectRoot||x4t(_))return!1;let v=T4t(l),P=(Array.isArray(v.extraRoots)?v.extraRoots:[]).map(O=>k7(O));return P.includes(_)?!1:(yJt(l,{version:1,extraRoots:[...P,_],updatedAt:new Date().toISOString()}),!0)}function vhn(u,i){let l=Que(u),_=k7(i),v=T4t(l);if(!Array.isArray(v.extraRoots))return!1;let T=v.extraRoots.map(P=>k7(P)).filter((P,O,V)=>P!==_&&V.indexOf(P)===O);return T.length===v.extraRoots.length?!1:(yJt(l,{version:1,extraRoots:T,updatedAt:new Date().toISOString()}),!0)}function Que(u){let i=k7(u),l=E4t(i),_=l??i,v=l,T=Tvt(_),P=mhn(_,v),O=Tvt(P.fingerprint),V=`ws-${Tvt(`${T}:${O}`)}`,K=ahn(_,V);if(!v)return{id:V,dirName:K,locationId:T,incarnationId:O,canonicalProjectRoot:i,canonicalRepoRoot:_,storageRoot:_,gitCommonDir:P.gitCommonDir,gitObjectDir:P.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let te=gJt(v),oe=te?dhn(te):null,q=oe?ihn(oe):null,Ie=te?fhn(te):{branch:null,commit:null};return{id:V,dirName:K,locationId:T,incarnationId:O,canonicalProjectRoot:i,canonicalRepoRoot:v,storageRoot:_,gitCommonDir:P.gitCommonDir,gitObjectDir:P.gitObjectDir,repoIdentity:q??`local:${Tvt(_)}`,remote:oe,branch:Ie.branch,commit:Ie.commit}}function bhn(u){return Que(u).id}function Sy(u){let i=Que(u);return hhn(i),qT.default.join(x6e(),"workspaces",i.dirName)}function Shn(u,i){let l=Que(i);return qT.default.join(u,"workspaces",l.dirName)}function E6e(u){return qT.default.join(Sy(u),"meta.db")}function cXe(u){return qT.default.join(Sy(u),"history")}function bO(u,i){return qT.default.join(Sy(u),`.pando-index-chunk-${i}.db`)}function xhn(u,i){return qT.default.join(Sy(u),`.pando-fts-chunk-${i}.db`)}function uXe(u){return qT.default.join(Sy(u),".pando-snapshots.db")}var qT,fJt,sz,pJt,lXe,FM=_c(()=>{"use strict";qT=ll(require("path")),fJt=ll(require("os")),sz=ll(require("fs")),pJt=ll(require("crypto"));dJt();lXe=".pando-data"});function SJt(){let u=process.env.PANDO_LOG_DIR||process.env.PANDO_WORKSPACE_DATA_DIR;if(u)return u;try{return x6e()}catch{let l=typeof C4t.default.homedir=="function"?C4t.default.homedir():process.env.HOME;if(l)return Cvt.default.join(l,lXe)}let i=process.env.HOME||process.cwd();return Cvt.default.join(i,lXe)}function Thn(){return Cvt.default.join(SJt(),"pando.log")}function whn(){try{A4t.default.mkdirSync(SJt(),{recursive:!0})}catch{}}function Nhn(u){if(u!==void 0)try{return typeof u=="string"?u:(0,bJt.inspect)(u,{depth:null,breakLength:1/0,maxArrayLength:1/0})}catch{try{return JSON.stringify(u)}catch{return String(u)}}}function $T(){return Dvt}function Rhn(u){return Dvt?Phn.has(u)?Dhn:!(!Ahn&&Ihn.has(u)):!1}function Su(u,i,l){if(!Rhn(u))return;let _=new Date().toISOString(),v=Nhn(l),T=v?`[${_}] [${u}] ${i} :: ${v}`:`[${_}] [${u}] ${i}`;if(!khn&&!process.env.PANDO_QUIET)try{process.stderr.write(T+`
|
|
32188
32188
|
`)}catch{}try{whn(),A4t.default.appendFileSync(Thn(),T+`
|
|
32189
32189
|
`,"utf8")}catch{}}var A4t,C4t,Cvt,bJt,Ehn,Avt,Chn,Dvt,Ahn,Dhn,Ihn,Phn,khn,XT=_c(()=>{"use strict";A4t=ll(require("fs")),C4t=ll(require("os")),Cvt=ll(require("path"));FM();bJt=require("util"),Ehn=require("crypto");Avt=u=>{if(u==null)return!1;let i=u.trim().toLowerCase();return i!=="0"&&i!=="false"&&i!=="off"&&i!=="no"},Chn=Avt(process.env.PANDO_LOG_DISABLED),Dvt=!Chn&&(process.env.PANDO_DEBUG==null||Avt(process.env.PANDO_DEBUG)),Ahn=Dvt&&(process.env.PANDO_INDEX_HOT_LOG==null||Avt(process.env.PANDO_INDEX_HOT_LOG)),Dhn=Dvt&&(process.env.PANDO_INDEX_TIMING==null||Avt(process.env.PANDO_INDEX_TIMING)),Ihn=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),Phn=new Set(["IndexTiming"]);khn=!1});function D4t(u,i){$T()&&Su("ClojureTrace",u,i)}var Ivt,xJt=_c(()=>{"use strict";lJt();XT();Ivt=class{constructor(i,l){this.fileStates=new Map;this.operationMetadata=new WeakMap;this.project=i,this.projectRoot=l,this.ls={getForFile:_=>Evt(this.projectRoot,_),ensureInProgram:_=>aJt(this.projectRoot,_),bump:_=>oJt(this.projectRoot,_)}}setQueryLayer(i){this._queries=i}get queries(){return this._queries}getOperationMetadata(i,l){return this.operationMetadata.get(i)?.get(l)}setOperationMetadata(i,l,_){let v=this.operationMetadata.get(i);v||(v=new Map,this.operationMetadata.set(i,v)),v.set(l,_)}clearOperationMetadata(i,l){if(l==null){this.operationMetadata.delete(i);return}let _=this.operationMetadata.get(i);_&&(_.delete(l),_.size===0&&this.operationMetadata.delete(i))}setLspHost(i){this._lspHost=i}get lsp(){if(!this._lspHost)try{let{CodeEngineFactory:i}=(eDe(),Pp(T6e)),l=i.getEngineOptions(this.projectRoot);l?.lspHost&&(this._lspHost=l.lspHost,D4t("ExecutionContext.lsp recovered host from engine options",{projectRoot:this.projectRoot,hasHost:!0}))}catch{}return this._lspHost?D4t("ExecutionContext.lsp returning host",{projectRoot:this.projectRoot,lspType:this._lspHost?.constructor?.name??typeof this._lspHost,hasReferences:!!this._lspHost?.references,hasRename:!!this._lspHost?.rename,hasWorkspaceFilesChanged:!!this._lspHost?.workspaceFilesChanged}):D4t("ExecutionContext.lsp returning undefined host",{projectRoot:this.projectRoot}),this._lspHost}saveFileState(i){let l=this.project.getSourceFile(i);l&&this.fileStates.set(i,l.getFullText())}saveFileStates(i){for(let l of i)this.saveFileState(l)}getSavedFilePaths(){return Array.from(this.fileStates.keys())}restoreFileStates(){for(let[i,l]of this.fileStates){let _=this.project.getSourceFile(i);_&&_.replaceWithText(l)}this.fileStates.clear()}}});var BV={};SD(BV,{Database:()=>wvt,Statement:()=>Pvt,default:()=>GS});var EJt,Pvt,wvt,GS,CD=_c(()=>{"use strict";EJt=require("node:sqlite"),Pvt=class{constructor(i){this.statement=i}run(...i){let l=this.statement.run(...i);return{changes:l.changes,lastInsertRowid:l.lastInsertRowid}}get(...i){let l=this.statement.get(...i);return l??void 0}all(...i){return this.statement.all(...i)}iterate(...i){return this.statement.iterate(...i)}setAllowBareNamedParameters(i){return this.statement.setAllowBareNamedParameters(i),this}setReadBigInts(i){return this.statement.setReadBigInts(i),this}},wvt=class u{constructor(i,l){this.file=i;this.transactionDepth=0;let _=l??{},v=!!(_.readOnly??_.readonly);this.connectionId=u.nextId++,this.database=new EJt.DatabaseSync(i,{readOnly:v,fileMustExist:!!_.fileMustExist,timeout:typeof _.timeout=="number"?Math.max(0,Math.floor(_.timeout)):void 0});try{this.database.exec("PRAGMA temp_store = MEMORY")}catch{}}static{this.nextId=1}prepare(i){return new Pvt(this.database.prepare(i))}exec(i){this.database.exec(i)}close(){this.database.close()}getConnectionId(){return this.connectionId}pragma(i){return this.database.prepare(`PRAGMA ${i}`).all()}transaction(i){return(...l)=>{this.transactionDepth+=1;let _=this.transactionDepth;_===1&&this.database.exec("BEGIN");try{let v=i(...l);if(v instanceof Promise)throw new TypeError("SQLite transactions must be synchronous. Received a Promise.");return _===1&&this.database.exec("COMMIT"),v}catch(v){if(_===1)try{this.database.exec("ROLLBACK")}catch{}throw v}finally{this.transactionDepth=Math.max(0,this.transactionDepth-1)}}}loadExtension(){throw new Error("loadExtension is not supported by the embedded SQLite runtime")}},GS=wvt});var tDe,TJt,Mhn,dXe,CJt=_c(()=>{"use strict";tDe=ll(require("fs")),TJt=ll(require("path"));CD();FM();Mhn=2,dXe=class{constructor(i=process.cwd()){this.projectRoot=i,this.chunkDbPaths=[],this.discoverChunkDatabases()}discoverChunkDatabases(){let i=Sy(this.projectRoot),l;try{l=tDe.readdirSync(i)}catch{this.chunkDbPaths=[];return}let _=/^\.pando-index-chunk-\d+\.db$/;this.chunkDbPaths=l.filter(v=>_.test(v)).sort().map(v=>TJt.join(i,v))}getChunkPaths(){return[...this.chunkDbPaths]}async queryAllChunks(i,l=[],_={}){let v=Date.now();if(this.chunkDbPaths.length===0)return console.log("\u26A0\uFE0F No chunk databases found. Run indexing first."),[];console.log(`\u{1F50D} Querying ${this.chunkDbPaths.length} chunks in parallel...`);let T=this.chunkDbPaths.map(async(oe,q)=>this.queryChunk(oe,q,i,l)),P=await Promise.all(T),O=[],V=0,K=[];for(let oe of P)oe.error?K.push(`Chunk ${oe.chunkIndex}: ${oe.error}`):(O.push(...oe.results),V+=oe.queryTime);if(_.deduplicateBy){let oe=new Set;O=O.filter(q=>{let Ie=q[_.deduplicateBy];return oe.has(Ie)?!1:(oe.add(Ie),!0)})}if(_.orderBy){let oe=_.orderDirection==="DESC"?-1:1;O.sort((q,Ie)=>{let ye=q[_.orderBy],ve=Ie[_.orderBy];return ye<ve?-1*oe:ye>ve?1*oe:0})}_.offset&&(O=O.slice(_.offset)),_.limit&&(O=O.slice(0,_.limit));let te=Date.now()-v;return console.log(`\u2705 Distributed query complete: ${O.length} results in ${te}ms`),console.log(` \u{1F4CA} Avg chunk query time: ${(V/this.chunkDbPaths.length).toFixed(1)}ms`),K.length>0&&console.log(`\u26A0\uFE0F ${K.length} chunk errors:`,K),O}async queryChunk(i,l,_,v){let T=Date.now();try{if(!tDe.existsSync(i))return{chunkIndex:l,chunkPath:i,results:[],queryTime:0,error:`Database file not found: ${i}`};let P=new GS(i,{readonly:!0}),V=P.prepare(_).all(...v);P.close();let K=Date.now()-T;return{chunkIndex:l,chunkPath:i,results:V,queryTime:K}}catch(P){let O=Date.now()-T;return{chunkIndex:l,chunkPath:i,results:[],queryTime:O,error:`Query failed: ${P.message}`}}}async getStats(){console.log(`\u{1F4CA} Gathering statistics from ${this.chunkDbPaths.length} chunks...`);let i=`
|
|
32190
32190
|
SELECT
|
|
@@ -32925,7 +32925,7 @@ gpgsig`+g7t(P)+`
|
|
|
32925
32925
|
`)+`
|
|
32926
32926
|
`,"utf8");let K=O[O.length-1].split(" ")[1];await v.writeStashRef(K)}else await u.rm(V)})}async function lTn({fs:u,dir:i,gitdir:l}){return new BDe({fs:u,dir:i,gitdir:l}).readStashReflogs({parsed:!0})}async function cTn({fs:u,dir:i,gitdir:l}){let _=new BDe({fs:u,dir:i,gitdir:l}),v=[_.refStashPath,_.refLogsStashPath];await I4e(v,async()=>{await Promise.all(v.map(async T=>{if(await u.exists(T))return u.rm(T)}))})}async function uTn({fs:u,dir:i,gitdir:l,refIdx:_=0}){await snn({fs:u,dir:i,gitdir:l,refIdx:_}),await ann({fs:u,dir:i,gitdir:l,refIdx:_})}async function onn({fs:u,dir:i,gitdir:l=Wc(i,".git"),op:_="push",message:v="",refIdx:T=0}){Ua("fs",u),Ua("dir",i),Ua("gitdir",l),Ua("op",_);let P={push:aTn,apply:snn,drop:ann,list:lTn,clear:cTn,pop:uTn,create:oTn},O=["apply","drop","pop"];try{let V=new E_(u),K=await U_({fsp:V,dotgit:l});["refs","logs","logs/refs"].map(q=>Wc(K,q)).forEach(async q=>{await V.exists(q)||await V.mkdir(q)});let oe=P[_];if(oe){if(O.includes(_)&&T<0)throw new mZ(`stash@${T}`,"number that is in range of [0, num of stash pushed]");return await oe({fs:V,dir:i,gitdir:K,message:v,refIdx:T})}throw new Error(`To be implemented: ${_}`)}catch(V){throw V.caller="git.stash",V}}async function lnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),filepath:_,cache:v={}}){try{Ua("fs",u),Ua("gitdir",l),Ua("filepath",_);let T=new E_(u),P=await U_({fsp:T,dotgit:l});if(await cve.isIgnored({fs:T,gitdir:P,dir:i,filepath:_}))return"ignored";let V=await dTn({fs:T,cache:v,gitdir:P}),K=await cnn({fs:T,cache:v,gitdir:P,tree:V,path:_}),te=await RN.acquire({fs:T,gitdir:P,cache:v},async function(ft){for(let vt of ft)if(vt.path===_)return vt;return null}),oe=await T.lstat(Wc(i,_)),q=K!==null,Ie=te!==null,ye=oe!==null,ve=async()=>{if(Ie&&!kbt(te,oe))return te.oid;{let ft=await T.read(Wc(i,_)),vt=await Ztn({gitdir:P,type:"blob",object:ft});return Ie&&te.oid===vt&&oe.size!==-1&&RN.acquire({fs:T,gitdir:P,cache:v},async function(Tt){Tt.insert({filepath:_,stats:oe,oid:vt})}),vt}};if(!q&&!ye&&!Ie)return"absent";if(!q&&!ye&&Ie)return"*absent";if(!q&&ye&&!Ie)return"*added";if(!q&&ye&&Ie)return await ve()===te.oid?"added":"*added";if(q&&!ye&&!Ie)return"deleted";if(q&&!ye&&Ie)return K===te.oid,"*deleted";if(q&&ye&&!Ie)return await ve()===K?"*undeleted":"*undeletemodified";if(q&&ye&&Ie){let ft=await ve();return ft===K?ft===te.oid?"unmodified":"*unmodified":ft===te.oid?"modified":"*modified"}}catch(T){throw T.caller="git.status",T}}async function cnn({fs:u,cache:i,gitdir:l,tree:_,path:v}){typeof v=="string"&&(v=v.split("/"));let T=v.shift();for(let P of _)if(P.path===T){if(v.length===0)return P.oid;let{type:O,object:V}=await WI({fs:u,cache:i,gitdir:l,oid:P.oid});if(O==="tree"){let K=_z.from(V);return cnn({fs:u,cache:i,gitdir:l,tree:K,path:v})}if(O==="blob")throw new hW(P.oid,O,"blob",v.join("/"))}return null}async function dTn({fs:u,cache:i,gitdir:l}){let _;try{_=await lf.resolve({fs:u,gitdir:l,ref:"HEAD"})}catch(T){if(T instanceof LC)return[]}let{tree:v}=await k4e({fs:u,cache:i,gitdir:l,oid:_});return v}async function unn({fs:u,dir:i,gitdir:l=Wc(i,".git"),ref:_="HEAD",filepaths:v=["."],filter:T,cache:P={},ignored:O=!1}){try{Ua("fs",u),Ua("gitdir",l),Ua("ref",_);let V=new E_(u),K=await U_({fsp:V,dotgit:l});return await lve({fs:V,cache:P,dir:i,gitdir:K,trees:[XV({ref:_}),N4e(),WDe()],map:async function(te,[oe,q,Ie]){if(!oe&&!Ie&&q&&!O&&await cve.isIgnored({fs:V,dir:i,filepath:te})||!v.some(gt=>Ken(te,gt)))return null;if(T&&!T(te))return;let[ye,ve,ft]=await Promise.all([oe&&oe.type(),q&&q.type(),Ie&&Ie.type()]),vt=[ye,ve,ft].includes("blob");if((ye==="tree"||ye==="special")&&!vt)return;if(ye==="commit")return null;if((ve==="tree"||ve==="special")&&!vt)return;if(ft==="commit")return null;if((ft==="tree"||ft==="special")&&!vt)return;let Tt=ye==="blob"?await oe.oid():void 0,an=ft==="blob"?await Ie.oid():void 0,bn;ye!=="blob"&&ve==="blob"&&ft!=="blob"?bn="42":ve==="blob"&&(bn=await q.oid());let sn=[void 0,Tt,bn,an],Ut=sn.map(gt=>sn.indexOf(gt));return Ut.shift(),[te,...Ut]}})}catch(V){throw V.caller="git.statusMatrix",V}}async function dnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),ref:_,object:v,force:T=!1}){try{Ua("fs",u),Ua("gitdir",l),Ua("ref",_);let P=new E_(u);if(_===void 0)throw new pz("ref");_=_.startsWith("refs/tags/")?_:`refs/tags/${_}`;let O=await U_({fsp:P,dotgit:l}),V=await lf.resolve({fs:P,gitdir:O,ref:v||"HEAD"});if(!T&&await lf.exists({fs:P,gitdir:O,ref:_}))throw new _Z("tag",_);await lf.writeRef({fs:P,gitdir:O,ref:_,value:V})}catch(P){throw P.caller="git.tag",P}}async function fnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),cache:_={},filepath:v,oid:T,mode:P,add:O,remove:V,force:K}){try{Ua("fs",u),Ua("gitdir",l),Ua("filepath",v);let te=new E_(u),oe=await U_({fsp:te,dotgit:l});if(V)return await RN.acquire({fs:te,gitdir:oe,cache:_},async function(Ie){if(!K){let ye=await te.lstat(Wc(i,v));if(ye){if(ye.isDirectory())throw new ove("directory");return}}Ie.has({filepath:v})&&Ie.delete({filepath:v})});let q;if(!T){if(q=await te.lstat(Wc(i,v)),!q)throw new LC(`file at "${v}" on disk and "remove" not set`);if(q.isDirectory())throw new ove("directory")}return await RN.acquire({fs:te,gitdir:oe,cache:_},async function(Ie){if(!O&&!Ie.has({filepath:v}))throw new LC(`file at "${v}" in index and "add" not set`);let ye;if(T)ye={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:P,uid:0,gid:0,size:0};else{ye=q;let ve=ye.isSymbolicLink()?await te.readlink(Wc(i,v)):await te.read(Wc(i,v));T=await hz({fs:te,gitdir:oe,type:"blob",format:"content",object:ve})}return Ie.insert({filepath:v,oid:T,stats:ye}),T})}catch(te){throw te.caller="git.updateIndex",te}}function pnn(){try{return Vbt.version}catch(u){throw u.caller="git.version",u}}async function _nn({fs:u,dir:i,gitdir:l=Wc(i,".git"),trees:_,map:v,reduce:T,iterate:P,cache:O={}}){try{Ua("fs",u),Ua("gitdir",l),Ua("trees",_);let V=new E_(u),K=await U_({fsp:V,dotgit:l});return await lve({fs:V,cache:O,dir:i,gitdir:K,trees:_,map:v,reduce:T,iterate:P})}catch(V){throw V.caller="git.walk",V}}async function mnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),blob:_}){try{Ua("fs",u),Ua("gitdir",l),Ua("blob",_);let v=new E_(u),T=await U_({fsp:v,dotgit:l});return await hz({fs:v,gitdir:T,type:"blob",object:_,format:"content"})}catch(v){throw v.caller="git.writeBlob",v}}async function hnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),commit:_}){try{Ua("fs",u),Ua("gitdir",l),Ua("commit",_);let v=new E_(u),T=await U_({fsp:v,dotgit:l});return await rnn({fs:v,gitdir:T,commit:_})}catch(v){throw v.caller="git.writeCommit",v}}async function gnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),type:_,object:v,format:T="parsed",oid:P,encoding:O=void 0}){try{let V=new E_(u),K=await U_({fsp:V,dotgit:l});if(T==="parsed"){switch(_){case"commit":v=mz.from(v).toObject();break;case"tree":v=_z.from(v).toObject();break;case"blob":v=Buffer.from(v,O);break;case"tag":v=QV.from(v).toObject();break;default:throw new hW(P||"",_,"blob|commit|tag|tree")}T="content"}return P=await hz({fs:V,gitdir:K,type:_,object:v,oid:P,format:T}),P}catch(V){throw V.caller="git.writeObject",V}}async function ynn({fs:u,dir:i,gitdir:l=Wc(i,".git"),ref:_,value:v,force:T=!1,symbolic:P=!1}){try{Ua("fs",u),Ua("gitdir",l),Ua("ref",_),Ua("value",v);let O=new E_(u);if(!KQe(_,!0))throw new mZ(_,IQe.clean(_));let V=await U_({fsp:O,dotgit:l});if(!T&&await lf.exists({fs:O,gitdir:V,ref:_}))throw new _Z("ref",_);P?await lf.writeSymbolicRef({fs:O,gitdir:V,ref:_,value:v}):(v=await lf.resolve({fs:O,gitdir:V,ref:v}),await lf.writeRef({fs:O,gitdir:V,ref:_,value:v}))}catch(O){throw O.caller="git.writeRef",O}}async function fTn({fs:u,gitdir:i,tag:l}){let _=QV.from(l).toObject();return await hz({fs:u,gitdir:i,type:"tag",object:_,format:"content"})}async function vnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),tag:_}){try{Ua("fs",u),Ua("gitdir",l),Ua("tag",_);let v=new E_(u),T=await U_({fsp:v,dotgit:l});return await fTn({fs:v,gitdir:T,tag:_})}catch(v){throw v.caller="git.writeTag",v}}async function bnn({fs:u,dir:i,gitdir:l=Wc(i,".git"),tree:_}){try{Ua("fs",u),Ua("gitdir",l),Ua("tree",_);let v=new E_(u),T=await U_({fsp:v,dotgit:l});return await XQe({fs:v,gitdir:T,tree:_})}catch(v){throw v.caller="git.writeTree",v}}var pTn={Errors:ken,STAGE:WDe,TREE:XV,WORKDIR:N4e,add:Fen,abortMerge:Men,addNote:Gen,addRemote:Ven,annotatedTag:Hen,branch:Jen,cherryPick:Xen,checkout:W7t,clone:ttn,commit:ntn,getConfig:gtn,getConfigAll:ytn,setConfig:nnn,currentBranch:rtn,deleteBranch:itn,deleteRef:stn,deleteRemote:atn,deleteTag:otn,expandOid:ltn,expandRef:ctn,fastForward:ftn,fetch:ptn,findMergeBase:_tn,findRoot:htn,getRemoteInfo:vtn,getRemoteInfo2:Stn,hashBlob:xtn,indexPack:Etn,init:Ttn,isDescendent:Atn,isIgnored:Dtn,listBranches:Itn,listFiles:wtn,listNotes:Ntn,listRefs:ktn,listRemotes:Rtn,listServerRefs:Mtn,listTags:Ltn,log:Ftn,merge:Btn,packObjects:jtn,pull:ztn,push:Gtn,readBlob:Htn,readCommit:G7t,readNote:Jtn,readObject:Ktn,readTag:qtn,readTree:$tn,remove:Xtn,removeNote:Qtn,renameBranch:Ytn,resetIndex:enn,updateIndex:fnn,resolveRef:tnn,status:lnn,statusMatrix:unn,tag:dnn,version:pnn,walk:_nn,writeBlob:mnn,writeCommit:hnn,writeObject:gnn,writeRef:ynn,writeTag:vnn,writeTree:bnn,stash:onn};Zf.Errors=ken;Zf.STAGE=WDe;Zf.TREE=XV;Zf.WORKDIR=N4e;Zf.abortMerge=Men;Zf.add=Fen;Zf.addNote=Gen;Zf.addRemote=Ven;Zf.annotatedTag=Hen;Zf.branch=Jen;Zf.checkout=W7t;Zf.cherryPick=Xen;Zf.clone=ttn;Zf.commit=ntn;Zf.currentBranch=rtn;Zf.default=pTn;Zf.deleteBranch=itn;Zf.deleteRef=stn;Zf.deleteRemote=atn;Zf.deleteTag=otn;Zf.expandOid=ltn;Zf.expandRef=ctn;Zf.fastForward=ftn;Zf.fetch=ptn;Zf.findMergeBase=_tn;Zf.findRoot=htn;Zf.getConfig=gtn;Zf.getConfigAll=ytn;Zf.getRemoteInfo=vtn;Zf.getRemoteInfo2=Stn;Zf.hashBlob=xtn;Zf.indexPack=Etn;Zf.init=Ttn;Zf.isDescendent=Atn;Zf.isIgnored=Dtn;Zf.listBranches=Itn;Zf.listFiles=wtn;Zf.listNotes=Ntn;Zf.listRefs=ktn;Zf.listRemotes=Rtn;Zf.listServerRefs=Mtn;Zf.listTags=Ltn;Zf.log=Ftn;Zf.merge=Btn;Zf.packObjects=jtn;Zf.pull=ztn;Zf.push=Gtn;Zf.readBlob=Htn;Zf.readCommit=G7t;Zf.readNote=Jtn;Zf.readObject=Ktn;Zf.readTag=qtn;Zf.readTree=$tn;Zf.remove=Xtn;Zf.removeNote=Qtn;Zf.renameBranch=Ytn;Zf.resetIndex=enn;Zf.resolveRef=tnn;Zf.setConfig=nnn;Zf.stash=onn;Zf.status=lnn;Zf.statusMatrix=unn;Zf.tag=dnn;Zf.updateIndex=fnn;Zf.version=pnn;Zf.walk=_nn;Zf.writeBlob=mnn;Zf.writeCommit=hnn;Zf.writeObject=gnn;Zf.writeRef=ynn;Zf.writeTag=vnn;Zf.writeTree=bnn});function r0(u,i){try{Lh.info(u,i)}catch{}}function xnn(u,i){try{Lh.warn(u,i)}catch{}}function U7t(u,i="100644"){let l=String(u??"").trim();if(l==="100644"||l==="100755"||l==="120000")return l;let _=typeof u=="number"?u:Number.NaN;return _===33261||_===33261?"100755":_===40960||_===40960?"120000":_===33188||_===33188?"100644":i}var O_,hZ,lv,xde,R4e,M4e,V7t=_c(()=>{"use strict";O_=ll(require("fs")),hZ=ll(require("path")),lv=ll(Snn());xO();xde=require("child_process");pDe();J0t();R4e=class{constructor(i){this.repoDir=i;this.stack=[{name:"",entries:[],dirNames:new Set,fileNames:new Set}]}currentDirs(){return this.stack.slice(1).map(i=>i.name)}lcpLen(i,l){let _=0;for(;_<i.length&&_<l.length&&i[_]===l[_];)_++;return _}async flushTop(){if(this.stack.length<=1)return;let i=this.stack.pop();i.entries.sort((v,T)=>v.path.localeCompare(T.path));let l=await lv.writeTree({fs:O_,dir:this.repoDir,tree:i.entries}),_=this.stack[this.stack.length-1];_.entries.push({mode:"040000",path:i.name,oid:l,type:"tree"}),_.dirNames.add(i.name)}async addEntry(i,l,_="100644"){let v=i.replace(/^\.\//,"").replace(/\\/g,"/"),T=v.split("/").filter(Boolean);if(!T.length)return;let P=T.slice(0,-1),O=T[T.length-1],V=this.currentDirs(),K=this.lcpLen(V,P);for(let oe=V.length;oe>K;oe--)await this.flushTop();for(let oe=K;oe<P.length;oe++){let q=P[oe];if(this.stack[this.stack.length-1].fileNames.has(q))throw new Error(`Path conflict: file exists where directory expected: ${P.slice(0,oe+1).join("/")}`);this.stack.push({name:q,entries:[],dirNames:new Set,fileNames:new Set})}let te=this.stack[this.stack.length-1];if(te.dirNames.has(O))throw new Error(`Path conflict: directory exists where file expected: ${v}`);te.entries.push({mode:_,path:O,oid:l,type:"blob"}),te.fileNames.add(O)}async addFile(i,l){await this.addEntry(i,l,"100644")}async finish(){for(;this.stack.length>1;)await this.flushTop();let i=this.stack[0];return i.entries.sort((l,_)=>l.path.localeCompare(_.path)),lv.writeTree({fs:O_,dir:this.repoDir,tree:i.entries})}},M4e=class{constructor(i){this.baseDir=i.baseDir;let l=e4e(i.shadowDir??i.baseDir);this.repoDir=hZ.join(l.root,"history")}async ensureInitialized(){O_.mkdirSync(this.repoDir,{recursive:!0});let i=hZ.join(this.repoDir,".git");if(O_.existsSync(i)){await this.ensureDefaultGitignore();return}let l=hZ.join(this.repoDir,".init.lock"),_=T=>new Promise(P=>setTimeout(P,T)),v=null;try{try{v=O_.openSync(l,"wx"),O_.writeFileSync(v,String(Date.now()))}catch{let T=Date.now(),P=3e4;for(;!O_.existsSync(i);){try{let O=O_.statSync(l);if(Date.now()-O.mtimeMs>P){try{O_.unlinkSync(l)}catch{}break}}catch{}if(Date.now()-T>P)break;await _(200)}if(O_.existsSync(i))return;v=O_.openSync(l,"wx"),O_.writeFileSync(v,String(Date.now()))}if(O_.existsSync(i))return;r0(`[${new Date().toISOString()}] [GitHistoryStore] Initializing history repo at ${this.repoDir}`),await lv.init({fs:O_,dir:this.repoDir}),r0(`[${new Date().toISOString()}] [GitHistoryStore] git.init OK`),await lv.setConfig({fs:O_,dir:this.repoDir,path:"user.name",value:"ast-db"}),await lv.setConfig({fs:O_,dir:this.repoDir,path:"user.email",value:"ast-db@example.com"}),r0(`[${new Date().toISOString()}] [GitHistoryStore] git config set (user.name/user.email)`),O_.writeFileSync(hZ.join(this.repoDir,".gitignore"),`# ast history repo
|
|
32927
32927
|
`),r0(`[${new Date().toISOString()}] [GitHistoryStore] wrote .gitignore`)}finally{try{v!=null&&O_.closeSync(v)}catch{}try{O_.existsSync(l)&&O_.unlinkSync(l)}catch{}}await this.ensureDefaultGitignore()}async ensureDefaultGitignore(){let i=hZ.join(this.repoDir,".gitignore");if(!O_.existsSync(i))try{O_.mkdirSync(hZ.dirname(i),{recursive:!0}),O_.writeFileSync(i,`# ast history repo
|
|
32928
|
-
`,"utf8");try{await lv.add({fs:O_,dir:this.repoDir,filepath:".gitignore"})}catch{}r0(`[GitHistoryStore] restored missing .gitignore at ${i}`)}catch(l){xnn(`[GitHistoryStore] failed to recreate .gitignore: ${l?.message||l}`)}}normalizeLogicalPath(i){return String(i||"").replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}gitExists(){try{return(0,xde.execFileSync)("git",["--version"],{cwd:this.repoDir,stdio:"ignore"}),!0}catch{return!1}}readProjectWorktreeEntry(i){let l=hZ.join(this.baseDir,i),_;try{_=O_.lstatSync(l)}catch{return null}if(_.isSymbolicLink()){let v=O_.readlinkSync(l);return{content:Buffer.from(v,"utf8"),mode:"120000",entryKind:"symlink",symlinkTarget:v}}return _.isFile()?{content:O_.readFileSync(l),mode:_.mode&73?"100755":"100644",entryKind:"file"}:null}createSnapshotNative(i,l,_,v){let P=(typeof _=="string"?_.match(/^AST-Restore-Trace-Id:\s*(.+)$/m):null)?.[1]?.trim()||null,O=l;if(!O)try{O=(0,xde.execFileSync)("git",["rev-parse","HEAD"],{cwd:this.repoDir,encoding:"utf8"}).trim()}catch{O=void 0}let V=new Map,K=new Map,te=Date.now();try{r0("[GitHistoryStore] native snapshot start",{traceId:P,repoDir:this.repoDir,memberCount:i.length,parentOid:O||null})}catch{}for(let Ie=0;Ie<i.length;Ie++){let ye=i[Ie];if(ye.content==null)throw new Error(`Direct snapshot requires content for ${ye.logicalPath}`);let ve=Buffer.isBuffer(ye.content)?ye.content:Buffer.from(ye.content),ft=this.normalizeLogicalPath(ye.logicalPath);if(!ft)throw new Error("Direct snapshot requires non-empty logicalPath");K.set(ft,U7t(ye.mode,ye.entryKind==="symlink"?"120000":"100644"));let vt=Date.now();try{r0("[GitHistoryStore] native hash-object start",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length})}catch{}let Tt;try{Tt=(0,xde.execFileSync)("git",["hash-object","-w","--stdin"],{cwd:this.repoDir,input:ve}).toString("utf8").trim()}catch(bn){try{xnn("[GitHistoryStore] native hash-object failed",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length,durationMs:Date.now()-vt,message:bn?.message||String(bn),status:bn?.status??null,signal:bn?.signal??null,stdout:bn?.stdout?String(bn.stdout).slice(0,500):null,stderr:bn?.stderr?String(bn.stderr).slice(0,500):null})}catch{}throw bn}let an=Date.now()-vt;try{(an>1e3||Ie<3||Ie===i.length-1)&&r0("[GitHistoryStore] native hash-object done",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length,durationMs:an,oid:Tt})}catch{}V.set(ft,Tt)}try{r0("[GitHistoryStore] native hash-object phase complete",{traceId:P,repoDir:this.repoDir,memberCount:i.length,durationMs:Date.now()-te})}catch{}let oe=hZ.join(this.repoDir,`.pando-index-${process.pid}-${Date.now()}`),q={...process.env,GIT_INDEX_FILE:oe};try{let Ie=Date.now();try{r0("[GitHistoryStore] native read-tree begin",{traceId:P,repoDir:this.repoDir,tmpIndex:oe})}catch{}(0,xde.execFileSync)("git",["read-tree","--empty"],{cwd:this.repoDir,env:q});try{r0("[GitHistoryStore] native read-tree complete",{traceId:P,repoDir:this.repoDir,durationMs:Date.now()-Ie})}catch{}let ye=Array.from(V.keys()).sort((Ut,gt)=>Ut.localeCompare(gt)),ve=Date.now();for(let Ut of ye){let gt=V.get(Ut),Mt=K.get(Ut)||"100644";(0,xde.execFileSync)("git",["update-index","--add","--cacheinfo",Mt,gt,Ut],{cwd:this.repoDir,env:q})}try{r0("[GitHistoryStore] native update-index complete",{traceId:P,repoDir:this.repoDir,entryCount:ye.length,durationMs:Date.now()-ve})}catch{}let ft=Date.now();try{r0("[GitHistoryStore] native write-tree begin",{traceId:P,repoDir:this.repoDir,entryCount:ye.length})}catch{}let vt=(0,xde.execFileSync)("git",["write-tree"],{cwd:this.repoDir,env:q}).toString("utf8").trim();try{r0("[GitHistoryStore] native write-tree complete",{traceId:P,repoDir:this.repoDir,treeOid:vt,durationMs:Date.now()-ft})}catch{}let Tt=["commit-tree",vt];O&&Tt.push("-p",O),_&&Tt.push("-m",_);let an=Date.now();try{r0("[GitHistoryStore] native commit-tree begin",{traceId:P,repoDir:this.repoDir,treeOid:vt,parentOid:O||null})}catch{}let bn=(0,xde.execFileSync)("git",Tt,{cwd:this.repoDir}).toString("utf8").trim();try{r0("[GitHistoryStore] native commit-tree complete",{traceId:P,repoDir:this.repoDir,commitOid:bn,durationMs:Date.now()-an})}catch{}let sn=Date.now();try{r0("[GitHistoryStore] native update-ref begin",{traceId:P,repoDir:this.repoDir,commitOid:bn})}catch{}(0,xde.execFileSync)("git",["update-ref","refs/heads/master",bn],{cwd:this.repoDir});try{r0("[GitHistoryStore] native update-ref complete",{traceId:P,repoDir:this.repoDir,commitOid:bn,durationMs:Date.now()-sn})}catch{}return{snapshotId:bn,parent:O}}finally{try{O_.unlinkSync(oe)}catch{}try{O_.unlinkSync(`${oe}.lock`)}catch{}}}async readObject(i){let{object:l}=await lv.readObject({fs:O_,dir:this.repoDir,oid:i});return Buffer.from(l)}async hasObject(i){try{return await lv.readObject({fs:O_,dir:this.repoDir,oid:i}),!0}catch{return!1}}async createSnapshot(i,l){Vy(l,"Snapshot cancelled"),await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot (streaming) with ${i.members.length} members`);let _=[...i.members].map(jt=>({...jt,logicalPath:this.normalizeLogicalPath(jt.logicalPath)})).filter(jt=>!!jt.logicalPath).sort((jt,er)=>jt.logicalPath.localeCompare(er.logicalPath)),v=this.gitExists()&&!l;try{v?Lh.info("[GitHistoryStore] Using native git snapshot path",{members:_.length}):Lh.info("[GitHistoryStore] Using JS snapshot path",{members:_.length,git:!1,cancellable:!!l})}catch{}if(v)try{return this.createSnapshotNative(_,i.parent,i.message,i.when).snapshotId}catch(jt){try{Lh.warn(`[GitHistoryStore] Native git path failed; falling back to JS path: ${jt?.message||jt}`)}catch{}}let T=Date.now(),P=jt=>jt.toString("hex"),O=jt=>require("crypto").createHash("sha1").update(jt).digest(),V=jt=>{let er=Buffer.from(`blob ${jt.length}\0`,"utf8"),$n=Buffer.concat([er,jt]);return P(O($n))},K=Math.max(1,Math.min(64,Number(process.env.SNAPSHOT_BLOB_CONCURRENCY||16))),te=String(process.env.SNAPSHOT_PRECOMPUTE_OIDS||"1")!=="0";try{Lh.info("[GitHistoryStore] JS snapshot settings",{SNAPSHOT_BLOB_CONCURRENCY:K,SNAPSHOT_PRECOMPUTE_OIDS:te})}catch{}let oe=new Map,q=new Map,Ie=0,ye=0,ve=0,ft=_.map(jt=>({path:jt.logicalPath,buf:Buffer.isBuffer(jt.content)?jt.content:Buffer.from(jt.content),mode:U7t(jt.mode,jt.entryKind==="symlink"?"120000":"100644")}));for(let jt of ft)q.set(jt.path,jt.mode);let vt=async()=>{for(;;){Vy(l,"Snapshot cancelled");let jt;if(Ie<ft.length)jt=ft[Ie++];else break;let er;if(te)try{let $n=V(jt.buf);await this.hasObject($n)&&(er=$n,ve++)}catch{}if(er||(er=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:jt.buf}),ye++),Vy(l,"Snapshot cancelled"),!er)throw new Error("Failed to compute blob object id");oe.set(jt.path,er)}},Tt=Array.from({length:Math.min(K,ft.length)},()=>vt());await Promise.all(Tt),Vy(l,"Snapshot cancelled"),r0(`[GitHistoryStore] Blobs ready wrote=${ye} skipped=${ve} in ${Date.now()-T}ms`);let an=new R4e(this.repoDir),bn=Array.from(oe.keys()).sort((jt,er)=>jt.localeCompare(er));for(let jt of bn)Vy(l,"Snapshot cancelled"),await an.addEntry(jt,oe.get(jt),q.get(jt)||"100644");Vy(l,"Snapshot cancelled");let sn=Date.now(),Ut=await an.finish();r0(`[GitHistoryStore] Wrote tree(s). root=${Ut} in ${Date.now()-sn}ms`);let gt=i.parent;if(!gt)try{gt=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}Vy(l,"Snapshot cancelled");let Mt=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),We=new Date(Mt*1e3).getTimezoneOffset(),In=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:gt?[gt]:[],tree:Ut,author:{name:"ast-db",email:"ast-db@example.com",timestamp:Mt,timezoneOffset:We},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:Mt,timezoneOffset:We}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:In,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${In}`),In}async listSnapshotMembers(i){await this.ensureInitialized();let l=T=>Math.round((T||0)/(1024*1024)),_=()=>{let T=process.memoryUsage();return`rss=${l(T.rss)}MB heapUsed=${l(T.heapUsed)}MB heapTotal=${l(T.heapTotal)}MB`},v=[];return r0(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${i}) start (${_()})`),await lv.walk({fs:O_,dir:this.repoDir,trees:[lv.TREE({ref:i})],map:async(T,[P])=>{if(!P)return;let O=await P.type();if(O==="blob"){let V=await P.oid(),K;try{K=U7t(await P.mode())}catch{}let te;if(K==="120000")try{te=(await this.readObject(V)).toString("utf8")}catch{}v.push({logicalPath:T,objectId:V,entryKind:K==="120000"?"symlink":"file",mode:K||(O==="blob"?"100644":void 0),symlinkTarget:te})}}}),r0(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${i}) -> ${v.length} blobs`),v.filter(T=>T.logicalPath&&T.logicalPath!==".").map(T=>({logicalPath:T.logicalPath.replace(/^\.\//,""),objectId:T.objectId}))}async readCommit(i){let{commit:l}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:i});return{message:l.message,committer:l.committer}}async readCommitParent(i){let{commit:l}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:i});return Array.isArray(l.parent)&&l.parent.length>0?String(l.parent[0]):void 0}async createSnapshotFromDisk(i,l){Vy(l,"Snapshot cancelled"),await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (streaming) with ${i.relPaths.length} members`);let _=[...i.relPaths].map(Ie=>this.normalizeLogicalPath(Ie)).filter(Boolean).sort((Ie,ye)=>Ie.localeCompare(ye)),v=Date.now(),T=new R4e(this.repoDir),P=0;for(let Ie of _){Vy(l,"Snapshot cancelled");let ye=hZ.join(this.baseDir,Ie);try{let ve=this.readProjectWorktreeEntry(Ie);if(!ve)continue;let ft=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:ve.content});await T.addEntry(Ie,ft,ve.mode),P++}catch{}}r0(`[GitHistoryStore] Wrote ${P} blobs (disk) in ${Date.now()-v}ms`),Vy(l,"Snapshot cancelled");let O=Date.now(),V=await T.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk). root=${V} in ${Date.now()-O}ms`);let K=i.parent;if(!K)try{K=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}Vy(l,"Snapshot cancelled");let te=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),oe=new Date(te*1e3).getTimezoneOffset(),q=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:K?[K]:[],tree:V,author:{name:"ast-db",email:"ast-db@example.com",timestamp:te,timezoneOffset:oe},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:te,timezoneOffset:oe}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:q,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${q}`),q}async createSnapshotFromDiskAndCapturedIfChanged(i){await this.ensureInitialized();let l=new Map;for(let ve of i.capturedMembers||[]){let ft=this.normalizeLogicalPath(ve.logicalPath);!ft||ve.content==null||l.has(ft)||l.set(ft,Buffer.isBuffer(ve.content)?ve.content:Buffer.from(ve.content))}r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk+captured (diff) with ${i.relPaths.length} members, captured=${l.size}`);let _=[...i.relPaths].map(ve=>this.normalizeLogicalPath(ve)).filter(Boolean).sort((ve,ft)=>ve.localeCompare(ft)),v=Date.now(),T=new R4e(this.repoDir),P=0,O=0,V=0;for(let ve of _)try{let ft=l.get(ve),vt=ft?{content:ft,mode:"100644"}:this.readProjectWorktreeEntry(ve);if(!vt)continue;let Tt=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:vt.content});await T.addEntry(ve,Tt,vt.mode),P++,ft?O++:V++}catch{}r0(`[GitHistoryStore] Wrote ${P} blobs (captured=${O}, disk=${V}) in ${Date.now()-v}ms`);let K=Date.now(),te=await T.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk+captured). root=${te} in ${Date.now()-K}ms`);let oe=i.parent;if(!oe)try{oe=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}if(oe)try{let{commit:ve}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:oe});if(ve?.tree===te){r0("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:oe,tree:te});let ft=await this.readCommitParent(oe);return{snapshotId:oe,identical:!0,parent:ft}}}catch(ve){r0("[GitHistoryStore] Parent read failed; proceeding with commit",{error:ve?.message||String(ve)})}let q=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),Ie=new Date(q*1e3).getTimezoneOffset(),ye=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:oe?[oe]:[],tree:te,author:{name:"ast-db",email:"ast-db@example.com",timestamp:q,timezoneOffset:Ie},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:q,timezoneOffset:Ie}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:ye,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${ye}`),{snapshotId:ye,identical:!1,parent:oe}}async createSnapshotFromDiskIfChanged(i){await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (diff) with ${i.relPaths.length} members`);let l=[...i.relPaths].map(q=>this.normalizeLogicalPath(q)).filter(Boolean).sort((q,Ie)=>q.localeCompare(Ie)),_=Date.now(),v=new R4e(this.repoDir),T=0;for(let q of l)try{let Ie=this.readProjectWorktreeEntry(q);if(!Ie)continue;let ye=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:Ie.content});await v.addEntry(q,ye,Ie.mode),T++}catch{}r0(`[GitHistoryStore] Wrote ${T} blobs (disk) in ${Date.now()-_}ms`);let P=Date.now(),O=await v.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk). root=${O} in ${Date.now()-P}ms`);let V=i.parent;if(!V)try{V=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}if(V)try{let{commit:q}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:V});if(q?.tree===O){r0("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:V,tree:O});let Ie=await this.readCommitParent(V);return{snapshotId:V,identical:!0,parent:Ie}}}catch(q){r0("[GitHistoryStore] Parent read failed; proceeding with commit",{error:q?.message||String(q)})}let K=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),te=new Date(K*1e3).getTimezoneOffset(),oe=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:V?[V]:[],tree:O,author:{name:"ast-db",email:"ast-db@example.com",timestamp:K,timezoneOffset:te},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:K,timezoneOffset:te}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:oe,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${oe}`),{snapshotId:oe,identical:!1,parent:V}}}});var Ede={};SD(Ede,{computeEffectiveMap:()=>Hbt,diffEffectiveSets:()=>Jbt,getEntryAtSnapshot:()=>YQe,getFileAtSnapshot:()=>Dnn,getFileAtSnapshotPath:()=>mTn,getSnapshotDatabase:()=>Inn});function _Tn(u,i){let l=[],_=i,v=new Set;for(;_&&!v.has(_);){v.add(_),l.push(_);let T=u.prepare("SELECT parents FROM snapshots WHERE snapshot_id = ?").get(_),P=T&&typeof T.parents=="string"&&T.parents.length>0?String(T.parents):null;_=(P?P.split(",")[0].trim():void 0)||void 0}return l.reverse(),l}function Hbt(u,i){let l=Enn.get(i);if(l)return l;let _=_Tn(u,i),v=new Map,T=!1;for(let P of _){let O=u.prepare("SELECT logical_path, object_id, entry_kind, mode, symlink_target FROM snapshot_members WHERE snapshot_id = ?").all(P);O.length>0&&(T=!0);for(let V of O){let K=V.logical_path,te=V.object_id;if(K)if(te&&te.length>0){let oe=V.entry_kind==="symlink"?"symlink":"file";v.set(K,{oid:te,src:P,entryKind:oe,mode:V.mode??(oe==="symlink"?"120000":"100644"),symlinkTarget:V.symlink_target??null})}else v.delete(K)}}return(v.size>0||T)&&Enn.set(i,v),v}function Jbt(u,i,l){let _=Hbt(u,i),v=l?Hbt(u,l):new Map,T=[],P=[],O=[],V=new Set(v.keys());for(let[K,te]of _){let oe=v.get(K);oe?Tnn(oe)!==Tnn(te)&&P.push(K):T.push(K),V.delete(K)}for(let K of V)O.push(K);return{added:T,changed:P,deleted:O}}function Tnn(u){return[u.entryKind,u.mode||"",u.oid,u.symlinkTarget||""].join("\0")}async function YQe(u,i,l,_){let T=Hbt(u,l).get(_);if(!T)return null;let O=await new M4e({baseDir:i}).readObject(T.oid);return{content:O,sourceSnapshot:T.src,oid:T.oid,entryKind:T.entryKind,mode:T.mode,symlinkTarget:T.entryKind==="symlink"?T.symlinkTarget??O.toString("utf8"):null}}async function Dnn(u,i,l,_){let v=await YQe(u,i,l,_);return!v||v.entryKind!=="file"?null:{content:v.content,sourceSnapshot:v.sourceSnapshot,oid:v.oid}}function Inn(u){let i=[uXe(u),Ann.default.join(Sy(u),"pando.db"),bO(u,0)];for(let l of i)if(Cnn.existsSync(l))try{let _=new GS(l,{readOnly:!0,fileMustExist:!0});try{_.pragma("busy_timeout = 10000")}catch{}return _}catch(_){Su("SnapshotEffective","failed to open snapshot DB",{dbPath:l,error:_?.message??_})}return null}async function mTn(u,i,l){let _=Inn(u);if(!_)return null;try{return await Dnn(_,u,i,l)}finally{try{_.close()}catch{}}}var Cnn,Ann,H7t,Enn,Oie=_c(()=>{"use strict";CD();Cnn=ll(require("fs")),Ann=ll(require("path"));V7t();FM();XT();H7t=class{constructor(i=100){this.max=i,this.map=new Map}get(i){let l=this.map.get(i);return l!==void 0&&(this.map.delete(i),this.map.set(i,l)),l}set(i,l){if(this.map.has(i)&&this.map.delete(i),this.map.set(i,l),this.map.size>this.max){let _=this.map.keys().next().value;this.map.delete(_)}}},Enn=new H7t(64)});function hTn(u){return u instanceof $bt||typeof u=="object"&&u!==null&&u.error_code==="invalid_fts_query"}function jnn(u){return u instanceof Xbt||typeof u=="object"&&u!==null&&u.error_code==="fts_storage_error"}function GDe(u){return hTn(u)||jnn(u)}function gTn(u){let i=String(u?.message||u||"").toLowerCase();return i.includes("readonly database")||i.includes("unable to open database file")||i.includes("database disk image is malformed")||i.includes("no such table")||i.includes("permission denied")||i.includes("operation not permitted")}function yTn(u,i){let l=u?.details?.sqliteMessage||u?.message||String(u),_=jnn(u),v=GDe(u)?{...u.details}:{query:i,adaptedQuery:i,sqliteMessage:l,syntax:"SQLite FTS5 MATCH"},T=_?`FTS index read failed: ${l}`:`FTS query failed: ${l}`;return{error:T,error_code:_?"fts_storage_error":"invalid_fts_query",details:v,warning:_?`${T}. ${Wnn}`:`${T}. ${Bnn}`}}function jDe(u,i,l,_){let v=yTn(l,_),T=String(v.details.sqliteMessage||v.error);return u.ftsErrors=[...u.ftsErrors??[],T],u.ftsError=v.details,v.error_code==="invalid_fts_query"?u.ftsSyntaxHint=Bnn:u.ftsStorageHint=Wnn,i.push(v.warning),v}function znn(u,i=new Set){if(!u||typeof u!="object"||i.has(u))return null;i.add(u);let l=u;if(l.constructor&&l.constructor.name==="B"&&typeof l.ga=="string")return l.constructor;for(let _ of Object.getOwnPropertyNames(u))try{let v=znn(u[_],i);if(v)return v}catch{}return null}function vTn(){if(ZQe)return ZQe;if(ZQe===null)throw new Error("DataScript keyword constructor unavailable");let u=iYe.empty_db({":seed":{":db/unique":":db.unique/identity"}}),i=znn(u);if(!i)throw ZQe=null,new Error("Failed to locate DataScript keyword constructor");return ZQe=i,i}function BM(u){let i=String(u||"").trim();if(!i)throw new Error("DataScript keyword attr cannot be empty");let l=i.startsWith(":")?i.slice(1):i,_=`:${l}`;if(J7t.has(_))return J7t.get(_);let v=l.indexOf("/"),T=v>=0?l.slice(0,v):null,P=v>=0?l.slice(v+1):l,O=new(vTn())(T,P,l,null);return J7t.set(_,O),O}function L7(u){if(!bTn)return()=>{};let i=u||"UnifiedDb",l=process.hrtime.bigint(),_=l;return(v,T)=>{let P=process.hrtime.bigint(),O=Number(P-l)/1e6,V=Number(P-_)/1e6;_=P;let K={stage:v,sinceStartMs:O,sinceLastMs:V,...T||{}};try{console.log("[UnifiedDb][PROFILE]",JSON.stringify({label:i,...K}))}catch{console.log("[UnifiedDb][PROFILE]",i,K)}}}function gZ(u,i){let l=new Date().toISOString();try{console.log(`[${l}] [UnifiedDb][DEBUG] ${u}`,i??{})}catch{console.log(`[${l}] [UnifiedDb][DEBUG] ${u}`)}}function Fie(u="nodes"){return`(SELECT path FROM dict_files WHERE id = ${u}.file_id)`}function STn(u="nodes"){return`(SELECT text FROM dict_symbols WHERE id = ${u}.name_id)`}function xTn(u="nodes"){return`(SELECT text FROM dict_kinds WHERE id = ${u}.kind_id)`}function tYe(u){let i=new Set,l=_=>{if(!_)return;let v=_.trim();if(!v)return;let T=v.toLowerCase();if(Object.prototype.hasOwnProperty.call(Pnn,T)){for(let P of Pnn[T])i.add(P);return}i.add(v)};if(Array.isArray(u))for(let _ of u)l(_);return Array.from(i)}function nYe(u){let i=[],l=[];for(let _ of u||[]){let v=String(_||"").trim();if(v){if(ETn.has(v.toLowerCase())){i.push(v);continue}l.push(v)}}return{contentDriven:i,structural:l}}function pve(u){if(typeof u!="string")return null;let i=u.indexOf("#");if(i===-1)return null;let l=u.slice(i+1),_=l.indexOf(":"),T=(_===-1?l:l.slice(0,_)).match(/^([0-9]+)-([0-9]+)$/);if(!T)return null;let P=Number(T[1]),O=Number(T[2]);return Number.isNaN(P)||Number.isNaN(O)?null:{start:P,end:O}}function rYe(u,i){let l=pve(u),_=pve(i);if(l&&_){if(l.start!==_.start)return l.start-_.start;if(l.end!==_.end)return l.end-_.end}return String(u).localeCompare(String(i))}function TTn(u){return String(u||"").toLowerCase().match(/[a-z0-9_]+/g)||[]}function wnn(u){let i=String(u||"").trim();if(!i)return null;let l=i.toLowerCase(),_=(T,P,O)=>{let V=T.trim().toLowerCase();if(!V)return!0;if(V.startsWith('"')&&V.endsWith('"')&&V.length>=2)return P.toLowerCase().includes(V.slice(1,-1));if(V.endsWith("*")){let K=V.slice(0,-1);return K.length>0&&O.some(te=>te.startsWith(K))}return O.includes(V)||P.toLowerCase().includes(V)},v=(T,P,O)=>{let V=T.match(/^\s*([A-Za-z0-9_]+)\s+NEAR\/(\d+)\s+([A-Za-z0-9_]+)\s*$/i);if(V){let K=V[1].toLowerCase(),te=Math.max(0,Number(V[2])||0),oe=V[3].toLowerCase(),q=[],Ie=[];return O.forEach((ye,ve)=>{ye===K&&q.push(ve),ye===oe&&Ie.push(ve)}),q.some(ye=>Ie.some(ve=>Math.abs(ye-ve)<=te))}if(/\bOR\b/i.test(T))return T.split(/\bOR\b/i).some(K=>v(K,P,O));if(/\bNOT\b/i.test(T)){let[K,...te]=T.split(/\bNOT\b/i),oe=te.join(" ").trim();return v(K,P,O)&&!v(oe,P,O)}return/\bAND\b/i.test(T)?T.split(/\bAND\b/i).every(K=>v(K,P,O)):T.includes("|")?T.split("|").some(K=>v(K,P,O)):_(T,P,O)};return T=>{let P=String(T||""),O=TTn(P);return v(l,P,O)}}function Nnn(u,i){let l=Array.from(new Set(u.filter(Boolean))),_=Array.from(new Set(i.filter(Boolean))),v=new Set(l),T=new Set(_),P=_.filter(Ie=>!v.has(Ie)),O=l.filter(Ie=>!T.has(Ie)),V={},K=l.slice(0,3),te=_.slice(0,3),oe=P.slice(0,3),q=O.slice(0,3);return K.length>0&&(V.beforeTop3=K),te.length>0&&(V.afterTop3=te),oe.length>0&&(V.addedTop3=oe),q.length>0&&(V.removedTop3=q),V}function knn(u){if(!Array.isArray(u))return[];let i=[];for(let l of u){if(!l)continue;let _=typeof l.path=="string"?String(l.path):"";_&&i.push(_)}return i}function Rnn(u){if(!Array.isArray(u))return[];let i=[];for(let l of u){if(!l)continue;let _=typeof l.file_path=="string"?String(l.file_path):typeof l.path=="string"?String(l.path).split("#")[0]:"";_&&i.push(_)}return i}function Mnn(u,i){let l={},_=Nnn(knn(u),knn(i)),v=Nnn(Rnn(u),Rnn(i));return Object.keys(_).length>0&&(l.paths=_),Object.keys(v).length>0&&(l.files=v),l}function q7t(u,i){try{return typeof u?.hasModifier=="function"&&u.hasModifier(i)}catch{return!1}}function zDe(u){let i=Td.extname(String(u||"")).toLowerCase();return CTn.has(i)}function ATn(u){return Pf.Node.isFunctionDeclaration(u)||Pf.Node.isFunctionExpression(u)||Pf.Node.isArrowFunction(u)||Pf.Node.isClassDeclaration(u)||Pf.Node.isClassExpression(u)||Pf.Node.isInterfaceDeclaration(u)||Pf.Node.isEnumDeclaration(u)||Pf.Node.isEnumMember(u)||Pf.Node.isTypeAliasDeclaration(u)||Pf.Node.isModuleDeclaration(u)||Pf.Node.isMethodDeclaration(u)||Pf.Node.isMethodSignature(u)||Pf.Node.isPropertyDeclaration(u)||Pf.Node.isPropertySignature(u)||Pf.Node.isGetAccessorDeclaration(u)||Pf.Node.isSetAccessorDeclaration(u)||Pf.Node.isConstructorDeclaration(u)||Pf.Node.isVariableDeclaration(u)}function DTn(u){return Pf.Node.isReturnStatement(u)||Pf.Node.isIfStatement(u)||Pf.Node.isForStatement(u)||Pf.Node.isForInStatement(u)||Pf.Node.isForOfStatement(u)||Pf.Node.isWhileStatement(u)||Pf.Node.isDoStatement(u)||Pf.Node.isSwitchStatement(u)||Pf.Node.isCaseClause(u)||Pf.Node.isDefaultClause(u)||Pf.Node.isTryStatement(u)||Pf.Node.isCatchClause(u)||Pf.Node.isThrowStatement(u)||Pf.Node.isExpressionStatement(u)||Pf.Node.isBlock(u)}function ITn(u){try{if(typeof u?.getName=="function"){let i=u.getName();if(typeof i=="string"&&i.length>0)return i}}catch{}try{if(Pf.Node.isConstructorDeclaration(u))return"constructor";if(Pf.Node.isIdentifier(u)||Pf.Node.isPrivateIdentifier(u)){let l=u.getText();return l.length>0?l:null}if(Pf.Node.isVariableDeclaration(u)||Pf.Node.isEnumMember(u))return typeof u.getName=="function"?u.getName()??null:null;let i=u.getParent();if(Pf.Node.isArrowFunction(u)||Pf.Node.isFunctionExpression(u)){if(i&&Pf.Node.isVariableDeclaration(i))return i.getName();if(i&&(Pf.Node.isPropertyAssignment(i)||Pf.Node.isPropertyDeclaration(i)||Pf.Node.isPropertySignature(i)))return i.getName?.()??null;if(i&&Pf.Node.isShorthandPropertyAssignment(i))return i.getNameNode()?.getText()??null;if(i&&Pf.Node.isExportAssignment(i))return"default"}}catch{}return null}function PTn(u){try{if(Pf.Node.isFunctionDeclaration(u)||Pf.Node.isMethodDeclaration(u)||Pf.Node.isConstructorDeclaration(u)||Pf.Node.isFunctionExpression(u)||Pf.Node.isArrowFunction(u)){let i=u.getParameters?.();if(Array.isArray(i))return i.length}}catch{}return null}function wTn(u){let i=Zue(u),l=(()=>{try{return u.getStart?.(!1)}catch{return}})(),_=typeof l=="number"&&Number.isFinite(l)?l:(()=>{try{let P=u.getStart?.();return typeof P=="number"&&Number.isFinite(P)?P:0}catch{return 0}})(),v=(()=>{try{return u.getEnd?.()}catch{return}})(),T=typeof v=="number"&&Number.isFinite(v)&&v>=_?v:_;return{start:_,end:T}}function NTn(u,i){if(Pf.Node.isSourceFile(u))return{start:0,end:typeof i=="number"&&Number.isFinite(i)?Math.max(0,i):0};try{let l=u?.getBody?.();if(!l||typeof l.getStart!="function"||typeof l.getEnd!="function")return null;let _=typeof l.getKindName=="function"?String(l.getKindName()):"",v=_==="Block"||_==="ModuleBlock",T=l.getStart(),P=l.getEnd(),O=v?T+1:T,V=v?P-1:P;return!Number.isFinite(O)||!Number.isFinite(V)||V<O?null:{start:O,end:V}}catch{return null}}function kTn(u){let i=u.getKindName();return!(i==="SourceFile"||i==="SyntaxList"||i==="EndOfFileToken"||i.endsWith("Token"))}function RTn(u){let i=u.getParent?.();if(!i)return null;try{if(Pf.Node.isIfStatement(i)){if(i.getExpression()===u)return"condition";if(i.getThenStatement()===u)return"then";if(i.getElseStatement()===u)return"else"}if(Pf.Node.isCallExpression(i)||Pf.Node.isNewExpression(i)){if(i.getExpression?.()===u)return"callee";if((i.getArguments?.()||[]).some(l=>l===u))return"argument"}if(Pf.Node.isConditionalExpression(i)){if(i.getCondition()===u)return"condition";if(i.getWhenTrue()===u)return"then";if(i.getWhenFalse()===u)return"else"}if(Pf.Node.isReturnStatement(i)&&i.getExpression?.()===u)return"value";if(Pf.Node.isExpressionStatement(i)&&i.getExpression()===u)return"expression";if(Pf.Node.isVariableDeclaration(i)){if(i.getNameNode?.()===u)return"name";if(i.getInitializer?.()===u)return"initializer"}if(Pf.Node.isPropertyDeclaration(i)||Pf.Node.isPropertyAssignment(i)){if(i.getNameNode?.()===u)return"name";if(i.getInitializer?.()===u)return"initializer"}if(Pf.Node.isBinaryExpression(i)){if(i.getLeft()===u)return"left";if(i.getRight()===u)return"right"}if(Pf.Node.isFunctionDeclaration(i)||Pf.Node.isFunctionExpression(i)||Pf.Node.isArrowFunction(i)||Pf.Node.isMethodDeclaration(i)||Pf.Node.isConstructorDeclaration(i)){if(i.getBody?.()===u)return"body";if((i.getParameters?.()||[]).some(l=>l===u))return"parameter"}if(Pf.Node.isBlock(i))return"statement"}catch{}return null}function Onn(u){let i=Td.dirname(Td.resolve(u));try{for(;;){let l=Td.join(i,"tsconfig.json");if(TO.existsSync(l))return l;let _=Td.dirname(i);if(_===i)break;i=_}}catch{}return Td.resolve("tsconfig.json")}var TO,Td,qbt,Fnn,Pf,Bie,iYe,Bnn,Wnn,$bt,Xbt,ZQe,J7t,bTn,eYe,Pnn,ETn,$7t,Kbt,K7t,CTn,Lnn,MTn,LTn,AE,Tde=_c(()=>{"use strict";TO=ll(require("fs")),Td=ll(require("path")),qbt=ll(require("crypto")),Fnn=require("child_process"),Pf=ll(MI()),Bie=ll(v6e());Gye();NXe();b3();FM();z4t();CD();w$t();cDe();pXe();Pq();H3t();Bvt();XT();J0t();S3t();iYe=R$t(),Bnn='Use valid SQLite FTS5 MATCH syntax, e.g. foo*, "foo bar", foo AND bar, foo OR bar, or foo NEAR/1 bar.',Wnn="The FTS index could not be read. Rebuild or repair the Pando index, or check the security helper data-directory permissions.",$bt=class extends Error{constructor(l){super(`SQLite rejected FTS MATCH expression: ${l.sqliteMessage}`);this.error_code="invalid_fts_query";this.name="FtsQueryRejectedError",this.details={query:l.query,adaptedQuery:l.adaptedQuery,shard:l.shard,sqliteMessage:l.sqliteMessage,syntax:"SQLite FTS5 MATCH"}}},Xbt=class extends Error{constructor(l){super(`SQLite could not read FTS index: ${l.sqliteMessage}`);this.error_code="fts_storage_error";this.name="FtsStorageError",this.details={query:l.query,adaptedQuery:l.adaptedQuery,shard:l.shard,sqliteMessage:l.sqliteMessage}}};J7t=new Map;bTn=process.env.AST_FIND_NODES_PROFILING==="1";eYe={reference:1,call:2,new:4,type:8,import:16,export:32};Pnn={function:["Function","Method","FunctionDeclaration","FunctionExpression","ArrowFunction","MethodDeclaration","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],functions:["Function","Method","FunctionDeclaration","FunctionExpression","ArrowFunction","MethodDeclaration","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],class:["Class","ClassDeclaration","ClassExpression"],classes:["Class","ClassDeclaration","ClassExpression"],struct:["Struct"],structs:["Struct"],union:["Union"],unions:["Union"],interface:["Interface","InterfaceDeclaration"],interfaces:["Interface","InterfaceDeclaration"],method:["Method","MethodDeclaration","MethodSignature","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],methods:["Method","MethodDeclaration","MethodSignature","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],property:["Field","PropertyDeclaration","PropertySignature"],properties:["Field","PropertyDeclaration","PropertySignature"],field:["Field"],fields:["Field"],variable:["Variable","VariableDeclaration"],variables:["Variable","VariableDeclaration"],enum:["Enum","EnumDeclaration"],enums:["Enum","EnumDeclaration"],"enum-member":["EnumMember","EnumMemberDeclaration"],enum_member:["EnumMember","EnumMemberDeclaration"],type:["TypeAlias","TypeAliasDeclaration"],"type-alias":["TypeAlias","TypeAliasDeclaration"],types:["TypeAlias","TypeAliasDeclaration"],namespace:["Namespace","ModuleDeclaration","NamespaceDeclaration"],namespaces:["Namespace","ModuleDeclaration","NamespaceDeclaration"],template:["Template"],templates:["Template"],"template-parameter":["TemplateParameter"],template_parameter:["TemplateParameter"],operator:["Operator"],operators:["Operator"],macro:["Macro"],macros:["Macro"],file:["SourceFile"],sourcefile:["SourceFile"],files:["SourceFile"],sourcefiles:["SourceFile"],return:["ReturnStatement"],return_statement:["ReturnStatement"],return_statements:["ReturnStatement"],if:["IfStatement"],if_statement:["IfStatement"],if_statements:["IfStatement"],for:["ForStatement","ForInStatement","ForOfStatement"],for_statement:["ForStatement"],for_in_statement:["ForInStatement"],for_of_statement:["ForOfStatement"],while:["WhileStatement"],while_statement:["WhileStatement"],do:["DoStatement"],do_statement:["DoStatement"],switch:["SwitchStatement"],switch_statement:["SwitchStatement"],case:["CaseClause"],case_clause:["CaseClause"],default:["DefaultClause"],default_clause:["DefaultClause"],try:["TryStatement"],try_statement:["TryStatement"],catch:["CatchClause"],catch_clause:["CatchClause"],throw:["ThrowStatement"],throw_statement:["ThrowStatement"],block:["Block"],expression:["ExpressionStatement"],expression_statement:["ExpressionStatement"]},ETn=new Set(["comment","comments","text"]);$7t={return_statement:["ReturnStatement"],return_statements:["ReturnStatement"],throw_statement:["ThrowStatement"],throw_statements:["ThrowStatement"],try_statement:["TryStatement"],try_statements:["TryStatement"],try_blocks:["TryStatement","CatchClause","FinallyBlock"],control_flow:["IfStatement","SwitchStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoStatement"]},Kbt=new Set(["ReturnStatement","ThrowStatement","TryStatement","CatchClause","FinallyBlock","IfStatement","SwitchStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoStatement",...Object.values($7t).flat()]),K7t=Number.MAX_SAFE_INTEGER,CTn=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Lnn=5;MTn={":node/path":{":db/unique":":db.unique/identity"}},LTn=/:node\/[A-Za-z0-9_-]+/g,AE=class u{constructor(i){this.chunkDbs=[];this.ftsChunkDbs=[];this.fileToChunkMap=new Map;this.functionLike=new Set(["FunctionDeclaration","MethodDeclaration","ArrowFunction","FunctionExpression","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration","Function","Method","Constructor","LocalFunctionStatement","LocalFunction"]);this.projectRoot=i,this.readOnly=process.env.PANDO_PROCESS_ROLE==="core";let l=L7("constructor");l("start",{projectRoot:i}),this.discoverChunks(),l("afterDiscoverChunks",{chunkCount:this.chunkDbs.length,ftsChunkCount:this.ftsChunkDbs.length}),gZ("constructor.afterDiscoverChunks",{projectRoot:i,pandoDataDir:Sy(i),chunkCount:this.chunkDbs.length,ftsChunkCount:this.ftsChunkDbs.length,chunkDbs:this.chunkDbs,ftsChunkDbs:this.ftsChunkDbs}),this.preloadFileMappings(),l("afterPreloadFileMappings",{cachedFiles:this.fileToChunkMap.size,mappingStore:!!this.mappingStore}),gZ("constructor.afterPreloadFileMappings",{projectRoot:i,cachedFiles:this.fileToChunkMap.size,mappingStore:!!this.mappingStore})}static{this.offsetsSupported=!0}static{this.DB_DEBUG=$T()}preflightDatalogQuery(i,l){if(!i||typeof i.query!="string")return null;let _=this.getDatalogQueryAttributes(i),v=_.filter(P=>!cqt.has(P)),T={ok:v.length===0,queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]};return T.ok||(T.error=`Unsupported datalog attrs: ${v.join(", ")}. Allowed attrs: ${U6e.join(", ")}`,T.error_code="unsupported_datalog_attributes",T.details={queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]}),l&&(l.datalogPreflight={ok:T.ok,queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]}),T}getDatalogQueryAttributes(i){return!i||typeof i.query!="string"?[]:Array.from(new Set(i.query.match(LTn)||[])).sort()}tokenizeDatalogClause(i){let l=[],_=String(i||""),v=0;for(;v<_.length;){for(;v<_.length&&/\s/.test(_[v]);)v++;if(v>=_.length)break;if(_[v]==='"'){let P=v+1,O=!1;for(;P<_.length;){let V=_[P];if(O){O=!1,P++;continue}if(V==="\\"){O=!0,P++;continue}if(V==='"'){P++;break}P++}l.push(_.slice(v,P)),v=P;continue}let T=v;for(;T<_.length&&!/\s/.test(_[T]);)T++;l.push(_.slice(v,T)),v=T}return l}parseExactDatalogLiteral(i){let l=String(i||"").trim();if(l){if(l==="true")return!0;if(l==="false")return!1;if(l==="nil"||l==="null")return null;if(/^-?\d+$/.test(l)){let _=Number(l);return Number.isSafeInteger(_)?_:void 0}if(l.startsWith('"')&&l.endsWith('"'))try{return JSON.parse(l)}catch{return}}}extractIndexedFieldFiltersFromDatalog(i){if(!i||typeof i.query!="string"||typeof i.result?.nodeVar!="string")return null;let l=String(i.result.nodeVar).trim();if(!l)return null;let _=i.query.match(/\[[^\[\]]*\]/g)||[];if(_.length===0)return null;let v=new Set,T=new Set,P=new Set,O=new Set,V=new Set,K=new Set;for(let q of _){let Ie=q.slice(1,-1).trim();if(!Ie)continue;let ye=this.tokenizeDatalogClause(Ie);if(ye.length!==3||ye[0]!==l)continue;let ve=ye[1],ft=this.parseExactDatalogLiteral(ye[2]);if(ft!==void 0)switch(ve){case":node/name":typeof ft=="string"&&ft&&v.add(ft);break;case":node/kind":case":node/type":typeof ft=="string"&&ft&&T.add(ft);break;case":node/semantic-kind":typeof ft=="string"&&ft&&P.add(ft);break;case":node/param-count":typeof ft=="number"&&Number.isFinite(ft)&&O.add(Math.max(0,Math.floor(ft)));break;case":node/exported":typeof ft=="boolean"&&V.add(ft);break;case":node/file":typeof ft=="string"&&ft&&K.add(ft.replace(/\\/g,"/"));break;default:break}}return v.size===0&&T.size===0&&P.size===0&&O.size===0&&V.size===0&&K.size===0?null:{impossible:v.size>1||T.size>1||P.size>1||O.size>1||V.size>1||K.size>1,name:v.size===1?Array.from(v)[0]:void 0,kind:T.size===1?Array.from(T)[0]:void 0,semanticKind:P.size===1?Array.from(P)[0]:void 0,paramCount:O.size===1?Array.from(O)[0]:void 0,exported:V.size===1?Array.from(V)[0]:void 0,filePath:K.size===1?Array.from(K)[0]:void 0}}datalogRequiresStructuralSourceScan(i){return this.getDatalogQueryAttributes(i).some(l=>uqt.has(l))}listFilesForDatalogScan(i,l){let _=new Set,v=K=>{K&&_.add(K.replace(/\\/g,"/"))},T=Array.isArray(i.candidateFiles)?i.candidateFiles.map(K=>this.normalizeCandidatePath(K)??String(K||"").replace(/\\/g,"/")).filter(K=>typeof K=="string"&&K.length>0):[],P=this.normalizeDatalogLangFilter(i.lang);if(T.length>0)for(let K of T)v(K);let O=typeof i.scope=="string"?String(i.scope).trim().replace(/\\/g,"/"):"";if(_.size===0&&O)if(O.includes("#"))v(O.split("#")[0]);else if(O.endsWith("/")){let K=this.collectFilesUnderDirectoryScope(O);for(let te of K)v(te)}else v(O);else if(_.size===0&&i.asOf)for(let K of this.getSnapshotFiles(String(i.asOf)))v(K);if(_.size===0)for(let K of this.fileToChunkMap.keys())v(K);let V=Array.from(_).filter(Boolean).filter(K=>this.matchesDatalogLangFilter(K,P)).sort();return V.length===0&&l.push("No candidate files found for datalog scan."),V}normalizeDatalogLangFilter(i){let l=Array.isArray(i)?i:typeof i=="string"?[i]:[];return Array.from(new Set(l.map(_=>String(_||"").trim()).filter(Boolean))).sort()}matchesDatalogLangFilter(i,l){if(l.length===0)return!0;let _=cT(i);return!!(_&&l.includes(_))}datalogCursorDescriptor(i){let _={datalog:i.datalog||null,prefilter:i.prefilter??null},v={scope:i.scope??null,candidateFiles:Array.isArray(i.candidateFiles)?[...i.candidateFiles].sort():null,asOf:i.asOf??null,projectFilter:i.projectFilter??null},T=this.normalizeDatalogLangFilter(i.lang).join(",");return{queryHash:qbt.default.createHash("sha1").update(JSON.stringify(_)).digest("hex"),scopeHash:qbt.default.createHash("sha1").update(JSON.stringify(v)).digest("hex"),langKey:T,orderingVersion:"file_path_asc,node_path_asc:v1"}}encodeDatalogCursor(i){let l=JSON.stringify(i);return Buffer.from(l,"utf8").toString("base64url")}decodeDatalogCursor(i){try{let l=Buffer.from(String(i),"base64url").toString("utf8"),_=JSON.parse(l);return!_||typeof _!="object"?null:_}catch{return null}}queryIndexedNodesForFile(i){let l=String(i||"").replace(/\\/g,"/");if(!l)return[];let _=this.fileToChunkMap.get(l),v=_?[_]:this.chunkDbs,T=`SELECT CAST(n.id AS TEXT) AS node_id,
|
|
32928
|
+
`,"utf8");try{await lv.add({fs:O_,dir:this.repoDir,filepath:".gitignore"})}catch{}r0(`[GitHistoryStore] restored missing .gitignore at ${i}`)}catch(l){xnn(`[GitHistoryStore] failed to recreate .gitignore: ${l?.message||l}`)}}normalizeLogicalPath(i){return String(i||"").replace(/\\/g,"/").replace(/^(?:\.\/)+/,"").replace(/^\/+/,"")}gitExists(){try{return(0,xde.execFileSync)("git",["--version"],{cwd:this.repoDir,stdio:"ignore"}),!0}catch{return!1}}readProjectWorktreeEntry(i){let l=hZ.join(this.baseDir,i),_;try{_=O_.lstatSync(l)}catch{return null}if(_.isSymbolicLink()){let v=O_.readlinkSync(l);return{content:Buffer.from(v,"utf8"),mode:"120000",entryKind:"symlink",symlinkTarget:v}}return _.isFile()?{content:O_.readFileSync(l),mode:_.mode&73?"100755":"100644",entryKind:"file"}:null}createSnapshotNative(i,l,_,v){let P=(typeof _=="string"?_.match(/^AST-Restore-Trace-Id:\s*(.+)$/m):null)?.[1]?.trim()||null,O=l;if(!O)try{O=(0,xde.execFileSync)("git",["rev-parse","HEAD"],{cwd:this.repoDir,encoding:"utf8"}).trim()}catch{O=void 0}let V=new Map,K=new Map,te=Date.now();try{r0("[GitHistoryStore] native snapshot start",{traceId:P,repoDir:this.repoDir,memberCount:i.length,parentOid:O||null})}catch{}for(let Ie=0;Ie<i.length;Ie++){let ye=i[Ie];if(ye.content==null)throw new Error(`Direct snapshot requires content for ${ye.logicalPath}`);let ve=Buffer.isBuffer(ye.content)?ye.content:Buffer.from(ye.content),ft=this.normalizeLogicalPath(ye.logicalPath);if(!ft)throw new Error("Direct snapshot requires non-empty logicalPath");K.set(ft,U7t(ye.mode,ye.entryKind==="symlink"?"120000":"100644"));let vt=Date.now();try{r0("[GitHistoryStore] native hash-object start",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length})}catch{}let Tt;try{Tt=(0,xde.execFileSync)("git",["hash-object","-w","--stdin"],{cwd:this.repoDir,input:ve}).toString("utf8").trim()}catch(bn){try{xnn("[GitHistoryStore] native hash-object failed",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length,durationMs:Date.now()-vt,message:bn?.message||String(bn),status:bn?.status??null,signal:bn?.signal??null,stdout:bn?.stdout?String(bn.stdout).slice(0,500):null,stderr:bn?.stderr?String(bn.stderr).slice(0,500):null})}catch{}throw bn}let an=Date.now()-vt;try{(an>1e3||Ie<3||Ie===i.length-1)&&r0("[GitHistoryStore] native hash-object done",{traceId:P,repoDir:this.repoDir,index:Ie+1,total:i.length,logicalPath:ft,bytes:ve.length,durationMs:an,oid:Tt})}catch{}V.set(ft,Tt)}try{r0("[GitHistoryStore] native hash-object phase complete",{traceId:P,repoDir:this.repoDir,memberCount:i.length,durationMs:Date.now()-te})}catch{}let oe=hZ.join(this.repoDir,`.pando-index-${process.pid}-${Date.now()}`),q={...process.env,GIT_INDEX_FILE:oe};try{let Ie=Date.now();try{r0("[GitHistoryStore] native read-tree begin",{traceId:P,repoDir:this.repoDir,tmpIndex:oe})}catch{}(0,xde.execFileSync)("git",["read-tree","--empty"],{cwd:this.repoDir,env:q});try{r0("[GitHistoryStore] native read-tree complete",{traceId:P,repoDir:this.repoDir,durationMs:Date.now()-Ie})}catch{}let ye=Array.from(V.keys()).sort((Ut,gt)=>Ut.localeCompare(gt)),ve=Date.now();for(let Ut of ye){let gt=V.get(Ut),Mt=K.get(Ut)||"100644";(0,xde.execFileSync)("git",["update-index","--add","--cacheinfo",Mt,gt,Ut],{cwd:this.repoDir,env:q})}try{r0("[GitHistoryStore] native update-index complete",{traceId:P,repoDir:this.repoDir,entryCount:ye.length,durationMs:Date.now()-ve})}catch{}let ft=Date.now();try{r0("[GitHistoryStore] native write-tree begin",{traceId:P,repoDir:this.repoDir,entryCount:ye.length})}catch{}let vt=(0,xde.execFileSync)("git",["write-tree"],{cwd:this.repoDir,env:q}).toString("utf8").trim();try{r0("[GitHistoryStore] native write-tree complete",{traceId:P,repoDir:this.repoDir,treeOid:vt,durationMs:Date.now()-ft})}catch{}let Tt=["commit-tree",vt];O&&Tt.push("-p",O),_&&Tt.push("-m",_);let an=Date.now();try{r0("[GitHistoryStore] native commit-tree begin",{traceId:P,repoDir:this.repoDir,treeOid:vt,parentOid:O||null})}catch{}let bn=(0,xde.execFileSync)("git",Tt,{cwd:this.repoDir}).toString("utf8").trim();try{r0("[GitHistoryStore] native commit-tree complete",{traceId:P,repoDir:this.repoDir,commitOid:bn,durationMs:Date.now()-an})}catch{}let sn=Date.now();try{r0("[GitHistoryStore] native update-ref begin",{traceId:P,repoDir:this.repoDir,commitOid:bn})}catch{}(0,xde.execFileSync)("git",["update-ref","refs/heads/master",bn],{cwd:this.repoDir});try{r0("[GitHistoryStore] native update-ref complete",{traceId:P,repoDir:this.repoDir,commitOid:bn,durationMs:Date.now()-sn})}catch{}return{snapshotId:bn,parent:O}}finally{try{O_.unlinkSync(oe)}catch{}try{O_.unlinkSync(`${oe}.lock`)}catch{}}}async readObject(i){let{object:l}=await lv.readObject({fs:O_,dir:this.repoDir,oid:i});return Buffer.from(l)}async hasObject(i){try{return await lv.readObject({fs:O_,dir:this.repoDir,oid:i}),!0}catch{return!1}}async createSnapshot(i,l){Vy(l,"Snapshot cancelled"),await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot (streaming) with ${i.members.length} members`);let _=[...i.members].map(jt=>({...jt,logicalPath:this.normalizeLogicalPath(jt.logicalPath)})).filter(jt=>!!jt.logicalPath).sort((jt,er)=>jt.logicalPath.localeCompare(er.logicalPath)),v=this.gitExists()&&!l;try{v?Lh.info("[GitHistoryStore] Using native git snapshot path",{members:_.length}):Lh.info("[GitHistoryStore] Using JS snapshot path",{members:_.length,git:!1,cancellable:!!l})}catch{}if(v)try{return this.createSnapshotNative(_,i.parent,i.message,i.when).snapshotId}catch(jt){try{Lh.warn(`[GitHistoryStore] Native git path failed; falling back to JS path: ${jt?.message||jt}`)}catch{}}let T=Date.now(),P=jt=>jt.toString("hex"),O=jt=>require("crypto").createHash("sha1").update(jt).digest(),V=jt=>{let er=Buffer.from(`blob ${jt.length}\0`,"utf8"),$n=Buffer.concat([er,jt]);return P(O($n))},K=Math.max(1,Math.min(64,Number(process.env.SNAPSHOT_BLOB_CONCURRENCY||16))),te=String(process.env.SNAPSHOT_PRECOMPUTE_OIDS||"1")!=="0";try{Lh.info("[GitHistoryStore] JS snapshot settings",{SNAPSHOT_BLOB_CONCURRENCY:K,SNAPSHOT_PRECOMPUTE_OIDS:te})}catch{}let oe=new Map,q=new Map,Ie=0,ye=0,ve=0,ft=_.map(jt=>({path:jt.logicalPath,buf:Buffer.isBuffer(jt.content)?jt.content:Buffer.from(jt.content),mode:U7t(jt.mode,jt.entryKind==="symlink"?"120000":"100644")}));for(let jt of ft)q.set(jt.path,jt.mode);let vt=async()=>{for(;;){Vy(l,"Snapshot cancelled");let jt;if(Ie<ft.length)jt=ft[Ie++];else break;let er;if(te)try{let $n=V(jt.buf);await this.hasObject($n)&&(er=$n,ve++)}catch{}if(er||(er=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:jt.buf}),ye++),Vy(l,"Snapshot cancelled"),!er)throw new Error("Failed to compute blob object id");oe.set(jt.path,er)}},Tt=Array.from({length:Math.min(K,ft.length)},()=>vt());await Promise.all(Tt),Vy(l,"Snapshot cancelled"),r0(`[GitHistoryStore] Blobs ready wrote=${ye} skipped=${ve} in ${Date.now()-T}ms`);let an=new R4e(this.repoDir),bn=Array.from(oe.keys()).sort((jt,er)=>jt.localeCompare(er));for(let jt of bn)Vy(l,"Snapshot cancelled"),await an.addEntry(jt,oe.get(jt),q.get(jt)||"100644");Vy(l,"Snapshot cancelled");let sn=Date.now(),Ut=await an.finish();r0(`[GitHistoryStore] Wrote tree(s). root=${Ut} in ${Date.now()-sn}ms`);let gt=i.parent;if(!gt)try{gt=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}Vy(l,"Snapshot cancelled");let Mt=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),We=new Date(Mt*1e3).getTimezoneOffset(),In=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:gt?[gt]:[],tree:Ut,author:{name:"ast-db",email:"ast-db@example.com",timestamp:Mt,timezoneOffset:We},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:Mt,timezoneOffset:We}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:In,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${In}`),In}async listSnapshotMembers(i){await this.ensureInitialized();let l=T=>Math.round((T||0)/(1024*1024)),_=()=>{let T=process.memoryUsage();return`rss=${l(T.rss)}MB heapUsed=${l(T.heapUsed)}MB heapTotal=${l(T.heapTotal)}MB`},v=[];return r0(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${i}) start (${_()})`),await lv.walk({fs:O_,dir:this.repoDir,trees:[lv.TREE({ref:i})],map:async(T,[P])=>{if(!P)return;let O=await P.type();if(O==="blob"){let V=await P.oid(),K;try{K=U7t(await P.mode())}catch{}let te;if(K==="120000")try{te=(await this.readObject(V)).toString("utf8")}catch{}v.push({logicalPath:T,objectId:V,entryKind:K==="120000"?"symlink":"file",mode:K||(O==="blob"?"100644":void 0),symlinkTarget:te})}}}),r0(`[${new Date().toISOString()}] [GitHistoryStore] listSnapshotMembers(${i}) -> ${v.length} blobs`),v.filter(T=>T.logicalPath&&T.logicalPath!==".").map(T=>({logicalPath:T.logicalPath.replace(/^\.\//,""),objectId:T.objectId}))}async readCommit(i){let{commit:l}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:i});return{message:l.message,committer:l.committer}}async readCommitParent(i){let{commit:l}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:i});return Array.isArray(l.parent)&&l.parent.length>0?String(l.parent[0]):void 0}async createSnapshotFromDisk(i,l){Vy(l,"Snapshot cancelled"),await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (streaming) with ${i.relPaths.length} members`);let _=[...i.relPaths].map(Ie=>this.normalizeLogicalPath(Ie)).filter(Boolean).sort((Ie,ye)=>Ie.localeCompare(ye)),v=Date.now(),T=new R4e(this.repoDir),P=0;for(let Ie of _){Vy(l,"Snapshot cancelled");let ye=hZ.join(this.baseDir,Ie);try{let ve=this.readProjectWorktreeEntry(Ie);if(!ve)continue;let ft=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:ve.content});await T.addEntry(Ie,ft,ve.mode),P++}catch{}}r0(`[GitHistoryStore] Wrote ${P} blobs (disk) in ${Date.now()-v}ms`),Vy(l,"Snapshot cancelled");let O=Date.now(),V=await T.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk). root=${V} in ${Date.now()-O}ms`);let K=i.parent;if(!K)try{K=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}Vy(l,"Snapshot cancelled");let te=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),oe=new Date(te*1e3).getTimezoneOffset(),q=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:K?[K]:[],tree:V,author:{name:"ast-db",email:"ast-db@example.com",timestamp:te,timezoneOffset:oe},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:te,timezoneOffset:oe}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:q,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${q}`),q}async createSnapshotFromDiskAndCapturedIfChanged(i){await this.ensureInitialized();let l=new Map;for(let ve of i.capturedMembers||[]){let ft=this.normalizeLogicalPath(ve.logicalPath);!ft||ve.content==null||l.has(ft)||l.set(ft,Buffer.isBuffer(ve.content)?ve.content:Buffer.from(ve.content))}r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk+captured (diff) with ${i.relPaths.length} members, captured=${l.size}`);let _=[...i.relPaths].map(ve=>this.normalizeLogicalPath(ve)).filter(Boolean).sort((ve,ft)=>ve.localeCompare(ft)),v=Date.now(),T=new R4e(this.repoDir),P=0,O=0,V=0;for(let ve of _)try{let ft=l.get(ve),vt=ft?{content:ft,mode:"100644"}:this.readProjectWorktreeEntry(ve);if(!vt)continue;let Tt=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:vt.content});await T.addEntry(ve,Tt,vt.mode),P++,ft?O++:V++}catch{}r0(`[GitHistoryStore] Wrote ${P} blobs (captured=${O}, disk=${V}) in ${Date.now()-v}ms`);let K=Date.now(),te=await T.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk+captured). root=${te} in ${Date.now()-K}ms`);let oe=i.parent;if(!oe)try{oe=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}if(oe)try{let{commit:ve}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:oe});if(ve?.tree===te){r0("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:oe,tree:te});let ft=await this.readCommitParent(oe);return{snapshotId:oe,identical:!0,parent:ft}}}catch(ve){r0("[GitHistoryStore] Parent read failed; proceeding with commit",{error:ve?.message||String(ve)})}let q=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),Ie=new Date(q*1e3).getTimezoneOffset(),ye=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:oe?[oe]:[],tree:te,author:{name:"ast-db",email:"ast-db@example.com",timestamp:q,timezoneOffset:Ie},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:q,timezoneOffset:Ie}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:ye,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${ye}`),{snapshotId:ye,identical:!1,parent:oe}}async createSnapshotFromDiskIfChanged(i){await this.ensureInitialized(),r0(`[${new Date().toISOString()}] [GitHistoryStore] Creating snapshot from disk (diff) with ${i.relPaths.length} members`);let l=[...i.relPaths].map(q=>this.normalizeLogicalPath(q)).filter(Boolean).sort((q,Ie)=>q.localeCompare(Ie)),_=Date.now(),v=new R4e(this.repoDir),T=0;for(let q of l)try{let Ie=this.readProjectWorktreeEntry(q);if(!Ie)continue;let ye=await lv.writeBlob({fs:O_,dir:this.repoDir,blob:Ie.content});await v.addEntry(q,ye,Ie.mode),T++}catch{}r0(`[GitHistoryStore] Wrote ${T} blobs (disk) in ${Date.now()-_}ms`);let P=Date.now(),O=await v.finish();r0(`[GitHistoryStore] Wrote tree(s) (disk). root=${O} in ${Date.now()-P}ms`);let V=i.parent;if(!V)try{V=await lv.resolveRef({fs:O_,dir:this.repoDir,ref:"HEAD"})}catch{}if(V)try{let{commit:q}=await lv.readCommit({fs:O_,dir:this.repoDir,oid:V});if(q?.tree===O){r0("[GitHistoryStore] Snapshot identical to parent; skipping commit",{parentOid:V,tree:O});let Ie=await this.readCommitParent(V);return{snapshotId:V,identical:!0,parent:Ie}}}catch(q){r0("[GitHistoryStore] Parent read failed; proceeding with commit",{error:q?.message||String(q)})}let K=i.when?Math.floor(i.when/1e3):Math.floor(Date.now()/1e3),te=new Date(K*1e3).getTimezoneOffset(),oe=await lv.commit({fs:O_,dir:this.repoDir,message:i.message,parent:V?[V]:[],tree:O,author:{name:"ast-db",email:"ast-db@example.com",timestamp:K,timezoneOffset:te},committer:{name:"ast-db",email:"ast-db@example.com",timestamp:K,timezoneOffset:te}});return await lv.writeRef({fs:O_,dir:this.repoDir,ref:"refs/heads/master",value:oe,force:!0}),r0(`[GitHistoryStore] Snapshot commit oid ${oe}`),{snapshotId:oe,identical:!1,parent:V}}}});var Ede={};SD(Ede,{computeEffectiveMap:()=>Hbt,diffEffectiveSets:()=>Jbt,getEntryAtSnapshot:()=>YQe,getFileAtSnapshot:()=>Dnn,getFileAtSnapshotPath:()=>mTn,getSnapshotDatabase:()=>Inn});function _Tn(u,i){let l=[],_=i,v=new Set;for(;_&&!v.has(_);){v.add(_),l.push(_);let T=u.prepare("SELECT parents FROM snapshots WHERE snapshot_id = ?").get(_),P=T&&typeof T.parents=="string"&&T.parents.length>0?String(T.parents):null;_=(P?P.split(",")[0].trim():void 0)||void 0}return l.reverse(),l}function Hbt(u,i){let l=Enn.get(i);if(l)return l;let _=_Tn(u,i),v=new Map,T=!1;for(let P of _){let O=u.prepare("SELECT logical_path, object_id, entry_kind, mode, symlink_target FROM snapshot_members WHERE snapshot_id = ?").all(P);O.length>0&&(T=!0);for(let V of O){let K=V.logical_path,te=V.object_id;if(K)if(te&&te.length>0){let oe=V.entry_kind==="symlink"?"symlink":"file";v.set(K,{oid:te,src:P,entryKind:oe,mode:V.mode??(oe==="symlink"?"120000":"100644"),symlinkTarget:V.symlink_target??null})}else v.delete(K)}}return(v.size>0||T)&&Enn.set(i,v),v}function Jbt(u,i,l){let _=Hbt(u,i),v=l?Hbt(u,l):new Map,T=[],P=[],O=[],V=new Set(v.keys());for(let[K,te]of _){let oe=v.get(K);oe?Tnn(oe)!==Tnn(te)&&P.push(K):T.push(K),V.delete(K)}for(let K of V)O.push(K);return{added:T,changed:P,deleted:O}}function Tnn(u){return[u.entryKind,u.mode||"",u.oid,u.symlinkTarget||""].join("\0")}async function YQe(u,i,l,_){let T=Hbt(u,l).get(_);if(!T)return null;let O=await new M4e({baseDir:i}).readObject(T.oid);return{content:O,sourceSnapshot:T.src,oid:T.oid,entryKind:T.entryKind,mode:T.mode,symlinkTarget:T.entryKind==="symlink"?T.symlinkTarget??O.toString("utf8"):null}}async function Dnn(u,i,l,_){let v=await YQe(u,i,l,_);return!v||v.entryKind!=="file"?null:{content:v.content,sourceSnapshot:v.sourceSnapshot,oid:v.oid}}function Inn(u){let i=[uXe(u),Ann.default.join(Sy(u),"pando.db"),bO(u,0)];for(let l of i)if(Cnn.existsSync(l))try{let _=new GS(l,{readOnly:!0,fileMustExist:!0});try{_.pragma("busy_timeout = 10000")}catch{}return _}catch(_){Su("SnapshotEffective","failed to open snapshot DB",{dbPath:l,error:_?.message??_})}return null}async function mTn(u,i,l){let _=Inn(u);if(!_)return null;try{return await Dnn(_,u,i,l)}finally{try{_.close()}catch{}}}var Cnn,Ann,H7t,Enn,Oie=_c(()=>{"use strict";CD();Cnn=ll(require("fs")),Ann=ll(require("path"));V7t();FM();XT();H7t=class{constructor(i=100){this.max=i,this.map=new Map}get(i){let l=this.map.get(i);return l!==void 0&&(this.map.delete(i),this.map.set(i,l)),l}set(i,l){if(this.map.has(i)&&this.map.delete(i),this.map.set(i,l),this.map.size>this.max){let _=this.map.keys().next().value;this.map.delete(_)}}},Enn=new H7t(64)});function hTn(u){return u instanceof $bt||typeof u=="object"&&u!==null&&u.error_code==="invalid_fts_query"}function jnn(u){return u instanceof Xbt||typeof u=="object"&&u!==null&&u.error_code==="fts_storage_error"}function GDe(u){return hTn(u)||jnn(u)}function gTn(u){let i=String(u?.message||u||"").toLowerCase();return i.includes("readonly database")||i.includes("unable to open database file")||i.includes("database disk image is malformed")||i.includes("no such table")||i.includes("permission denied")||i.includes("operation not permitted")}function yTn(u,i){let l=u?.details?.sqliteMessage||u?.message||String(u),_=jnn(u),v=GDe(u)?{...u.details}:{query:i,adaptedQuery:i,sqliteMessage:l,syntax:"SQLite FTS5 MATCH"},T=_?`FTS index read failed: ${l}`:`FTS query failed: ${l}`;return{error:T,error_code:_?"fts_storage_error":"invalid_fts_query",details:v,warning:_?`${T}. ${Wnn}`:`${T}. ${Bnn}`}}function jDe(u,i,l,_){let v=yTn(l,_),T=String(v.details.sqliteMessage||v.error);return u.ftsErrors=[...u.ftsErrors??[],T],u.ftsError=v.details,v.error_code==="invalid_fts_query"?u.ftsSyntaxHint=Bnn:u.ftsStorageHint=Wnn,i.push(v.warning),v}function znn(u,i=new Set){if(!u||typeof u!="object"||i.has(u))return null;i.add(u);let l=u;if(l.constructor&&l.constructor.name==="B"&&typeof l.ga=="string")return l.constructor;for(let _ of Object.getOwnPropertyNames(u))try{let v=znn(u[_],i);if(v)return v}catch{}return null}function vTn(){if(ZQe)return ZQe;if(ZQe===null)throw new Error("DataScript keyword constructor unavailable");let u=iYe.empty_db({":seed":{":db/unique":":db.unique/identity"}}),i=znn(u);if(!i)throw ZQe=null,new Error("Failed to locate DataScript keyword constructor");return ZQe=i,i}function BM(u){let i=String(u||"").trim();if(!i)throw new Error("DataScript keyword attr cannot be empty");let l=i.startsWith(":")?i.slice(1):i,_=`:${l}`;if(J7t.has(_))return J7t.get(_);let v=l.indexOf("/"),T=v>=0?l.slice(0,v):null,P=v>=0?l.slice(v+1):l,O=new(vTn())(T,P,l,null);return J7t.set(_,O),O}function L7(u){if(!bTn)return()=>{};let i=u||"UnifiedDb",l=process.hrtime.bigint(),_=l;return(v,T)=>{let P=process.hrtime.bigint(),O=Number(P-l)/1e6,V=Number(P-_)/1e6;_=P;let K={stage:v,sinceStartMs:O,sinceLastMs:V,...T||{}};try{console.log("[UnifiedDb][PROFILE]",JSON.stringify({label:i,...K}))}catch{console.log("[UnifiedDb][PROFILE]",i,K)}}}function gZ(u,i){let l=new Date().toISOString();try{console.log(`[${l}] [UnifiedDb][DEBUG] ${u}`,i??{})}catch{console.log(`[${l}] [UnifiedDb][DEBUG] ${u}`)}}function Fie(u="nodes"){return`(SELECT path FROM dict_files WHERE id = ${u}.file_id)`}function STn(u="nodes"){return`(SELECT text FROM dict_symbols WHERE id = ${u}.name_id)`}function xTn(u="nodes"){return`(SELECT text FROM dict_kinds WHERE id = ${u}.kind_id)`}function tYe(u){let i=new Set,l=_=>{if(!_)return;let v=_.trim();if(!v)return;let T=v.toLowerCase();if(Object.prototype.hasOwnProperty.call(Pnn,T)){for(let P of Pnn[T])i.add(P);return}i.add(v)};if(Array.isArray(u))for(let _ of u)l(_);return Array.from(i)}function nYe(u){let i=[],l=[];for(let _ of u||[]){let v=String(_||"").trim();if(v){if(ETn.has(v.toLowerCase())){i.push(v);continue}l.push(v)}}return{contentDriven:i,structural:l}}function pve(u){if(typeof u!="string")return null;let i=u.indexOf("#");if(i===-1)return null;let l=u.slice(i+1),_=l.indexOf(":"),T=(_===-1?l:l.slice(0,_)).match(/^([0-9]+)-([0-9]+)$/);if(!T)return null;let P=Number(T[1]),O=Number(T[2]);return Number.isNaN(P)||Number.isNaN(O)?null:{start:P,end:O}}function rYe(u,i){let l=pve(u),_=pve(i);if(l&&_){if(l.start!==_.start)return l.start-_.start;if(l.end!==_.end)return l.end-_.end}return String(u).localeCompare(String(i))}function TTn(u){return String(u||"").toLowerCase().match(/[a-z0-9_]+/g)||[]}function wnn(u){let i=String(u||"").trim();if(!i)return null;let l=i.toLowerCase(),_=(T,P,O)=>{let V=T.trim().toLowerCase();if(!V)return!0;if(V.startsWith('"')&&V.endsWith('"')&&V.length>=2)return P.toLowerCase().includes(V.slice(1,-1));if(V.endsWith("*")){let K=V.slice(0,-1);return K.length>0&&O.some(te=>te.startsWith(K))}return O.includes(V)||P.toLowerCase().includes(V)},v=(T,P,O)=>{let V=T.match(/^\s*([A-Za-z0-9_]+)\s+NEAR\/(\d+)\s+([A-Za-z0-9_]+)\s*$/i);if(V){let K=V[1].toLowerCase(),te=Math.max(0,Number(V[2])||0),oe=V[3].toLowerCase(),q=[],Ie=[];return O.forEach((ye,ve)=>{ye===K&&q.push(ve),ye===oe&&Ie.push(ve)}),q.some(ye=>Ie.some(ve=>Math.abs(ye-ve)<=te))}if(/\bOR\b/i.test(T))return T.split(/\bOR\b/i).some(K=>v(K,P,O));if(/\bNOT\b/i.test(T)){let[K,...te]=T.split(/\bNOT\b/i),oe=te.join(" ").trim();return v(K,P,O)&&!v(oe,P,O)}return/\bAND\b/i.test(T)?T.split(/\bAND\b/i).every(K=>v(K,P,O)):T.includes("|")?T.split("|").some(K=>v(K,P,O)):_(T,P,O)};return T=>{let P=String(T||""),O=TTn(P);return v(l,P,O)}}function Nnn(u,i){let l=Array.from(new Set(u.filter(Boolean))),_=Array.from(new Set(i.filter(Boolean))),v=new Set(l),T=new Set(_),P=_.filter(Ie=>!v.has(Ie)),O=l.filter(Ie=>!T.has(Ie)),V={},K=l.slice(0,3),te=_.slice(0,3),oe=P.slice(0,3),q=O.slice(0,3);return K.length>0&&(V.beforeTop3=K),te.length>0&&(V.afterTop3=te),oe.length>0&&(V.addedTop3=oe),q.length>0&&(V.removedTop3=q),V}function knn(u){if(!Array.isArray(u))return[];let i=[];for(let l of u){if(!l)continue;let _=typeof l.path=="string"?String(l.path):"";_&&i.push(_)}return i}function Rnn(u){if(!Array.isArray(u))return[];let i=[];for(let l of u){if(!l)continue;let _=typeof l.file_path=="string"?String(l.file_path):typeof l.path=="string"?String(l.path).split("#")[0]:"";_&&i.push(_)}return i}function Mnn(u,i){let l={},_=Nnn(knn(u),knn(i)),v=Nnn(Rnn(u),Rnn(i));return Object.keys(_).length>0&&(l.paths=_),Object.keys(v).length>0&&(l.files=v),l}function q7t(u,i){try{return typeof u?.hasModifier=="function"&&u.hasModifier(i)}catch{return!1}}function zDe(u){let i=Td.extname(String(u||"")).toLowerCase();return CTn.has(i)}function ATn(u){return Pf.Node.isFunctionDeclaration(u)||Pf.Node.isFunctionExpression(u)||Pf.Node.isArrowFunction(u)||Pf.Node.isClassDeclaration(u)||Pf.Node.isClassExpression(u)||Pf.Node.isInterfaceDeclaration(u)||Pf.Node.isEnumDeclaration(u)||Pf.Node.isEnumMember(u)||Pf.Node.isTypeAliasDeclaration(u)||Pf.Node.isModuleDeclaration(u)||Pf.Node.isMethodDeclaration(u)||Pf.Node.isMethodSignature(u)||Pf.Node.isPropertyDeclaration(u)||Pf.Node.isPropertySignature(u)||Pf.Node.isGetAccessorDeclaration(u)||Pf.Node.isSetAccessorDeclaration(u)||Pf.Node.isConstructorDeclaration(u)||Pf.Node.isVariableDeclaration(u)}function DTn(u){return Pf.Node.isReturnStatement(u)||Pf.Node.isIfStatement(u)||Pf.Node.isForStatement(u)||Pf.Node.isForInStatement(u)||Pf.Node.isForOfStatement(u)||Pf.Node.isWhileStatement(u)||Pf.Node.isDoStatement(u)||Pf.Node.isSwitchStatement(u)||Pf.Node.isCaseClause(u)||Pf.Node.isDefaultClause(u)||Pf.Node.isTryStatement(u)||Pf.Node.isCatchClause(u)||Pf.Node.isThrowStatement(u)||Pf.Node.isExpressionStatement(u)||Pf.Node.isBlock(u)}function ITn(u){try{if(typeof u?.getName=="function"){let i=u.getName();if(typeof i=="string"&&i.length>0)return i}}catch{}try{if(Pf.Node.isConstructorDeclaration(u))return"constructor";if(Pf.Node.isIdentifier(u)||Pf.Node.isPrivateIdentifier(u)){let l=u.getText();return l.length>0?l:null}if(Pf.Node.isVariableDeclaration(u)||Pf.Node.isEnumMember(u))return typeof u.getName=="function"?u.getName()??null:null;let i=u.getParent();if(Pf.Node.isArrowFunction(u)||Pf.Node.isFunctionExpression(u)){if(i&&Pf.Node.isVariableDeclaration(i))return i.getName();if(i&&(Pf.Node.isPropertyAssignment(i)||Pf.Node.isPropertyDeclaration(i)||Pf.Node.isPropertySignature(i)))return i.getName?.()??null;if(i&&Pf.Node.isShorthandPropertyAssignment(i))return i.getNameNode()?.getText()??null;if(i&&Pf.Node.isExportAssignment(i))return"default"}}catch{}return null}function PTn(u){try{if(Pf.Node.isFunctionDeclaration(u)||Pf.Node.isMethodDeclaration(u)||Pf.Node.isConstructorDeclaration(u)||Pf.Node.isFunctionExpression(u)||Pf.Node.isArrowFunction(u)){let i=u.getParameters?.();if(Array.isArray(i))return i.length}}catch{}return null}function wTn(u){let i=Zue(u),l=(()=>{try{return u.getStart?.(!1)}catch{return}})(),_=typeof l=="number"&&Number.isFinite(l)?l:(()=>{try{let P=u.getStart?.();return typeof P=="number"&&Number.isFinite(P)?P:0}catch{return 0}})(),v=(()=>{try{return u.getEnd?.()}catch{return}})(),T=typeof v=="number"&&Number.isFinite(v)&&v>=_?v:_;return{start:_,end:T}}function NTn(u,i){if(Pf.Node.isSourceFile(u))return{start:0,end:typeof i=="number"&&Number.isFinite(i)?Math.max(0,i):0};try{let l=u?.getBody?.();if(!l||typeof l.getStart!="function"||typeof l.getEnd!="function")return null;let _=typeof l.getKindName=="function"?String(l.getKindName()):"",v=_==="Block"||_==="ModuleBlock",T=l.getStart(),P=l.getEnd(),O=v?T+1:T,V=v?P-1:P;return!Number.isFinite(O)||!Number.isFinite(V)||V<O?null:{start:O,end:V}}catch{return null}}function kTn(u){let i=u.getKindName();return!(i==="SourceFile"||i==="SyntaxList"||i==="EndOfFileToken"||i.endsWith("Token"))}function RTn(u){let i=u.getParent?.();if(!i)return null;try{if(Pf.Node.isIfStatement(i)){if(i.getExpression()===u)return"condition";if(i.getThenStatement()===u)return"then";if(i.getElseStatement()===u)return"else"}if(Pf.Node.isCallExpression(i)||Pf.Node.isNewExpression(i)){if(i.getExpression?.()===u)return"callee";if((i.getArguments?.()||[]).some(l=>l===u))return"argument"}if(Pf.Node.isConditionalExpression(i)){if(i.getCondition()===u)return"condition";if(i.getWhenTrue()===u)return"then";if(i.getWhenFalse()===u)return"else"}if(Pf.Node.isReturnStatement(i)&&i.getExpression?.()===u)return"value";if(Pf.Node.isExpressionStatement(i)&&i.getExpression()===u)return"expression";if(Pf.Node.isVariableDeclaration(i)){if(i.getNameNode?.()===u)return"name";if(i.getInitializer?.()===u)return"initializer"}if(Pf.Node.isPropertyDeclaration(i)||Pf.Node.isPropertyAssignment(i)){if(i.getNameNode?.()===u)return"name";if(i.getInitializer?.()===u)return"initializer"}if(Pf.Node.isBinaryExpression(i)){if(i.getLeft()===u)return"left";if(i.getRight()===u)return"right"}if(Pf.Node.isFunctionDeclaration(i)||Pf.Node.isFunctionExpression(i)||Pf.Node.isArrowFunction(i)||Pf.Node.isMethodDeclaration(i)||Pf.Node.isConstructorDeclaration(i)){if(i.getBody?.()===u)return"body";if((i.getParameters?.()||[]).some(l=>l===u))return"parameter"}if(Pf.Node.isBlock(i))return"statement"}catch{}return null}function Onn(u){let i=Td.dirname(Td.resolve(u));try{for(;;){let l=Td.join(i,"tsconfig.json");if(TO.existsSync(l))return l;let _=Td.dirname(i);if(_===i)break;i=_}}catch{}return Td.resolve("tsconfig.json")}var TO,Td,qbt,Fnn,Pf,Bie,iYe,Bnn,Wnn,$bt,Xbt,ZQe,J7t,bTn,eYe,Pnn,ETn,$7t,Kbt,K7t,CTn,Lnn,MTn,LTn,AE,Tde=_c(()=>{"use strict";TO=ll(require("fs")),Td=ll(require("path")),qbt=ll(require("crypto")),Fnn=require("child_process"),Pf=ll(MI()),Bie=ll(v6e());Gye();NXe();b3();FM();z4t();CD();w$t();cDe();pXe();Pq();H3t();Bvt();XT();J0t();S3t();iYe=R$t(),Bnn='Use valid SQLite FTS5 MATCH syntax, e.g. foo*, "foo bar", foo AND bar, foo OR bar, or foo NEAR/1 bar.',Wnn="The FTS index could not be read. Rebuild or repair the Pando index, or check the security helper data-directory permissions.",$bt=class extends Error{constructor(l){super(`SQLite rejected FTS MATCH expression: ${l.sqliteMessage}`);this.error_code="invalid_fts_query";this.name="FtsQueryRejectedError",this.details={query:l.query,adaptedQuery:l.adaptedQuery,shard:l.shard,sqliteMessage:l.sqliteMessage,syntax:"SQLite FTS5 MATCH"}}},Xbt=class extends Error{constructor(l){super(`SQLite could not read FTS index: ${l.sqliteMessage}`);this.error_code="fts_storage_error";this.name="FtsStorageError",this.details={query:l.query,adaptedQuery:l.adaptedQuery,shard:l.shard,sqliteMessage:l.sqliteMessage}}};J7t=new Map;bTn=process.env.AST_FIND_NODES_PROFILING==="1";eYe={reference:1,call:2,new:4,type:8,import:16,export:32};Pnn={function:["Function","Method","FunctionDeclaration","FunctionExpression","ArrowFunction","MethodDeclaration","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],functions:["Function","Method","FunctionDeclaration","FunctionExpression","ArrowFunction","MethodDeclaration","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],class:["Class","ClassDeclaration","ClassExpression"],classes:["Class","ClassDeclaration","ClassExpression"],struct:["Struct"],structs:["Struct"],union:["Union"],unions:["Union"],interface:["Interface","InterfaceDeclaration"],interfaces:["Interface","InterfaceDeclaration"],method:["Method","MethodDeclaration","MethodSignature","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],methods:["Method","MethodDeclaration","MethodSignature","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration"],property:["Field","PropertyDeclaration","PropertySignature"],properties:["Field","PropertyDeclaration","PropertySignature"],field:["Field"],fields:["Field"],variable:["Variable","VariableDeclaration"],variables:["Variable","VariableDeclaration"],enum:["Enum","EnumDeclaration"],enums:["Enum","EnumDeclaration"],"enum-member":["EnumMember","EnumMemberDeclaration"],enum_member:["EnumMember","EnumMemberDeclaration"],type:["TypeAlias","TypeAliasDeclaration"],"type-alias":["TypeAlias","TypeAliasDeclaration"],types:["TypeAlias","TypeAliasDeclaration"],namespace:["Namespace","ModuleDeclaration","NamespaceDeclaration"],namespaces:["Namespace","ModuleDeclaration","NamespaceDeclaration"],template:["Template"],templates:["Template"],"template-parameter":["TemplateParameter"],template_parameter:["TemplateParameter"],operator:["Operator"],operators:["Operator"],macro:["Macro"],macros:["Macro"],file:["SourceFile"],sourcefile:["SourceFile"],files:["SourceFile"],sourcefiles:["SourceFile"],return:["ReturnStatement"],return_statement:["ReturnStatement"],return_statements:["ReturnStatement"],if:["IfStatement"],if_statement:["IfStatement"],if_statements:["IfStatement"],for:["ForStatement","ForInStatement","ForOfStatement"],for_statement:["ForStatement"],for_in_statement:["ForInStatement"],for_of_statement:["ForOfStatement"],while:["WhileStatement"],while_statement:["WhileStatement"],do:["DoStatement"],do_statement:["DoStatement"],switch:["SwitchStatement"],switch_statement:["SwitchStatement"],case:["CaseClause"],case_clause:["CaseClause"],default:["DefaultClause"],default_clause:["DefaultClause"],try:["TryStatement"],try_statement:["TryStatement"],catch:["CatchClause"],catch_clause:["CatchClause"],throw:["ThrowStatement"],throw_statement:["ThrowStatement"],block:["Block"],expression:["ExpressionStatement"],expression_statement:["ExpressionStatement"]},ETn=new Set(["comment","comments","text"]);$7t={return_statement:["ReturnStatement"],return_statements:["ReturnStatement"],throw_statement:["ThrowStatement"],throw_statements:["ThrowStatement"],try_statement:["TryStatement"],try_statements:["TryStatement"],try_blocks:["TryStatement","CatchClause","FinallyBlock"],control_flow:["IfStatement","SwitchStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoStatement"]},Kbt=new Set(["ReturnStatement","ThrowStatement","TryStatement","CatchClause","FinallyBlock","IfStatement","SwitchStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoStatement",...Object.values($7t).flat()]),K7t=Number.MAX_SAFE_INTEGER,CTn=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Lnn=5;MTn={":node/path":{":db/unique":":db.unique/identity"}},LTn=/:node\/[A-Za-z0-9_-]+/g,AE=class u{constructor(i){this.chunkDbs=[];this.ftsChunkDbs=[];this.fileToChunkMap=new Map;this.functionLike=new Set(["FunctionDeclaration","MethodDeclaration","ArrowFunction","FunctionExpression","ConstructorDeclaration","GetAccessorDeclaration","SetAccessorDeclaration","Function","Method","Constructor","LocalFunctionStatement","LocalFunction"]);this.projectRoot=i,this.readOnly=!1;let l=L7("constructor");l("start",{projectRoot:i}),this.discoverChunks(),l("afterDiscoverChunks",{chunkCount:this.chunkDbs.length,ftsChunkCount:this.ftsChunkDbs.length}),gZ("constructor.afterDiscoverChunks",{projectRoot:i,pandoDataDir:Sy(i),chunkCount:this.chunkDbs.length,ftsChunkCount:this.ftsChunkDbs.length,chunkDbs:this.chunkDbs,ftsChunkDbs:this.ftsChunkDbs}),this.preloadFileMappings(),l("afterPreloadFileMappings",{cachedFiles:this.fileToChunkMap.size,mappingStore:!!this.mappingStore}),gZ("constructor.afterPreloadFileMappings",{projectRoot:i,cachedFiles:this.fileToChunkMap.size,mappingStore:!!this.mappingStore})}static{this.offsetsSupported=!0}static{this.DB_DEBUG=$T()}preflightDatalogQuery(i,l){if(!i||typeof i.query!="string")return null;let _=this.getDatalogQueryAttributes(i),v=_.filter(P=>!cqt.has(P)),T={ok:v.length===0,queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]};return T.ok||(T.error=`Unsupported datalog attrs: ${v.join(", ")}. Allowed attrs: ${U6e.join(", ")}`,T.error_code="unsupported_datalog_attributes",T.details={queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]}),l&&(l.datalogPreflight={ok:T.ok,queryAttributes:_,unsupportedAttributes:v,allowedAttributes:[...U6e]}),T}getDatalogQueryAttributes(i){return!i||typeof i.query!="string"?[]:Array.from(new Set(i.query.match(LTn)||[])).sort()}tokenizeDatalogClause(i){let l=[],_=String(i||""),v=0;for(;v<_.length;){for(;v<_.length&&/\s/.test(_[v]);)v++;if(v>=_.length)break;if(_[v]==='"'){let P=v+1,O=!1;for(;P<_.length;){let V=_[P];if(O){O=!1,P++;continue}if(V==="\\"){O=!0,P++;continue}if(V==='"'){P++;break}P++}l.push(_.slice(v,P)),v=P;continue}let T=v;for(;T<_.length&&!/\s/.test(_[T]);)T++;l.push(_.slice(v,T)),v=T}return l}parseExactDatalogLiteral(i){let l=String(i||"").trim();if(l){if(l==="true")return!0;if(l==="false")return!1;if(l==="nil"||l==="null")return null;if(/^-?\d+$/.test(l)){let _=Number(l);return Number.isSafeInteger(_)?_:void 0}if(l.startsWith('"')&&l.endsWith('"'))try{return JSON.parse(l)}catch{return}}}extractIndexedFieldFiltersFromDatalog(i){if(!i||typeof i.query!="string"||typeof i.result?.nodeVar!="string")return null;let l=String(i.result.nodeVar).trim();if(!l)return null;let _=i.query.match(/\[[^\[\]]*\]/g)||[];if(_.length===0)return null;let v=new Set,T=new Set,P=new Set,O=new Set,V=new Set,K=new Set;for(let q of _){let Ie=q.slice(1,-1).trim();if(!Ie)continue;let ye=this.tokenizeDatalogClause(Ie);if(ye.length!==3||ye[0]!==l)continue;let ve=ye[1],ft=this.parseExactDatalogLiteral(ye[2]);if(ft!==void 0)switch(ve){case":node/name":typeof ft=="string"&&ft&&v.add(ft);break;case":node/kind":case":node/type":typeof ft=="string"&&ft&&T.add(ft);break;case":node/semantic-kind":typeof ft=="string"&&ft&&P.add(ft);break;case":node/param-count":typeof ft=="number"&&Number.isFinite(ft)&&O.add(Math.max(0,Math.floor(ft)));break;case":node/exported":typeof ft=="boolean"&&V.add(ft);break;case":node/file":typeof ft=="string"&&ft&&K.add(ft.replace(/\\/g,"/"));break;default:break}}return v.size===0&&T.size===0&&P.size===0&&O.size===0&&V.size===0&&K.size===0?null:{impossible:v.size>1||T.size>1||P.size>1||O.size>1||V.size>1||K.size>1,name:v.size===1?Array.from(v)[0]:void 0,kind:T.size===1?Array.from(T)[0]:void 0,semanticKind:P.size===1?Array.from(P)[0]:void 0,paramCount:O.size===1?Array.from(O)[0]:void 0,exported:V.size===1?Array.from(V)[0]:void 0,filePath:K.size===1?Array.from(K)[0]:void 0}}datalogRequiresStructuralSourceScan(i){return this.getDatalogQueryAttributes(i).some(l=>uqt.has(l))}listFilesForDatalogScan(i,l){let _=new Set,v=K=>{K&&_.add(K.replace(/\\/g,"/"))},T=Array.isArray(i.candidateFiles)?i.candidateFiles.map(K=>this.normalizeCandidatePath(K)??String(K||"").replace(/\\/g,"/")).filter(K=>typeof K=="string"&&K.length>0):[],P=this.normalizeDatalogLangFilter(i.lang);if(T.length>0)for(let K of T)v(K);let O=typeof i.scope=="string"?String(i.scope).trim().replace(/\\/g,"/"):"";if(_.size===0&&O)if(O.includes("#"))v(O.split("#")[0]);else if(O.endsWith("/")){let K=this.collectFilesUnderDirectoryScope(O);for(let te of K)v(te)}else v(O);else if(_.size===0&&i.asOf)for(let K of this.getSnapshotFiles(String(i.asOf)))v(K);if(_.size===0)for(let K of this.fileToChunkMap.keys())v(K);let V=Array.from(_).filter(Boolean).filter(K=>this.matchesDatalogLangFilter(K,P)).sort();return V.length===0&&l.push("No candidate files found for datalog scan."),V}normalizeDatalogLangFilter(i){let l=Array.isArray(i)?i:typeof i=="string"?[i]:[];return Array.from(new Set(l.map(_=>String(_||"").trim()).filter(Boolean))).sort()}matchesDatalogLangFilter(i,l){if(l.length===0)return!0;let _=cT(i);return!!(_&&l.includes(_))}datalogCursorDescriptor(i){let _={datalog:i.datalog||null,prefilter:i.prefilter??null},v={scope:i.scope??null,candidateFiles:Array.isArray(i.candidateFiles)?[...i.candidateFiles].sort():null,asOf:i.asOf??null,projectFilter:i.projectFilter??null},T=this.normalizeDatalogLangFilter(i.lang).join(",");return{queryHash:qbt.default.createHash("sha1").update(JSON.stringify(_)).digest("hex"),scopeHash:qbt.default.createHash("sha1").update(JSON.stringify(v)).digest("hex"),langKey:T,orderingVersion:"file_path_asc,node_path_asc:v1"}}encodeDatalogCursor(i){let l=JSON.stringify(i);return Buffer.from(l,"utf8").toString("base64url")}decodeDatalogCursor(i){try{let l=Buffer.from(String(i),"base64url").toString("utf8"),_=JSON.parse(l);return!_||typeof _!="object"?null:_}catch{return null}}queryIndexedNodesForFile(i){let l=String(i||"").replace(/\\/g,"/");if(!l)return[];let _=this.fileToChunkMap.get(l),v=_?[_]:this.chunkDbs,T=`SELECT CAST(n.id AS TEXT) AS node_id,
|
|
32929
32929
|
CAST(n.parent_node_id AS TEXT) AS parent_node_id,
|
|
32930
32930
|
COALESCE(k.text, NULLIF(n.raw_kind, '')) AS type,
|
|
32931
32931
|
n.raw_kind,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as xn,d as ae,e as B,f as mt}from"./chunk-MGQRPDUI.mjs";import{a as bn}from"./chunk-RRIZV7YJ.mjs";var Z={getAbbrev(n,e="ts"){return n},getKindFromAbbrev(n,e="ts"){return n}};function Ie(n){let e=`${n.sourceFile}#${n.sourceStart}-${n.sourceEnd}`,t=n.refKind??"",r=n.refName??"",i=n.targetFile??"",s=n.targetStart!=null&&n.targetEnd!=null?`#${n.targetStart}-${n.targetEnd}`:"",o=n.targetNodeId??"",l=`${e}:REF:${t}:${r}|${i}${s}|${o}`;return mt(l)}function ft(n){let e=[],t=new Set,r=i=>{!i?.name||t.has(i.name)||(t.add(i.name),e.push(i))};for(let i of n.exports??[])r(i);for(let i of n.explicitExports??[])r({name:i});for(let i of n.modulePublic??[])r({name:i});return e}function ye(n,e,t){let r=new Date().toISOString();return{payload:{lang:n,fileRel:e,preDeleted:!1,exportRows:[],nodeRows:[],referenceRows:[],symbolMentionRows:[],importRows:[],importBindingRows:[],fileRow:[e,t?.mtime??null,t?.size??null,"failed",r],fts:null,fullyIndexed:!1},fileSize:t?.size,mtime:t?.mtime}}function be(n){let{lang:e,fileRel:t,content:r,meta:i,preDeleted:s,parsed:o,resolveNodeId:l,exportKind:c,fullyIndexed:u}=n,m=[],p=o.nodes??[],C=p.map(a=>{let f=`${t}#${a.start}-${a.end}:${Z.getAbbrev(a.kind,e)}`;return(e==="c"||e==="cpp"||e==="java"||e==="clojure")&&a.name?`${f}:${a.name}`:f});for(let a=0;a<p.length;a+=1){let f=p[a],h=f.rawKind??f.kind,P=f.rawKindSource??"cli",g=f.containerRawKind??f.containerKind??null,y=f.containerRawKindSource??(g?"cli":null),E=f.scopeChain??null,N=Array.isArray(E)?JSON.stringify(E):typeof E=="string"?E:null,j=C[a],S=typeof f.parentIndex=="number"?C[f.parentIndex]??null:f.parentNodeId??null,x=f.metadata&&Object.keys(f.metadata).length?JSON.stringify(f.metadata):null;m.push([j,f.name,f.kind,h,P,f.semanticKind??null,f.start,f.end,typeof f.isExported=="number"?f.isExported:0,f.containerKind??null,g,y,typeof f.paramCount=="number"?f.paramCount:null,f.qualifiedName??null,N,f.symbolKey??null,x,S,f.role??null,typeof f.indexInParent=="number"?f.indexInParent:null,typeof f.depth=="number"?f.depth:0,typeof f.bodyStart=="number"?f.bodyStart:null,typeof f.bodyEnd=="number"?f.bodyEnd:null])}let I=[],K=new Set;for(let a of ft(o)){if(!a.name||K.has(a.name))continue;K.add(a.name);let f=a.nodeId??(l?l(a.name):null);I.push([t,a.name,f??null,a.isReexport?1:0,a.reexportFrom??null,a.reexportName??null,a.exportKind??c??"cli",a.targetSymbolKey??null])}let R=[],F=[],O=new Map,U=new Map;for(let a of m){let f=a[0]!=null?String(a[0]):null,h=a[13]!=null?String(a[13]):null,P=a[15]!=null?String(a[15]):null;f&&(h&&!O.has(h)&&O.set(h,f),P&&!U.has(P)&&U.set(P,f))}if(ae()&&e==="clojure"&&(o.references??[]).length>0){let a=Array.from(O.keys()).slice(0,10),f=Array.from(U.keys()).slice(0,10),h=(o.references??[]).slice(0,10).map(g=>g.containerQualifiedName),P={file:t,nodeCount:m.length,refCount:(o.references??[]).length,nodeQualifiedNames:a,nodeSymbolKeys:f,refContainers:h,qualifiedNameMapSize:O.size,symbolKeyMapSize:U.size};try{console.error("[CliPayload][CLOJURE-DEBUG] source_node_id lookup context",P)}catch{}}for(let a of o.references??[]){let f=a.targetNodeId??(l&&a.refName?l(a.refName):null),h=a.targetFile??(f?t:null),P=a.sourceNodeId??(a.containerQualifiedName?O.get(a.containerQualifiedName)??null:null)??(a.containerQualifiedName?U.get(a.containerQualifiedName)??null:null),g=Ie({sourceFile:t,sourceStart:a.sourceStart,sourceEnd:a.sourceEnd,refKind:a.refKind,refName:a.refName,targetFile:h??null,targetStart:a.targetStart??null,targetEnd:a.targetEnd??null,targetNodeId:f??a.targetNodeId??null}),y=a.metadata&&Object.keys(a.metadata).length?JSON.stringify(a.metadata):null;R.push([g,t,P,a.refName??null,a.refKind,a.sourceStart,a.sourceEnd,f??a.targetNodeId??null,h??null,f||a.targetNodeId||a.targetFile?"resolved":"unresolved",a.receiverName??null,typeof a.arity=="number"?a.arity:null,a.containerQualifiedName??null,a.targetSymbolKey??null,a.confidence??null,y])}for(let a of o.symbolMentions??[]){let f=typeof a?.name=="string"?a.name.trim():"";if(!f)continue;let h=typeof a?.mentionKind=="string"&&a.mentionKind.trim().length>0?a.mentionKind.trim():"reference",P=typeof a?.count=="number"&&Number.isFinite(a.count)&&a.count>0?Math.floor(a.count):1;F.push([f,h,a.targetSymbolKey??null,a.containerQualifiedName??null,P])}if(ae()&&e==="clojure"&&R.length>0){let a=R.reduce((h,P)=>h+(P?.[2]!=null?1:0),0),f=R.reduce((h,P)=>h+(P?.[12]!=null?1:0),0);try{console.error("[CliPayload] clojure source-node summary",{file:t,refs:R.length,sourceNodeCount:a,containerCount:f,sample:R.slice(0,5).map(h=>({sourceNodeId:h[2]==null?null:String(h[2]),refName:h[3],refKind:h[4],containerQualifiedName:h[12]}))})}catch{}}let z=[];for(let a of o.imports??[])z.push([t,a.module??null,a.isTypeOnly??0]);let H=[];for(let a of o.importBindings??[])H.push([t,a.module??null,a.kind,a.localName,a.importedName,a.isTypeOnly??0]);let ge=new Date().toISOString(),V=[t,i?.mtime??null,i?.size??null,"completed",ge,u?1:0];return{payload:{lang:e,fileRel:t,preDeleted:!!s,exportRows:I,nodeRows:m,referenceRows:R,symbolMentionRows:F,importRows:z,importBindingRows:H,fileRow:V,fts:typeof r=="string"?{blobOid:t,content:r}:null,fullyIndexed:!!u},fileSize:i?.size,mtime:i?.mtime}}var xe=["ts","js","python","c","cpp","csharp","dart","java","clojure"];function ze(n){return typeof n=="string"&&xe.includes(n)}xn();function gt(){let n=process.env.PANDO_ENABLED_LANGUAGES;if(n&&n.trim().length>0){let t=n.split(",").map(r=>r.trim()).filter(r=>r.length>0).filter(ze);if(t.length>0)return ht(t)}return[...xe]}function ht(n){let e=new Set;for(let t of n)ze(t)&&e.add(t);return xe.filter(t=>e.has(t))}function yt(n){let e=new Set(ht(n)),t={};for(let r of xe){if(e.has(r)){t[r]={enabled:!0,source:"embedded"};continue}t[r]={enabled:!1,source:"none",reason:"disabled by language support config"}}return{byLanguage:t}}import Ue from"path";import An from"fs";import{Project as kn,Node as G}from"ts-morph";import{Node as d,SyntaxKind as le}from"ts-morph";import*as X from"typescript";import{SyntaxKind as Se}from"ts-morph";var qe={LINE_COMMENT:{kind:9001,name:"LineComment",triviaKind:Se.SingleLineCommentTrivia},BLOCK_COMMENT:{kind:9002,name:"BlockComment",triviaKind:Se.MultiLineCommentTrivia},JSDOC_COMMENT:{kind:9003,name:"JSDocComment",triviaKind:Se.MultiLineCommentTrivia}};function bt(n,e){return n===Se.SingleLineCommentTrivia?qe.LINE_COMMENT:n===Se.MultiLineCommentTrivia&&e.startsWith("/**")?qe.JSDOC_COMMENT:qe.BLOCK_COMMENT}import{Node as T}from"ts-morph";var xt={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},St=(n,e)=>T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)?{kind:"Function",semanticKind:"function"}:T.isGetAccessorDeclaration(n)||T.isSetAccessorDeclaration(n)?{kind:"Method",semanticKind:"property"}:T.isMethodDeclaration(n)||T.isMethodSignature(n)||T.isConstructorDeclaration(n)?{kind:"Method",semanticKind:"method"}:T.isClassDeclaration(n)||T.isClassExpression(n)?{kind:"Class",semanticKind:"class"}:T.isInterfaceDeclaration(n)?{kind:"Interface",semanticKind:"interface"}:T.isEnumDeclaration(n)?{kind:"Enum",semanticKind:"enum"}:T.isEnumMember(n)?{kind:"EnumMember",semanticKind:"enum"}:T.isTypeAliasDeclaration(n)?{kind:"TypeAlias",semanticKind:"type"}:T.isModuleDeclaration(n)?{kind:"Namespace",semanticKind:"namespace"}:T.isPropertyDeclaration(n)||T.isPropertySignature(n)?{kind:"Field",semanticKind:"property"}:T.isVariableDeclaration(n)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null};function Ct(n){try{let e=n.getKindName?.();if(typeof e=="string"&&e.trim())return e}catch{}return"Unknown"}function Ae(n){let e=Ct(n),t=St(n,e);return{kind:t.kind,semanticKind:t.semanticKind,rawKind:e,rawKindSource:xt.TS_MORPH}}function vt(n){let e=Ct(n);return{kind:St(n,e).kind,rawKind:e,rawKindSource:xt.TS_MORPH}}function ke(n,e){if(!n.kind||!n.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!n.rawKind||!n.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!n.rawKindSource||!String(n.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}function Sn(n){if(n.kind==="local"){let r=n.isDefault?"default":n.name;return r?{name:r,priority:n.isDefault?4:3}:null}if(n.kind==="alias")return n.exported?{name:n.exported,priority:2}:null;let e=n.isNamespace??!1,t=n.alias||n.name||(e?"*":null);return t?{name:t,priority:e?0:1}:null}function Cn(n){if(n.length<2)return n;let e=new Map;for(let t of n){let r=Sn(t);if(!r)continue;let i=e.get(r.name);(!i||r.priority>i.priority)&&e.set(r.name,{record:t,priority:r.priority})}return Array.from(e.values()).map(t=>t.record)}function Ce(n){try{if(n&&typeof n.getName=="function"){let e=n.getName();if(typeof e=="string"&&e.length>0)return e}}catch{}return null}function vn(n){try{let e=n?.getBody?.();if(!e||typeof e.getStart!="function"||typeof e.getEnd!="function")return null;let t=typeof e.getKindName=="function"?String(e.getKindName()):"",r=t==="Block"||t==="ModuleBlock",i=e.getStart(),s=e.getEnd(),o=r?i+1:i,l=r?s-1:s;return!Number.isFinite(o)||!Number.isFinite(l)||l<o?null:{start:o,end:l}}catch{return null}}function En(n){let e=n.getParent?.();if(!e)return null;try{if(d.isIfStatement(e)){if(e.getExpression()===n)return"condition";if(e.getThenStatement()===n)return"then";if(e.getElseStatement()===n)return"else"}if(d.isReturnStatement(e)&&e.getExpression?.()===n)return"value";if(d.isVariableDeclaration(e)){if(e.getNameNode?.()===n)return"name";if(e.getInitializer?.()===n)return"initializer"}if(d.isCallExpression(e)||d.isNewExpression(e)){if(e.getExpression?.()===n)return"callee";if((e.getArguments?.()??[]).indexOf(n)>=0)return"argument"}if(d.isPropertyAccessExpression(e)){if(e.getExpression()===n)return"object";if(e.getNameNode()===n)return"property"}}catch{return null}return null}function Je(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}function wn(n){try{if(d.isFunctionDeclaration(n)||d.isMethodDeclaration(n)||d.isConstructorDeclaration(n)||d.isFunctionExpression(n)||d.isArrowFunction(n)){let e=n.getParameters?.();if(Array.isArray(e))return e.length}}catch{}return null}function Pn(n){try{return d.isIdentifier(n)?n.getSymbol():d.isPropertyAccessExpression(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol?.()}catch{return}}function Me(n,e){try{return typeof n?.hasModifier=="function"&&n.hasModifier(e)}catch{return!1}}function Et(n){try{return n.getModuleSpecifierValue?.()??null}catch{try{return n.getModuleSpecifier?.()?.getLiteralText?.()??null}catch{return null}}}function Nn(n,e,t){if(!d.isImportDeclaration(n))return;let i={moduleSpecifier:Et(n),isTypeOnly:n.isTypeOnly(),namedImports:[]};try{let s=n.getDefaultImport();if(s){let o=s.getText();i.defaultImport=o,t(o,s)}}catch{}try{let s=n.getNamespaceImport();if(s){let o=s.getText();i.namespaceImport=o,t(o,s)}}catch{}try{n.getNamedImports().forEach(s=>{try{let o=s.getName(),l=s.getAliasNode(),c=l?l.getText():void 0;o&&(i.namedImports.push({name:o,alias:c||void 0}),t(c||o,s.getNameNode()))}catch{}})}catch{}e.push(i)}function Rn(n,e){if(d.isExportDeclaration(n)){let t=Et(n);if(t){if(n.getNamedExports().length>0)try{n.getNamedExports().forEach(r=>{try{let i=r.getName(),s=r.getAliasNode(),o=s?s.getText():void 0;e.push({kind:"reexport",moduleSpecifier:t,name:i||void 0,alias:o||void 0,isNamespace:!1})}catch{}})}catch{}else if(n.isNamespaceExport())try{let i=n.getNamespaceExport()?.getName();e.push({kind:"reexport",moduleSpecifier:t,name:i||"*",alias:i||void 0,isNamespace:!0})}catch{e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0})}else e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0});return}try{n.getNamedExports().forEach(r=>{try{let i=r.getName();if(!i)return;let s=r.getAliasNode(),o=s?s.getText():i;e.push({kind:"alias",local:i,exported:o})}catch{}})}catch{}return}if(d.isExportAssignment(n))try{let t=n.getExpression();if(t&&d.isIdentifier(t)){let r=t.getText();e.push({kind:"alias",local:r,exported:"default"})}}catch{}}function In(n,e,t,r){if(!Me(n,le.ExportKeyword))return;let i=Me(n,le.DefaultKeyword);if(d.isVariableStatement(n)){try{let s=n.getDeclarationList().getDeclarations();for(let o of s){let l=Ce(o)??o.getName?.()??null;if(l){t(l,o);let c=r(o);c&&e.push({kind:"local",name:l,isDefault:i,nodeId:c})}}}catch{}return}if(d.isFunctionDeclaration(n)||d.isClassDeclaration(n)||d.isInterfaceDeclaration(n)||d.isEnumDeclaration(n)||d.isTypeAliasDeclaration(n)||d.isModuleDeclaration(n)){let s=Ce(n)||(i?"default":null),o=r(n);o&&e.push({kind:"local",name:s??"default",isDefault:i,nodeId:o})}}function wt(n,e,t,r){let i=[],s=[],o=[],l=new Set,c=new Map,u=[],m=[],C=(r?.emitMode??"light")==="full",I=new Map,K=new Map,R=new Map,F=[{node:n,id:null,kind:"module",rawKind:"SourceFile",rawKindSource:"ts-morph",name:null,isExported:!1}],O=a=>{if(!a)return null;try{return e(a)}catch{return null}},U=a=>{let f=a.getParent?.();for(;f;){let h=I.get(f);if(h)return h;f=f.getParent?.()}return null},z=(a,f)=>{if(a&&(l.has(a)||l.add(a),f&&!c.has(a))){let h=O(f);h&&c.set(a,h)}},H=a=>d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isInterfaceDeclaration(a)||d.isEnumDeclaration(a)||d.isEnumMember(a)||d.isTypeAliasDeclaration(a)||d.isModuleDeclaration(a)||d.isMethodDeclaration(a)||d.isMethodSignature(a)||d.isPropertyDeclaration(a)||d.isPropertySignature(a)||d.isGetAccessorDeclaration(a)||d.isSetAccessorDeclaration(a)||d.isConstructorDeclaration(a)||d.isVariableDeclaration(a),ge=a=>d.isSourceFile(a)||d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isMethodDeclaration(a)||d.isConstructorDeclaration(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isModuleDeclaration(a),V=a=>{let f=Ce(a);if(f)return f;if(d.isConstructorDeclaration(a))return"constructor";if(d.isArrowFunction(a)||d.isFunctionExpression(a)){let h=a.getParent();try{if(d.isVariableDeclaration(h))return h.getName();if(d.isPropertyAssignment(h)||d.isPropertyDeclaration(h)||d.isPropertySignature(h))return h.getName?.()??null;if(d.isShorthandPropertyAssignment(h))return h.getNameNode()?.getText()??null;if(d.isExportAssignment(h))return"default"}catch{}}if(d.isEnumMember(a))try{return a.getName()}catch{return null}if(d.isVariableDeclaration(a))try{return a.getName()}catch{return null}return null},Y=a=>{let f=F[F.length-1],h=f?.id??null,P=f?.kind??"module",g=f?.name??null;if(d.isImportDeclaration(a))Nn(a,u,z);else if(d.isImportEqualsDeclaration(a))try{let S=a.getModuleReference();if(S&&d.isExternalModuleReference(S)){let x=S.getExpression(),v;if(x&&d.isStringLiteral(x))v=x.getLiteralText();else if(x){let w=x.getText();v=typeof w=="string"?w.replace(/^['"]|['"]$/g,""):void 0}if(v){let M=a.getNameNode()?.getText(),_={moduleSpecifier:v,isTypeOnly:!1,namedImports:[]};M&&(_.defaultImport=M,z(M,a)),u.push(_)}}}catch{}(d.isExportDeclaration(a)||d.isExportAssignment(a))&&Rn(a,m),In(a,m,z,O);let y=H(a),E=C||y,N=y?V(a):null;if(E){let S=e(a);y&&s.push({nodeId:S,node:a});let x=U(a),v=x==null?null:K.get(x)??0;x!=null&&v!=null&&K.set(x,v+1),I.set(a,S);let w=x?(R.get(x)??-1)+1:0;R.set(S,w);let M=Me(a,le.ExportKeyword)||f?.isExported||!1,_=y?a.getNameNode?.()?.getText?.()??null:null,D=N??(y?Ce(a)??_:Ce(a));N?z(N,a):D&&z(D,a);let A=Je(a),L=wn(a),k=Ae(a);ke(k,{source:"ts-node-collector",file:n.getFilePath(),name:D??null});let J=vn(a);i.push({nodeId:S,nodeName:D??null,containerId:h,containerKind:P,containerRawKind:f?.rawKind??null,containerRawKindSource:f?.rawKindSource??null,containerName:g,isExported:M,kind:k.kind,rawKind:k.rawKind,rawKindSource:k.rawKindSource,semanticKind:k.semanticKind??null,start:A.start,end:A.end,paramCount:L,metadata:null,parentNodeId:x,role:En(a),indexInParent:v,depth:w,bodyStart:J?.start??null,bodyEnd:J?.end??null})}if(d.isCallExpression(a)||d.isNewExpression(a)){let S=a.getExpression(),x=null,v,w;try{if(w=Pn(S),d.isIdentifier(S))x=S.getText();else if(d.isPropertyAccessExpression(S)){x=S.getName();let D=S.getExpression();d.isIdentifier(D)&&(v=D.getText())}}catch{}let M="";try{M=S.getText()}catch{}let _=Je(a);if(o.push({name:x,kind:d.isNewExpression(a)?"new":"call",containerId:h,containerKind:P,containerName:g,expression:M,objectName:v,symbol:w,start:_.start,end:_.end}),d.isCallExpression(a))try{if(d.isIdentifier(S)&&S.getText()==="require"){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}if(L){let k={moduleSpecifier:L,isTypeOnly:!1,namedImports:[]},J=a.getParent();if(J&&d.isVariableDeclaration(J)){let Re=J.getNameNode();try{if(d.isIdentifier(Re)){let he=Re.getText();he&&(k.defaultImport=he,z(he,J))}}catch{}}u.push(k)}}else if(S?.getKind?.()===le.ImportKeyword){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}L&&u.push({moduleSpecifier:L,isTypeOnly:!1,namedImports:[]})}}catch{}}if(d.isCallExpression(a)){let S=a.getExpression();try{if(d.isIdentifier(S)&&S.getText()==="require"){let x=a.getParent();if(!(x&&d.isExternalModuleReference(x))){let w=a.getArguments()[0],M;if(w&&(d.isStringLiteral(w)||d.isNoSubstitutionTemplateLiteral(w)))try{M=w.getLiteralText()}catch{M=w.getText().replace(/^['"]|['"]$/g,"")}if(M){let _={moduleSpecifier:M,isTypeOnly:!1,namedImports:[]};if(x&&d.isVariableDeclaration(x)){let D=x.getNameNode();try{if(d.isIdentifier(D)){let A=D.getText();A&&(_.defaultImport=A,z(A,x))}}catch{}}u.push(_)}}}else if(S?.getKind?.()===le.ImportKeyword){let v=a.getArguments()[0],w;if(v&&(d.isStringLiteral(v)||d.isNoSubstitutionTemplateLiteral(v)))try{w=v.getLiteralText()}catch{w=v.getText().replace(/^['"]|['"]$/g,"")}w&&u.push({moduleSpecifier:w,isTypeOnly:!1,namedImports:[]})}}catch{}}let j=!1;if(ge(a)){let S=O(a)??e(a),x=vt(a);F.push({node:a,id:S,kind:x.kind,rawKind:x.rawKind,rawKindSource:x.rawKindSource,name:N??g,isExported:Me(a,le.ExportKeyword)||f?.isExported||!1}),j=!0}a.forEachChild(Y),j&&F.pop()};if(C){let a=e(n);I.set(n,a),R.set(a,0);let f=Je(n);i.push({nodeId:a,nodeName:n.getBaseName?.()??null,containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:"SourceFile",rawKind:"SourceFile",rawKindSource:"ts-morph",semanticKind:"file",start:f.start,end:f.end,paramCount:null,metadata:null,parentNodeId:null,role:null,indexInParent:null,depth:0,bodyStart:f.start,bodyEnd:f.end})}if(n.forEachChild(Y),r?.includeComments===!0||C||process.env.AST_INDEX_COMMENTS==="1")try{let a=n.getFullText(),f=X.createScanner(X.ScriptTarget.Latest,!1,X.LanguageVariant.Standard,a),h=new Set;for(let P=f.scan();P!==X.SyntaxKind.EndOfFileToken;P=f.scan()){if(P!==X.SyntaxKind.SingleLineCommentTrivia&&P!==X.SyntaxKind.MultiLineCommentTrivia)continue;let g=f.getTokenPos(),y=f.getTextPos(),E=`${g}-${y}`;if(h.has(E)||(h.add(E),t.has(E)))continue;t.add(E);let N=a.substring(g,y),j=bt(P,N),x=e({getKindName:()=>j.name,getKind:()=>j.kind,getPos:()=>g,getEnd:()=>y,getStart:()=>g,getFullStart:()=>g,getText:()=>N,getSourceFile:()=>n,getParent:()=>n,__isComment:!0,__commentPosition:"standalone",__attachedTo:null},"COM"),v=I.get(n)??null,w=C&&v!=null?K.get(v)??0:null;C&&v!=null&&w!=null&&K.set(v,w+1),i.push({nodeId:x,nodeName:N.substring(0,100),containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:j.name,rawKind:j.name,rawKindSource:"ts-morph",semanticKind:null,start:g,end:y,paramCount:null,metadata:null,parentNodeId:v,role:"comment",indexInParent:w,depth:C?1:0,bodyStart:null,bodyEnd:null})}}catch{}return{nodes:i,symbolCandidateNodes:s,references:o,declaredNames:l,localDeclarations:c,imports:u,exports:Cn(m)}}function Pt(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}var Mn=100;function Dn(n,e,t,r){let{start:i,end:s}=Pt(e),o=Ae(e);ke(o,{source:"ts-node-id",file:n,kind:o.kind});let l=r||Z.getAbbrev(o.kind,t);return`${n}#${i}-${s}:${l}`}function Tn(n,e){return Ue.relative(n,e).replace(/\\/g,"/")}function Nt(n,e){if(!n)return null;let t=n;try{let m=n.getAliasedSymbol();m&&(t=m)}catch{}let r=[];try{r=t.getDeclarations()??[]}catch{r=[]}if(!r.length)return null;let s=r.slice().sort((m,p)=>{let C=m.getSourceFile().getFilePath(),I=p.getSourceFile().getFilePath();if(C!==I)return C.localeCompare(I);let K=m.getStart(!1),R=p.getStart(!1);return K!==R?K-R:m.getEnd()-p.getEnd()})[0],o=Tn(e,s.getSourceFile().getFilePath()),l=s.getStart(!1),c=s.getEnd(),u="";try{u=t.getEscapedName()}catch{try{u=t.getName()}catch{u=""}}return`${o}#${l}-${c}:${u}`}function Kn(n){try{return G.isVariableDeclaration(n)||G.isEnumMember(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol()}catch{return}}function _n(n,e){let t=n.getDescendantAtPos(e);if(!t)return;let r=t;if(!G.isCallExpression(r)&&!G.isNewExpression(r)&&(r=t.getFirstAncestor(s=>G.isCallExpression(s)||G.isNewExpression(s))??void 0),!r||!G.isCallExpression(r)&&!G.isNewExpression(r))return;let i=r.getExpression();try{return G.isIdentifier(i)?i.getSymbol():G.isPropertyAccessExpression(i)?i.getNameNode().getSymbol()??i.getSymbol():i.getSymbol()}catch{return}}async function On(n){let{sf:e,fileRel:t,content:r,preDeleted:i,meta:s,projectRoot:o,lang:l}=n,c=n.emitMode??"light",m=wt(e,(g,y)=>Dn(t,g,l,y),new Set,{includeComments:c==="full",emitMode:c}),p=new Map;for(let{nodeId:g,node:y}of m.symbolCandidateNodes){let E=Nt(Kn(y),o);E&&(p.has(g)||p.set(g,E))}let C=[],I=new Map,K=m.exports.filter(g=>g.kind!=="reexport"),R=m.exports.filter(g=>g.kind==="reexport");for(let g of K)if(g.kind==="local"){let y=g.isDefault?"default":g.name;if(!y||I.has(y))continue;let E=g.nodeId;C.push([t,y,E,0,null,null,g.isDefault?"default":"named"]),I.set(y,E)}else if(g.kind==="alias"){let y=g.exported;if(!y||I.has(y))continue;C.push([t,y,null,0,null,g.local,"alias"]),I.set(y,"alias")}for(let g of R){let y=g.moduleSpecifier;if(!y)continue;let E=y;if(g.isNamespace){let N=g.alias||"*";if(I.has(N))continue;C.push([t,N,null,1,E,g.name||N,"reexport_star"]),I.set(N,"reexport")}else{let N=g.alias||g.name;if(!N||I.has(N))continue;C.push([t,N,null,1,E,g.name||N,"reexport_named"]),I.set(N,"reexport")}}let F=[],O=typeof r=="string"?r:null;if(O==null)try{let g=e.getFullText();O=typeof g=="string"?g:null}catch{O=null}for(let g of m.nodes){let{nodeId:y,nodeName:E,containerKind:N,containerRawKind:j,containerRawKindSource:S,isExported:x,kind:v,rawKind:w,rawKindSource:M,semanticKind:_,start:D,end:A,paramCount:L,metadata:k,parentNodeId:J,role:Re,indexInParent:he,depth:mn,bodyStart:fn,bodyEnd:gn}=g,hn=k&&Object.keys(k).length?JSON.stringify(k):null,yn=p.get(y)??null;F.push([y,E??null,v,w??v,M??null,_??null,D,A,x?1:0,N??"module",j??N??"module",S??null,L,null,null,yn,hn,J??null,Re??null,he??null,mn??0,fn??null,gn??null])}let U=[];for(let g of m.references){let{name:y,kind:E,containerId:N,containerName:j,expression:S,objectName:x,start:v,end:w}=g,M=null,_=null,D=Nt(g.symbol??_n(e,v),o),A=y?m.localDeclarations.get(y):void 0;A&&(M=A,_=t,D||(D=p.get(A)??null));let L=Ie({sourceFile:t,sourceStart:v,sourceEnd:w,refKind:E,refName:y,targetFile:_,targetNodeId:M}),k={};S&&(k.expression=S),x&&(k.objectName=x),j&&(k.containerName=j);let J=Object.keys(k).length?JSON.stringify(k):null;U.push([L,t,N,y,E,v,w,M,_,M?"resolved":"unresolved",x??null,null,null,D,J])}let z=[],H=[];for(let g of m.imports){let y=g.moduleSpecifier??null;z.push([t,y,g.isTypeOnly?1:0]),g.defaultImport&&H.push([t,y,"default",g.defaultImport,"default",g.isTypeOnly?1:0]),g.namespaceImport&&H.push([t,y,"namespace",g.namespaceImport,"*",g.isTypeOnly?1:0]);for(let E of g.namedImports){let N=E.alias||E.name;H.push([t,y,"named",N,E.name,g.isTypeOnly?1:0])}}let ge=Ue.join(o,t),V=s?.size,Y=s?.mtime;if(V===void 0||Y===void 0)try{let g=An.statSync(ge);V=g.size,Y=Math.floor(g.mtimeMs)}catch{}let a=new Date().toISOString(),f=c==="full",h=[t,Y??null,V??null,"completed",a,f?1:0],P=null;if(typeof O=="string")P={blobOid:t,content:O};else try{let g=e.getFullText?.();typeof g=="string"&&(P={blobOid:t,content:g})}catch(g){console.log(`[TypescriptIndexer] Failed to compute FTS payload for ${t}:`,g?.message??g)}return{payload:{lang:l,fileRel:t,preDeleted:i,exportRows:C,nodeRows:F,referenceRows:U,importRows:z,importBindingRows:H,fileRow:h,fts:P,fullyIndexed:f},fileSize:V,mtime:Y}}var We=class{constructor(e,t){this.project=null;this.filesProcessed=0;this.projectRoot=e,this.lang=t}getProject(){return this.project||(this.project=new kn({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0})),this.project}disposeProject(){if(this.project){try{let e=this.project.getLanguageService().compilerObject;typeof e?.dispose=="function"&&e.dispose()}catch{}this.project=null}}async process(e){let t=this.getProject(),r;try{let i=t.createSourceFile(Ue.join(this.projectRoot,e.relPath),e.content,{overwrite:!0});r=await On({sf:i,fileRel:e.relPath,content:e.content,preDeleted:!!e.preDeleted,meta:e.meta,projectRoot:this.projectRoot,lang:e.lang,emitMode:e.emitMode??"light"})}catch(i){this.disposeProject(),this.filesProcessed=0;let s=i?.message||String(i);throw new Error(`TypeScript parser failed for ${e.relPath}: ${s}`)}return this.filesProcessed++,this.filesProcessed>=Mn&&(this.disposeProject(),this.filesProcessed=0),{payload:r.payload,fileSize:r.fileSize,mtime:r.mtime}}};function Ln(n){return n==="ts"?[".ts",".tsx",".mts",".cts"]:n==="js"?[".js",".jsx",".mjs",".cjs"]:[]}function Xe(n){return{id:n,extensions:Ln(n),indexingMode:"worker",createIndexer:e=>new We(e,n)}}import Te from"fs";import ee from"path";import{spawn as $n}from"child_process";import Fn from"fs";var ce=class{constructor(e=5e3){this.maxEntries=e;this.cache=new Map}get(e,t){let r=this.cache.get(e);if(!r)return null;let i=t?.mtime??null,s=t?.size??null;return i!=null&&s!=null&&r.mtime===i&&r.size===s?r.result:null}set(e,t,r){let i=t?.mtime??null,s=t?.size??null;this.cache.set(e,{mtime:i,size:s,result:r}),this.cache.size>this.maxEntries&&this.cache.clear()}};var Ge=class{constructor(e,t,r,i){this.projectRoot=e;this.lang=t;this.parse=r;this.exportKind=i;this.cache=new ce}async process(e){let t=e.meta?.mtime,r=e.meta?.size;if(t==null||r==null)try{let o=Fn.statSync(e.absPath);t=Math.floor(o.mtimeMs),r=o.size}catch{}let i=e.emitMode==="full"?null:this.cache.get(e.absPath,{mtime:t,size:r});if(i)return be({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:i,resolveNodeId:Rt(e.relPath,i,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"});let s=null;try{s=await this.parse({absPath:e.absPath,relPath:e.relPath,content:e.content,meta:{mtime:t,size:r},projectRoot:this.projectRoot,lang:this.lang,emitMode:e.emitMode??"light"})}catch(o){try{console.log(`[CliContract:${this.lang}] parse threw for ${e.relPath}: ${o?.message||String(o)}`)}catch{}return ye(this.lang,e.relPath,{mtime:t,size:r})}return!s||s.error?ye(this.lang,e.relPath,{mtime:t,size:r}):(e.emitMode!=="full"&&this.cache.set(e.absPath,{mtime:t,size:r},s),be({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:s,resolveNodeId:Rt(e.relPath,s,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"}))}};function Rt(n,e,t){let r=new Map;for(let i of e.nodes??[]){if(!i.name||r.has(i.name))continue;let s=`${n}#${i.start}-${i.end}:${Z.getAbbrev(i.kind,t)}`;r.set(i.name,s)}return i=>r.get(i)??null}function Q(n){return{id:n.id,extensions:n.extensions,indexingMode:"worker",createIndexer:e=>new Ge(e,n.id,n.parse,n.exportKind),resolveSpan:n.resolve?async(e,t,r)=>n.resolve({projectRoot:e,absPath:t,nodePath:r,lang:n.id}):void 0}}import jn from"fs";import De from"path";var Qe=null;function Bn(n){for(let e of n)if(jn.existsSync(e))return e;return null}function q(n){let e=Qe?.toolsRoot??process.env.PANDO_TOOLS_ROOT,t=Qe?.runtimeRoot??process.env.PANDO_RUNTIME_ROOT,r=Qe?.resourcesRoot??process.env.PANDO_RESOURCES_ROOT,i=[e?De.join(e,n):null,t?De.join(t,"tools",n):null,r?De.join(r,"tools",n):null,De.resolve(process.cwd(),"tools",n)].filter(s=>!!s);return Bn(i)}function W(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
1
|
+
import{c as xn,d as ae,e as B,f as mt}from"./chunk-CGVA3QGF.mjs";import{a as bn}from"./chunk-RRIZV7YJ.mjs";var Z={getAbbrev(n,e="ts"){return n},getKindFromAbbrev(n,e="ts"){return n}};function Ie(n){let e=`${n.sourceFile}#${n.sourceStart}-${n.sourceEnd}`,t=n.refKind??"",r=n.refName??"",i=n.targetFile??"",s=n.targetStart!=null&&n.targetEnd!=null?`#${n.targetStart}-${n.targetEnd}`:"",o=n.targetNodeId??"",l=`${e}:REF:${t}:${r}|${i}${s}|${o}`;return mt(l)}function ft(n){let e=[],t=new Set,r=i=>{!i?.name||t.has(i.name)||(t.add(i.name),e.push(i))};for(let i of n.exports??[])r(i);for(let i of n.explicitExports??[])r({name:i});for(let i of n.modulePublic??[])r({name:i});return e}function ye(n,e,t){let r=new Date().toISOString();return{payload:{lang:n,fileRel:e,preDeleted:!1,exportRows:[],nodeRows:[],referenceRows:[],symbolMentionRows:[],importRows:[],importBindingRows:[],fileRow:[e,t?.mtime??null,t?.size??null,"failed",r],fts:null,fullyIndexed:!1},fileSize:t?.size,mtime:t?.mtime}}function be(n){let{lang:e,fileRel:t,content:r,meta:i,preDeleted:s,parsed:o,resolveNodeId:l,exportKind:c,fullyIndexed:u}=n,m=[],p=o.nodes??[],C=p.map(a=>{let f=`${t}#${a.start}-${a.end}:${Z.getAbbrev(a.kind,e)}`;return(e==="c"||e==="cpp"||e==="java"||e==="clojure")&&a.name?`${f}:${a.name}`:f});for(let a=0;a<p.length;a+=1){let f=p[a],h=f.rawKind??f.kind,P=f.rawKindSource??"cli",g=f.containerRawKind??f.containerKind??null,y=f.containerRawKindSource??(g?"cli":null),E=f.scopeChain??null,N=Array.isArray(E)?JSON.stringify(E):typeof E=="string"?E:null,j=C[a],S=typeof f.parentIndex=="number"?C[f.parentIndex]??null:f.parentNodeId??null,x=f.metadata&&Object.keys(f.metadata).length?JSON.stringify(f.metadata):null;m.push([j,f.name,f.kind,h,P,f.semanticKind??null,f.start,f.end,typeof f.isExported=="number"?f.isExported:0,f.containerKind??null,g,y,typeof f.paramCount=="number"?f.paramCount:null,f.qualifiedName??null,N,f.symbolKey??null,x,S,f.role??null,typeof f.indexInParent=="number"?f.indexInParent:null,typeof f.depth=="number"?f.depth:0,typeof f.bodyStart=="number"?f.bodyStart:null,typeof f.bodyEnd=="number"?f.bodyEnd:null])}let I=[],K=new Set;for(let a of ft(o)){if(!a.name||K.has(a.name))continue;K.add(a.name);let f=a.nodeId??(l?l(a.name):null);I.push([t,a.name,f??null,a.isReexport?1:0,a.reexportFrom??null,a.reexportName??null,a.exportKind??c??"cli",a.targetSymbolKey??null])}let R=[],F=[],O=new Map,U=new Map;for(let a of m){let f=a[0]!=null?String(a[0]):null,h=a[13]!=null?String(a[13]):null,P=a[15]!=null?String(a[15]):null;f&&(h&&!O.has(h)&&O.set(h,f),P&&!U.has(P)&&U.set(P,f))}if(ae()&&e==="clojure"&&(o.references??[]).length>0){let a=Array.from(O.keys()).slice(0,10),f=Array.from(U.keys()).slice(0,10),h=(o.references??[]).slice(0,10).map(g=>g.containerQualifiedName),P={file:t,nodeCount:m.length,refCount:(o.references??[]).length,nodeQualifiedNames:a,nodeSymbolKeys:f,refContainers:h,qualifiedNameMapSize:O.size,symbolKeyMapSize:U.size};try{console.error("[CliPayload][CLOJURE-DEBUG] source_node_id lookup context",P)}catch{}}for(let a of o.references??[]){let f=a.targetNodeId??(l&&a.refName?l(a.refName):null),h=a.targetFile??(f?t:null),P=a.sourceNodeId??(a.containerQualifiedName?O.get(a.containerQualifiedName)??null:null)??(a.containerQualifiedName?U.get(a.containerQualifiedName)??null:null),g=Ie({sourceFile:t,sourceStart:a.sourceStart,sourceEnd:a.sourceEnd,refKind:a.refKind,refName:a.refName,targetFile:h??null,targetStart:a.targetStart??null,targetEnd:a.targetEnd??null,targetNodeId:f??a.targetNodeId??null}),y=a.metadata&&Object.keys(a.metadata).length?JSON.stringify(a.metadata):null;R.push([g,t,P,a.refName??null,a.refKind,a.sourceStart,a.sourceEnd,f??a.targetNodeId??null,h??null,f||a.targetNodeId||a.targetFile?"resolved":"unresolved",a.receiverName??null,typeof a.arity=="number"?a.arity:null,a.containerQualifiedName??null,a.targetSymbolKey??null,a.confidence??null,y])}for(let a of o.symbolMentions??[]){let f=typeof a?.name=="string"?a.name.trim():"";if(!f)continue;let h=typeof a?.mentionKind=="string"&&a.mentionKind.trim().length>0?a.mentionKind.trim():"reference",P=typeof a?.count=="number"&&Number.isFinite(a.count)&&a.count>0?Math.floor(a.count):1;F.push([f,h,a.targetSymbolKey??null,a.containerQualifiedName??null,P])}if(ae()&&e==="clojure"&&R.length>0){let a=R.reduce((h,P)=>h+(P?.[2]!=null?1:0),0),f=R.reduce((h,P)=>h+(P?.[12]!=null?1:0),0);try{console.error("[CliPayload] clojure source-node summary",{file:t,refs:R.length,sourceNodeCount:a,containerCount:f,sample:R.slice(0,5).map(h=>({sourceNodeId:h[2]==null?null:String(h[2]),refName:h[3],refKind:h[4],containerQualifiedName:h[12]}))})}catch{}}let z=[];for(let a of o.imports??[])z.push([t,a.module??null,a.isTypeOnly??0]);let H=[];for(let a of o.importBindings??[])H.push([t,a.module??null,a.kind,a.localName,a.importedName,a.isTypeOnly??0]);let ge=new Date().toISOString(),V=[t,i?.mtime??null,i?.size??null,"completed",ge,u?1:0];return{payload:{lang:e,fileRel:t,preDeleted:!!s,exportRows:I,nodeRows:m,referenceRows:R,symbolMentionRows:F,importRows:z,importBindingRows:H,fileRow:V,fts:typeof r=="string"?{blobOid:t,content:r}:null,fullyIndexed:!!u},fileSize:i?.size,mtime:i?.mtime}}var xe=["ts","js","python","c","cpp","csharp","dart","java","clojure"];function ze(n){return typeof n=="string"&&xe.includes(n)}xn();function gt(){let n=process.env.PANDO_ENABLED_LANGUAGES;if(n&&n.trim().length>0){let t=n.split(",").map(r=>r.trim()).filter(r=>r.length>0).filter(ze);if(t.length>0)return ht(t)}return[...xe]}function ht(n){let e=new Set;for(let t of n)ze(t)&&e.add(t);return xe.filter(t=>e.has(t))}function yt(n){let e=new Set(ht(n)),t={};for(let r of xe){if(e.has(r)){t[r]={enabled:!0,source:"embedded"};continue}t[r]={enabled:!1,source:"none",reason:"disabled by language support config"}}return{byLanguage:t}}import Ue from"path";import An from"fs";import{Project as kn,Node as G}from"ts-morph";import{Node as d,SyntaxKind as le}from"ts-morph";import*as X from"typescript";import{SyntaxKind as Se}from"ts-morph";var qe={LINE_COMMENT:{kind:9001,name:"LineComment",triviaKind:Se.SingleLineCommentTrivia},BLOCK_COMMENT:{kind:9002,name:"BlockComment",triviaKind:Se.MultiLineCommentTrivia},JSDOC_COMMENT:{kind:9003,name:"JSDocComment",triviaKind:Se.MultiLineCommentTrivia}};function bt(n,e){return n===Se.SingleLineCommentTrivia?qe.LINE_COMMENT:n===Se.MultiLineCommentTrivia&&e.startsWith("/**")?qe.JSDOC_COMMENT:qe.BLOCK_COMMENT}import{Node as T}from"ts-morph";var xt={TS_MORPH:"ts-morph",PYTHON_AST:"python-ast",CLANG:"clang",ROSLYN:"roslyn",JAVA_AST:"java-ast",CLI:"cli",UNKNOWN:"unknown"},St=(n,e)=>T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)?{kind:"Function",semanticKind:"function"}:T.isGetAccessorDeclaration(n)||T.isSetAccessorDeclaration(n)?{kind:"Method",semanticKind:"property"}:T.isMethodDeclaration(n)||T.isMethodSignature(n)||T.isConstructorDeclaration(n)?{kind:"Method",semanticKind:"method"}:T.isClassDeclaration(n)||T.isClassExpression(n)?{kind:"Class",semanticKind:"class"}:T.isInterfaceDeclaration(n)?{kind:"Interface",semanticKind:"interface"}:T.isEnumDeclaration(n)?{kind:"Enum",semanticKind:"enum"}:T.isEnumMember(n)?{kind:"EnumMember",semanticKind:"enum"}:T.isTypeAliasDeclaration(n)?{kind:"TypeAlias",semanticKind:"type"}:T.isModuleDeclaration(n)?{kind:"Namespace",semanticKind:"namespace"}:T.isPropertyDeclaration(n)||T.isPropertySignature(n)?{kind:"Field",semanticKind:"property"}:T.isVariableDeclaration(n)?{kind:"Variable",semanticKind:"variable"}:{kind:e,semanticKind:null};function Ct(n){try{let e=n.getKindName?.();if(typeof e=="string"&&e.trim())return e}catch{}return"Unknown"}function Ae(n){let e=Ct(n),t=St(n,e);return{kind:t.kind,semanticKind:t.semanticKind,rawKind:e,rawKindSource:xt.TS_MORPH}}function vt(n){let e=Ct(n);return{kind:St(n,e).kind,rawKind:e,rawKindSource:xt.TS_MORPH}}function ke(n,e){if(!n.kind||!n.kind.trim())throw new Error(`Invalid normalized kind: missing kind ${e?JSON.stringify(e):""}`);if(!n.rawKind||!n.rawKind.trim())throw new Error(`Invalid normalized kind: missing rawKind ${e?JSON.stringify(e):""}`);if(!n.rawKindSource||!String(n.rawKindSource).trim())throw new Error(`Invalid normalized kind: missing rawKindSource ${e?JSON.stringify(e):""}`)}function Sn(n){if(n.kind==="local"){let r=n.isDefault?"default":n.name;return r?{name:r,priority:n.isDefault?4:3}:null}if(n.kind==="alias")return n.exported?{name:n.exported,priority:2}:null;let e=n.isNamespace??!1,t=n.alias||n.name||(e?"*":null);return t?{name:t,priority:e?0:1}:null}function Cn(n){if(n.length<2)return n;let e=new Map;for(let t of n){let r=Sn(t);if(!r)continue;let i=e.get(r.name);(!i||r.priority>i.priority)&&e.set(r.name,{record:t,priority:r.priority})}return Array.from(e.values()).map(t=>t.record)}function Ce(n){try{if(n&&typeof n.getName=="function"){let e=n.getName();if(typeof e=="string"&&e.length>0)return e}}catch{}return null}function vn(n){try{let e=n?.getBody?.();if(!e||typeof e.getStart!="function"||typeof e.getEnd!="function")return null;let t=typeof e.getKindName=="function"?String(e.getKindName()):"",r=t==="Block"||t==="ModuleBlock",i=e.getStart(),s=e.getEnd(),o=r?i+1:i,l=r?s-1:s;return!Number.isFinite(o)||!Number.isFinite(l)||l<o?null:{start:o,end:l}}catch{return null}}function En(n){let e=n.getParent?.();if(!e)return null;try{if(d.isIfStatement(e)){if(e.getExpression()===n)return"condition";if(e.getThenStatement()===n)return"then";if(e.getElseStatement()===n)return"else"}if(d.isReturnStatement(e)&&e.getExpression?.()===n)return"value";if(d.isVariableDeclaration(e)){if(e.getNameNode?.()===n)return"name";if(e.getInitializer?.()===n)return"initializer"}if(d.isCallExpression(e)||d.isNewExpression(e)){if(e.getExpression?.()===n)return"callee";if((e.getArguments?.()??[]).indexOf(n)>=0)return"argument"}if(d.isPropertyAccessExpression(e)){if(e.getExpression()===n)return"object";if(e.getNameNode()===n)return"property"}}catch{return null}return null}function Je(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}function wn(n){try{if(d.isFunctionDeclaration(n)||d.isMethodDeclaration(n)||d.isConstructorDeclaration(n)||d.isFunctionExpression(n)||d.isArrowFunction(n)){let e=n.getParameters?.();if(Array.isArray(e))return e.length}}catch{}return null}function Pn(n){try{return d.isIdentifier(n)?n.getSymbol():d.isPropertyAccessExpression(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol?.()}catch{return}}function Me(n,e){try{return typeof n?.hasModifier=="function"&&n.hasModifier(e)}catch{return!1}}function Et(n){try{return n.getModuleSpecifierValue?.()??null}catch{try{return n.getModuleSpecifier?.()?.getLiteralText?.()??null}catch{return null}}}function Nn(n,e,t){if(!d.isImportDeclaration(n))return;let i={moduleSpecifier:Et(n),isTypeOnly:n.isTypeOnly(),namedImports:[]};try{let s=n.getDefaultImport();if(s){let o=s.getText();i.defaultImport=o,t(o,s)}}catch{}try{let s=n.getNamespaceImport();if(s){let o=s.getText();i.namespaceImport=o,t(o,s)}}catch{}try{n.getNamedImports().forEach(s=>{try{let o=s.getName(),l=s.getAliasNode(),c=l?l.getText():void 0;o&&(i.namedImports.push({name:o,alias:c||void 0}),t(c||o,s.getNameNode()))}catch{}})}catch{}e.push(i)}function Rn(n,e){if(d.isExportDeclaration(n)){let t=Et(n);if(t){if(n.getNamedExports().length>0)try{n.getNamedExports().forEach(r=>{try{let i=r.getName(),s=r.getAliasNode(),o=s?s.getText():void 0;e.push({kind:"reexport",moduleSpecifier:t,name:i||void 0,alias:o||void 0,isNamespace:!1})}catch{}})}catch{}else if(n.isNamespaceExport())try{let i=n.getNamespaceExport()?.getName();e.push({kind:"reexport",moduleSpecifier:t,name:i||"*",alias:i||void 0,isNamespace:!0})}catch{e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0})}else e.push({kind:"reexport",moduleSpecifier:t,name:"*",isNamespace:!0});return}try{n.getNamedExports().forEach(r=>{try{let i=r.getName();if(!i)return;let s=r.getAliasNode(),o=s?s.getText():i;e.push({kind:"alias",local:i,exported:o})}catch{}})}catch{}return}if(d.isExportAssignment(n))try{let t=n.getExpression();if(t&&d.isIdentifier(t)){let r=t.getText();e.push({kind:"alias",local:r,exported:"default"})}}catch{}}function In(n,e,t,r){if(!Me(n,le.ExportKeyword))return;let i=Me(n,le.DefaultKeyword);if(d.isVariableStatement(n)){try{let s=n.getDeclarationList().getDeclarations();for(let o of s){let l=Ce(o)??o.getName?.()??null;if(l){t(l,o);let c=r(o);c&&e.push({kind:"local",name:l,isDefault:i,nodeId:c})}}}catch{}return}if(d.isFunctionDeclaration(n)||d.isClassDeclaration(n)||d.isInterfaceDeclaration(n)||d.isEnumDeclaration(n)||d.isTypeAliasDeclaration(n)||d.isModuleDeclaration(n)){let s=Ce(n)||(i?"default":null),o=r(n);o&&e.push({kind:"local",name:s??"default",isDefault:i,nodeId:o})}}function wt(n,e,t,r){let i=[],s=[],o=[],l=new Set,c=new Map,u=[],m=[],C=(r?.emitMode??"light")==="full",I=new Map,K=new Map,R=new Map,F=[{node:n,id:null,kind:"module",rawKind:"SourceFile",rawKindSource:"ts-morph",name:null,isExported:!1}],O=a=>{if(!a)return null;try{return e(a)}catch{return null}},U=a=>{let f=a.getParent?.();for(;f;){let h=I.get(f);if(h)return h;f=f.getParent?.()}return null},z=(a,f)=>{if(a&&(l.has(a)||l.add(a),f&&!c.has(a))){let h=O(f);h&&c.set(a,h)}},H=a=>d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isInterfaceDeclaration(a)||d.isEnumDeclaration(a)||d.isEnumMember(a)||d.isTypeAliasDeclaration(a)||d.isModuleDeclaration(a)||d.isMethodDeclaration(a)||d.isMethodSignature(a)||d.isPropertyDeclaration(a)||d.isPropertySignature(a)||d.isGetAccessorDeclaration(a)||d.isSetAccessorDeclaration(a)||d.isConstructorDeclaration(a)||d.isVariableDeclaration(a),ge=a=>d.isSourceFile(a)||d.isFunctionDeclaration(a)||d.isFunctionExpression(a)||d.isArrowFunction(a)||d.isMethodDeclaration(a)||d.isConstructorDeclaration(a)||d.isClassDeclaration(a)||d.isClassExpression(a)||d.isModuleDeclaration(a),V=a=>{let f=Ce(a);if(f)return f;if(d.isConstructorDeclaration(a))return"constructor";if(d.isArrowFunction(a)||d.isFunctionExpression(a)){let h=a.getParent();try{if(d.isVariableDeclaration(h))return h.getName();if(d.isPropertyAssignment(h)||d.isPropertyDeclaration(h)||d.isPropertySignature(h))return h.getName?.()??null;if(d.isShorthandPropertyAssignment(h))return h.getNameNode()?.getText()??null;if(d.isExportAssignment(h))return"default"}catch{}}if(d.isEnumMember(a))try{return a.getName()}catch{return null}if(d.isVariableDeclaration(a))try{return a.getName()}catch{return null}return null},Y=a=>{let f=F[F.length-1],h=f?.id??null,P=f?.kind??"module",g=f?.name??null;if(d.isImportDeclaration(a))Nn(a,u,z);else if(d.isImportEqualsDeclaration(a))try{let S=a.getModuleReference();if(S&&d.isExternalModuleReference(S)){let x=S.getExpression(),v;if(x&&d.isStringLiteral(x))v=x.getLiteralText();else if(x){let w=x.getText();v=typeof w=="string"?w.replace(/^['"]|['"]$/g,""):void 0}if(v){let M=a.getNameNode()?.getText(),_={moduleSpecifier:v,isTypeOnly:!1,namedImports:[]};M&&(_.defaultImport=M,z(M,a)),u.push(_)}}}catch{}(d.isExportDeclaration(a)||d.isExportAssignment(a))&&Rn(a,m),In(a,m,z,O);let y=H(a),E=C||y,N=y?V(a):null;if(E){let S=e(a);y&&s.push({nodeId:S,node:a});let x=U(a),v=x==null?null:K.get(x)??0;x!=null&&v!=null&&K.set(x,v+1),I.set(a,S);let w=x?(R.get(x)??-1)+1:0;R.set(S,w);let M=Me(a,le.ExportKeyword)||f?.isExported||!1,_=y?a.getNameNode?.()?.getText?.()??null:null,D=N??(y?Ce(a)??_:Ce(a));N?z(N,a):D&&z(D,a);let A=Je(a),L=wn(a),k=Ae(a);ke(k,{source:"ts-node-collector",file:n.getFilePath(),name:D??null});let J=vn(a);i.push({nodeId:S,nodeName:D??null,containerId:h,containerKind:P,containerRawKind:f?.rawKind??null,containerRawKindSource:f?.rawKindSource??null,containerName:g,isExported:M,kind:k.kind,rawKind:k.rawKind,rawKindSource:k.rawKindSource,semanticKind:k.semanticKind??null,start:A.start,end:A.end,paramCount:L,metadata:null,parentNodeId:x,role:En(a),indexInParent:v,depth:w,bodyStart:J?.start??null,bodyEnd:J?.end??null})}if(d.isCallExpression(a)||d.isNewExpression(a)){let S=a.getExpression(),x=null,v,w;try{if(w=Pn(S),d.isIdentifier(S))x=S.getText();else if(d.isPropertyAccessExpression(S)){x=S.getName();let D=S.getExpression();d.isIdentifier(D)&&(v=D.getText())}}catch{}let M="";try{M=S.getText()}catch{}let _=Je(a);if(o.push({name:x,kind:d.isNewExpression(a)?"new":"call",containerId:h,containerKind:P,containerName:g,expression:M,objectName:v,symbol:w,start:_.start,end:_.end}),d.isCallExpression(a))try{if(d.isIdentifier(S)&&S.getText()==="require"){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}if(L){let k={moduleSpecifier:L,isTypeOnly:!1,namedImports:[]},J=a.getParent();if(J&&d.isVariableDeclaration(J)){let Re=J.getNameNode();try{if(d.isIdentifier(Re)){let he=Re.getText();he&&(k.defaultImport=he,z(he,J))}}catch{}}u.push(k)}}else if(S?.getKind?.()===le.ImportKeyword){let A=a.getArguments()[0],L;if(A&&(d.isStringLiteral(A)||d.isNoSubstitutionTemplateLiteral(A)))try{L=A.getLiteralText()}catch{let k=A.getText();L=typeof k=="string"?k.replace(/^['"]|['"]$/g,""):void 0}L&&u.push({moduleSpecifier:L,isTypeOnly:!1,namedImports:[]})}}catch{}}if(d.isCallExpression(a)){let S=a.getExpression();try{if(d.isIdentifier(S)&&S.getText()==="require"){let x=a.getParent();if(!(x&&d.isExternalModuleReference(x))){let w=a.getArguments()[0],M;if(w&&(d.isStringLiteral(w)||d.isNoSubstitutionTemplateLiteral(w)))try{M=w.getLiteralText()}catch{M=w.getText().replace(/^['"]|['"]$/g,"")}if(M){let _={moduleSpecifier:M,isTypeOnly:!1,namedImports:[]};if(x&&d.isVariableDeclaration(x)){let D=x.getNameNode();try{if(d.isIdentifier(D)){let A=D.getText();A&&(_.defaultImport=A,z(A,x))}}catch{}}u.push(_)}}}else if(S?.getKind?.()===le.ImportKeyword){let v=a.getArguments()[0],w;if(v&&(d.isStringLiteral(v)||d.isNoSubstitutionTemplateLiteral(v)))try{w=v.getLiteralText()}catch{w=v.getText().replace(/^['"]|['"]$/g,"")}w&&u.push({moduleSpecifier:w,isTypeOnly:!1,namedImports:[]})}}catch{}}let j=!1;if(ge(a)){let S=O(a)??e(a),x=vt(a);F.push({node:a,id:S,kind:x.kind,rawKind:x.rawKind,rawKindSource:x.rawKindSource,name:N??g,isExported:Me(a,le.ExportKeyword)||f?.isExported||!1}),j=!0}a.forEachChild(Y),j&&F.pop()};if(C){let a=e(n);I.set(n,a),R.set(a,0);let f=Je(n);i.push({nodeId:a,nodeName:n.getBaseName?.()??null,containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:"SourceFile",rawKind:"SourceFile",rawKindSource:"ts-morph",semanticKind:"file",start:f.start,end:f.end,paramCount:null,metadata:null,parentNodeId:null,role:null,indexInParent:null,depth:0,bodyStart:f.start,bodyEnd:f.end})}if(n.forEachChild(Y),r?.includeComments===!0||C||process.env.AST_INDEX_COMMENTS==="1")try{let a=n.getFullText(),f=X.createScanner(X.ScriptTarget.Latest,!1,X.LanguageVariant.Standard,a),h=new Set;for(let P=f.scan();P!==X.SyntaxKind.EndOfFileToken;P=f.scan()){if(P!==X.SyntaxKind.SingleLineCommentTrivia&&P!==X.SyntaxKind.MultiLineCommentTrivia)continue;let g=f.getTokenPos(),y=f.getTextPos(),E=`${g}-${y}`;if(h.has(E)||(h.add(E),t.has(E)))continue;t.add(E);let N=a.substring(g,y),j=bt(P,N),x=e({getKindName:()=>j.name,getKind:()=>j.kind,getPos:()=>g,getEnd:()=>y,getStart:()=>g,getFullStart:()=>g,getText:()=>N,getSourceFile:()=>n,getParent:()=>n,__isComment:!0,__commentPosition:"standalone",__attachedTo:null},"COM"),v=I.get(n)??null,w=C&&v!=null?K.get(v)??0:null;C&&v!=null&&w!=null&&K.set(v,w+1),i.push({nodeId:x,nodeName:N.substring(0,100),containerId:null,containerKind:"module",containerRawKind:"SourceFile",containerRawKindSource:"ts-morph",containerName:null,isExported:!1,kind:j.name,rawKind:j.name,rawKindSource:"ts-morph",semanticKind:null,start:g,end:y,paramCount:null,metadata:null,parentNodeId:v,role:"comment",indexInParent:w,depth:C?1:0,bodyStart:null,bodyEnd:null})}}catch{}return{nodes:i,symbolCandidateNodes:s,references:o,declaredNames:l,localDeclarations:c,imports:u,exports:Cn(m)}}function Pt(n){let e;try{let r=n.getStart?.(!1);typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}if(e===void 0)try{let r=n.getFullStart?.();typeof r=="number"&&Number.isFinite(r)&&(e=r)}catch{}e===void 0&&(e=0);let t;try{let r=n.getEnd?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}if(t===void 0)try{let r=n.getStart?.();typeof r=="number"&&Number.isFinite(r)&&(t=r)}catch{}return t===void 0&&(t=e),t<e&&(t=e),{start:e,end:t}}var Mn=100;function Dn(n,e,t,r){let{start:i,end:s}=Pt(e),o=Ae(e);ke(o,{source:"ts-node-id",file:n,kind:o.kind});let l=r||Z.getAbbrev(o.kind,t);return`${n}#${i}-${s}:${l}`}function Tn(n,e){return Ue.relative(n,e).replace(/\\/g,"/")}function Nt(n,e){if(!n)return null;let t=n;try{let m=n.getAliasedSymbol();m&&(t=m)}catch{}let r=[];try{r=t.getDeclarations()??[]}catch{r=[]}if(!r.length)return null;let s=r.slice().sort((m,p)=>{let C=m.getSourceFile().getFilePath(),I=p.getSourceFile().getFilePath();if(C!==I)return C.localeCompare(I);let K=m.getStart(!1),R=p.getStart(!1);return K!==R?K-R:m.getEnd()-p.getEnd()})[0],o=Tn(e,s.getSourceFile().getFilePath()),l=s.getStart(!1),c=s.getEnd(),u="";try{u=t.getEscapedName()}catch{try{u=t.getName()}catch{u=""}}return`${o}#${l}-${c}:${u}`}function Kn(n){try{return G.isVariableDeclaration(n)||G.isEnumMember(n)?n.getNameNode().getSymbol()??n.getSymbol():n.getSymbol()}catch{return}}function _n(n,e){let t=n.getDescendantAtPos(e);if(!t)return;let r=t;if(!G.isCallExpression(r)&&!G.isNewExpression(r)&&(r=t.getFirstAncestor(s=>G.isCallExpression(s)||G.isNewExpression(s))??void 0),!r||!G.isCallExpression(r)&&!G.isNewExpression(r))return;let i=r.getExpression();try{return G.isIdentifier(i)?i.getSymbol():G.isPropertyAccessExpression(i)?i.getNameNode().getSymbol()??i.getSymbol():i.getSymbol()}catch{return}}async function On(n){let{sf:e,fileRel:t,content:r,preDeleted:i,meta:s,projectRoot:o,lang:l}=n,c=n.emitMode??"light",m=wt(e,(g,y)=>Dn(t,g,l,y),new Set,{includeComments:c==="full",emitMode:c}),p=new Map;for(let{nodeId:g,node:y}of m.symbolCandidateNodes){let E=Nt(Kn(y),o);E&&(p.has(g)||p.set(g,E))}let C=[],I=new Map,K=m.exports.filter(g=>g.kind!=="reexport"),R=m.exports.filter(g=>g.kind==="reexport");for(let g of K)if(g.kind==="local"){let y=g.isDefault?"default":g.name;if(!y||I.has(y))continue;let E=g.nodeId;C.push([t,y,E,0,null,null,g.isDefault?"default":"named"]),I.set(y,E)}else if(g.kind==="alias"){let y=g.exported;if(!y||I.has(y))continue;C.push([t,y,null,0,null,g.local,"alias"]),I.set(y,"alias")}for(let g of R){let y=g.moduleSpecifier;if(!y)continue;let E=y;if(g.isNamespace){let N=g.alias||"*";if(I.has(N))continue;C.push([t,N,null,1,E,g.name||N,"reexport_star"]),I.set(N,"reexport")}else{let N=g.alias||g.name;if(!N||I.has(N))continue;C.push([t,N,null,1,E,g.name||N,"reexport_named"]),I.set(N,"reexport")}}let F=[],O=typeof r=="string"?r:null;if(O==null)try{let g=e.getFullText();O=typeof g=="string"?g:null}catch{O=null}for(let g of m.nodes){let{nodeId:y,nodeName:E,containerKind:N,containerRawKind:j,containerRawKindSource:S,isExported:x,kind:v,rawKind:w,rawKindSource:M,semanticKind:_,start:D,end:A,paramCount:L,metadata:k,parentNodeId:J,role:Re,indexInParent:he,depth:mn,bodyStart:fn,bodyEnd:gn}=g,hn=k&&Object.keys(k).length?JSON.stringify(k):null,yn=p.get(y)??null;F.push([y,E??null,v,w??v,M??null,_??null,D,A,x?1:0,N??"module",j??N??"module",S??null,L,null,null,yn,hn,J??null,Re??null,he??null,mn??0,fn??null,gn??null])}let U=[];for(let g of m.references){let{name:y,kind:E,containerId:N,containerName:j,expression:S,objectName:x,start:v,end:w}=g,M=null,_=null,D=Nt(g.symbol??_n(e,v),o),A=y?m.localDeclarations.get(y):void 0;A&&(M=A,_=t,D||(D=p.get(A)??null));let L=Ie({sourceFile:t,sourceStart:v,sourceEnd:w,refKind:E,refName:y,targetFile:_,targetNodeId:M}),k={};S&&(k.expression=S),x&&(k.objectName=x),j&&(k.containerName=j);let J=Object.keys(k).length?JSON.stringify(k):null;U.push([L,t,N,y,E,v,w,M,_,M?"resolved":"unresolved",x??null,null,null,D,J])}let z=[],H=[];for(let g of m.imports){let y=g.moduleSpecifier??null;z.push([t,y,g.isTypeOnly?1:0]),g.defaultImport&&H.push([t,y,"default",g.defaultImport,"default",g.isTypeOnly?1:0]),g.namespaceImport&&H.push([t,y,"namespace",g.namespaceImport,"*",g.isTypeOnly?1:0]);for(let E of g.namedImports){let N=E.alias||E.name;H.push([t,y,"named",N,E.name,g.isTypeOnly?1:0])}}let ge=Ue.join(o,t),V=s?.size,Y=s?.mtime;if(V===void 0||Y===void 0)try{let g=An.statSync(ge);V=g.size,Y=Math.floor(g.mtimeMs)}catch{}let a=new Date().toISOString(),f=c==="full",h=[t,Y??null,V??null,"completed",a,f?1:0],P=null;if(typeof O=="string")P={blobOid:t,content:O};else try{let g=e.getFullText?.();typeof g=="string"&&(P={blobOid:t,content:g})}catch(g){console.log(`[TypescriptIndexer] Failed to compute FTS payload for ${t}:`,g?.message??g)}return{payload:{lang:l,fileRel:t,preDeleted:i,exportRows:C,nodeRows:F,referenceRows:U,importRows:z,importBindingRows:H,fileRow:h,fts:P,fullyIndexed:f},fileSize:V,mtime:Y}}var We=class{constructor(e,t){this.project=null;this.filesProcessed=0;this.projectRoot=e,this.lang=t}getProject(){return this.project||(this.project=new kn({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0})),this.project}disposeProject(){if(this.project){try{let e=this.project.getLanguageService().compilerObject;typeof e?.dispose=="function"&&e.dispose()}catch{}this.project=null}}async process(e){let t=this.getProject(),r;try{let i=t.createSourceFile(Ue.join(this.projectRoot,e.relPath),e.content,{overwrite:!0});r=await On({sf:i,fileRel:e.relPath,content:e.content,preDeleted:!!e.preDeleted,meta:e.meta,projectRoot:this.projectRoot,lang:e.lang,emitMode:e.emitMode??"light"})}catch(i){this.disposeProject(),this.filesProcessed=0;let s=i?.message||String(i);throw new Error(`TypeScript parser failed for ${e.relPath}: ${s}`)}return this.filesProcessed++,this.filesProcessed>=Mn&&(this.disposeProject(),this.filesProcessed=0),{payload:r.payload,fileSize:r.fileSize,mtime:r.mtime}}};function Ln(n){return n==="ts"?[".ts",".tsx",".mts",".cts"]:n==="js"?[".js",".jsx",".mjs",".cjs"]:[]}function Xe(n){return{id:n,extensions:Ln(n),indexingMode:"worker",createIndexer:e=>new We(e,n)}}import Te from"fs";import ee from"path";import{spawn as $n}from"child_process";import Fn from"fs";var ce=class{constructor(e=5e3){this.maxEntries=e;this.cache=new Map}get(e,t){let r=this.cache.get(e);if(!r)return null;let i=t?.mtime??null,s=t?.size??null;return i!=null&&s!=null&&r.mtime===i&&r.size===s?r.result:null}set(e,t,r){let i=t?.mtime??null,s=t?.size??null;this.cache.set(e,{mtime:i,size:s,result:r}),this.cache.size>this.maxEntries&&this.cache.clear()}};var Ge=class{constructor(e,t,r,i){this.projectRoot=e;this.lang=t;this.parse=r;this.exportKind=i;this.cache=new ce}async process(e){let t=e.meta?.mtime,r=e.meta?.size;if(t==null||r==null)try{let o=Fn.statSync(e.absPath);t=Math.floor(o.mtimeMs),r=o.size}catch{}let i=e.emitMode==="full"?null:this.cache.get(e.absPath,{mtime:t,size:r});if(i)return be({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:i,resolveNodeId:Rt(e.relPath,i,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"});let s=null;try{s=await this.parse({absPath:e.absPath,relPath:e.relPath,content:e.content,meta:{mtime:t,size:r},projectRoot:this.projectRoot,lang:this.lang,emitMode:e.emitMode??"light"})}catch(o){try{console.log(`[CliContract:${this.lang}] parse threw for ${e.relPath}: ${o?.message||String(o)}`)}catch{}return ye(this.lang,e.relPath,{mtime:t,size:r})}return!s||s.error?ye(this.lang,e.relPath,{mtime:t,size:r}):(e.emitMode!=="full"&&this.cache.set(e.absPath,{mtime:t,size:r},s),be({lang:this.lang,fileRel:e.relPath,content:e.content,meta:{mtime:t,size:r},preDeleted:e.preDeleted,parsed:s,resolveNodeId:Rt(e.relPath,s,this.lang),exportKind:this.exportKind??"cli",fullyIndexed:e.emitMode==="full"}))}};function Rt(n,e,t){let r=new Map;for(let i of e.nodes??[]){if(!i.name||r.has(i.name))continue;let s=`${n}#${i.start}-${i.end}:${Z.getAbbrev(i.kind,t)}`;r.set(i.name,s)}return i=>r.get(i)??null}function Q(n){return{id:n.id,extensions:n.extensions,indexingMode:"worker",createIndexer:e=>new Ge(e,n.id,n.parse,n.exportKind),resolveSpan:n.resolve?async(e,t,r)=>n.resolve({projectRoot:e,absPath:t,nodePath:r,lang:n.id}):void 0}}import jn from"fs";import De from"path";var Qe=null;function Bn(n){for(let e of n)if(jn.existsSync(e))return e;return null}function q(n){let e=Qe?.toolsRoot??process.env.PANDO_TOOLS_ROOT,t=Qe?.runtimeRoot??process.env.PANDO_RUNTIME_ROOT,r=Qe?.resourcesRoot??process.env.PANDO_RESOURCES_ROOT,i=[e?De.join(e,n):null,t?De.join(t,"tools",n):null,r?De.join(r,"tools",n):null,De.resolve(process.cwd(),"tools",n)].filter(s=>!!s);return Bn(i)}function W(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
2
2
|
`)}catch{}}var zn=Number(process.env.PANDO_PYTHON_WORKER_PARSE_TIMEOUT_MS||18e4),qn=Number(process.env.PANDO_PYTHON_WORKER_RESOLVE_TIMEOUT_MS||6e4),pe=class extends Error{constructor(t,r){super(t);this.fatal=r;this.name="PythonWorkerRequestError"}},Ke=class{constructor(e,t){this.interpreter=e;this.scriptPath=t;this.buffer=Buffer.alloc(0);this.pending=new Map;this.requestQueue=Promise.resolve();this.seq=1;this.closed=!1;if(this.proc=$n(this.interpreter,["-u",this.scriptPath],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw new Error("python worker stdio unavailable");this.proc.stdout.on("data",r=>this.onData(r)),this.proc.stderr.on("data",r=>{W(`[PythonWorker] ${r.toString("utf8").trim()}`)}),this.proc.stdin.on("error",r=>this.handleError(r)),this.proc.on("error",r=>this.handleError(r)),this.proc.on("exit",r=>this.handleError(new Error(`python worker exited with code ${r}`))),this.ready=this.ping()}handleError(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)t.timeout&&clearTimeout(t.timeout),t.summary&&W("[PythonCliAdapter] worker error",{interpreter:this.interpreter,error:e.message,...t.summary}),t.reject(e);this.pending.clear();try{this.proc.stdin?.end()}catch{}try{this.proc.kill()}catch{}}}onData(e){for(this.buffer=Buffer.concat([this.buffer,e]);this.buffer.length>=4;){let t=this.buffer.readUInt32BE(0);if(this.buffer.length<4+t)return;let r=this.buffer.slice(4,4+t);this.buffer=this.buffer.slice(4+t);let i=null;try{i=JSON.parse(r.toString("utf8"))}catch{continue}let s=this.pending.get(i.id);s&&(this.pending.delete(i.id),s.timeout&&clearTimeout(s.timeout),i.ok?s.resolve(i):s.reject(new pe(i.error||"python worker error",!1)))}}sendMessage(e){if(this.closed)throw new Error("python worker is closed");let t=Buffer.from(JSON.stringify(e),"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0),this.proc.stdin.write(r),this.proc.stdin.write(t)}async requestRaw(e,t,r=1e4){let i=this.seq++,s={id:i,op:e,...t},o={op:e,id:i};return typeof t?.path=="string"&&(o.path=t.path),typeof t?.nodePath=="string"&&(o.nodePath=t.nodePath),typeof t?.content_b64=="string"&&(o.contentBytes=t.content_b64.length),new Promise((l,c)=>{let u=setTimeout(()=>{this.pending.delete(i);let m=new pe(`python worker timeout (${e})`,!0);W("[PythonCliAdapter] worker timeout",{op:e,id:i,timeoutMs:r,pending:this.pending.size,interpreter:this.interpreter,...o}),c(m),this.handleError(m)},r);this.pending.set(i,{resolve:l,reject:c,timeout:u,summary:o}),this.pending.size%200===0&&W("[PythonCliAdapter] worker pending",{op:e,pending:this.pending.size,interpreter:this.interpreter});try{this.sendMessage(s)}catch(m){clearTimeout(u),this.pending.delete(i),c(m)}})}async enqueueRequest(e){let t=this.requestQueue.catch(()=>{}),r,i=new Promise(s=>{r=s});this.requestQueue=t.then(()=>i),await t;try{return await e()}finally{r()}}async request(e,t,r=1e4){await this.ready;let i=Date.now();return this.enqueueRequest(async()=>{let s=Date.now()-i,o=Date.now();s>2e3&&W("[PythonCliAdapter] worker queued",{op:e,queueMs:s,interpreter:this.interpreter,path:t?.path});let l=await this.requestRaw(e,t,r),c=Date.now()-o;return c>2e3&&W("[PythonCliAdapter] worker slow",{op:e,ms:c,queueMs:s,pending:this.pending.size,interpreter:this.interpreter,path:t?.path}),l})}async ping(){await this.requestRaw("ping",{},5e3)}async parse(e){let t=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("parse",{path:e.path,content_b64:t,encoding:e.encoding,emit_mode:e.emitMode??"light"},zn);return r.nodes?r:null}async resolve(e){let t=Buffer.from(e.content,"utf8").toString("base64"),r=await this.request("resolve",{path:e.path,nodePath:e.nodePath,content_b64:t,encoding:e.encoding},qn);return typeof r.start=="number"&&typeof r.end=="number"?r:null}close(){if(this.closed)return;this.closed=!0;for(let[,t]of this.pending)t.timeout&&clearTimeout(t.timeout),t.reject(new Error("python worker client closed"));this.pending.clear();let e=this.proc;try{e.stdin?.end()}catch{}try{e.kill()}catch{}}};function It(n){let e=ee.resolve(n,"tools/python-indexer/pando_python_worker.py");if(Te.existsSync(e))return e;let t=q("python-indexer/pando_python_worker.py");if(t)return t;let r=ee.resolve(__dirname,"../../../../../tools/python-indexer/pando_python_worker.py");return Te.existsSync(r)?r:null}var de=new Map;function ue(n){try{return Te.readFileSync(n,"utf8")}catch{return null}}function ve(n){if(!n)return null;let e=n.match(/(\d+)\.(\d+)/);return e?{major:Number(e[1]),minor:Number(e[2])}:null}function Jn(n){let e=ue(ee.join(n,"pyproject.toml"));if(e){let l=e.match(/requires-python\s*=\s*"([^"]+)"/i),c=ve(l?.[1]??null);if(c)return c}let t=ue(ee.join(n,"setup.cfg"));if(t){let l=t.match(/python_requires\s*=\s*([\w\d\.<>~=\s]+)/i),c=ve(l?.[1]??null);if(c)return c}let r=ue(ee.join(n,"setup.py"));if(r){let l=r.match(/python_requires\s*=\s*['\"]([^'\"]+)['\"]/i),c=ve(l?.[1]??null);if(c)return c}let i=ue(ee.join(n,"tox.ini"));if(i){let l=i.match(/envlist\s*=\s*([^\n]+)/i);if(l&&l[1]){let c=l[1].split(/[,\s]+/).filter(Boolean);for(let u of c){let m=u.match(/py(\d)(\d)/i);if(m)return{major:Number(m[1]),minor:Number(m[2])}}}}let s=ue(ee.join(n,".python-version"));if(s){let l=ve(s.trim());if(l)return l}let o=ue(ee.join(n,"runtime.txt"));if(o){let l=o.match(/python-(\d+\.\d+)/i),c=ve(l?.[1]??null);if(c)return c}return null}function At(n){return Jn(n)?.major===2?["python2","python","python3"]:["python3","python","python2"]}async function Wn(n,e,t,r){let i=It(n);if(!i)return null;let s=At(n);for(let o of s){let l=`${o}::${i}`,c=de.get(l);if(!c)try{c=new Ke(o,i),de.set(l,c)}catch{continue}try{let u=await c.parse({path:e,content:t,encoding:"utf-8",emitMode:r});if(u)return u}catch(u){let m=u?.message||String(u),p=u instanceof pe?u.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(m);W("[PythonCliAdapter] worker parse error",{file:e,interpreter:o,script:i,fatal:p,error:m}),p&&de.delete(l)}}return null}async function Un(n,e,t,r){let i=It(n);if(!i)return null;let s=At(n);for(let o of s){let l=`${o}::${i}`,c=de.get(l);if(!c)try{c=new Ke(o,i),de.set(l,c)}catch{continue}try{let u=await c.resolve({path:e,nodePath:r,content:t,encoding:"utf-8"});if(u)return u}catch(u){let m=u?.message||String(u),p=u instanceof pe?u.fatal:/timeout|closed|exited|EPIPE|ENOENT|spawn/i.test(m);W("[PythonCliAdapter] worker resolve error",{file:e,interpreter:o,nodePath:r,script:i,fatal:p,error:m}),p&&de.delete(l)}}return null}async function Xn(n){let e=Date.now(),t=!1,r=null;try{r=await Wn(n.projectRoot,n.absPath,n.content,n.emitMode??"light"),t=!!r}catch{}if(!r){W(`[PythonCliAdapter] parse failed for ${n.relPath} via python worker`);let o=Date.now()-e;return o>2e3&&W("[PythonCliAdapter] parse slow (failed)",{file:n.relPath,ms:o}),null}let i=[];for(let o of r.references||[]){let l={};o.expression&&(l.expression=o.expression),o.objectName&&(l.objectName=o.objectName),o.containerName&&(l.containerName=o.containerName),o.containerKind&&(l.containerKind=o.containerKind),i.push({sourceStart:o.start,sourceEnd:o.end,refKind:o.kind,refName:o.name,receiverName:o.receiverName??o.objectName??null,arity:typeof o.arity=="number"?o.arity:null,containerQualifiedName:o.containerQualifiedName??null,targetSymbolKey:o.targetSymbolKey??null,metadata:Object.keys(l).length?l:null})}let s=Date.now()-e;return s>2e3&&W("[PythonCliAdapter] parse slow",{file:n.relPath,ms:s,usedWorker:t}),{nodes:r.nodes,imports:r.imports,importBindings:r.importBindings,references:i,modulePublic:r.modulePublic??void 0,explicitExports:r.explicitExports??void 0}}function kt(){return Q({id:"python",extensions:[".py",".pyw",".pyi"],exportKind:"named",parse:({absPath:n,relPath:e,projectRoot:t,content:r,emitMode:i})=>Xn({absPath:n,relPath:e,projectRoot:t,content:r,emitMode:i}),resolve:async({absPath:n,nodePath:e,projectRoot:t})=>{try{let r=Te.readFileSync(n,"utf8"),i=await Un(t,n,r,e);if(i)return i}catch{}return null}})}import Tt from"fs";import Kt from"path";import{spawn as Yn,spawnSync as es}from"child_process";var Gn=!1,_e=new Set,Mt=!1;function Qn(n){_e.add(n),Vn()}function Hn(n){_e.delete(n)}function te(n){return Qn(n),n.on?.("exit",()=>Hn(n)),n}function Dt(n="SIGKILL"){Gn=!0;for(let e of _e)try{e.kill(n)}catch{}_e.clear()}function Vn(){if(Mt)return;Mt=!0,process.on("exit",()=>{Dt("SIGKILL")});let n=()=>{Dt("SIGKILL")};process.once("SIGINT",n),process.once("SIGTERM",n),process.once("SIGHUP",n)}var Zn=256e3,er=32;function re(...n){try{let e=n.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ");process.stderr.write(e+`
|
|
3
3
|
`)}catch{}}var He=class{constructor(e){this.cmd=e;this.proc=null;this.buffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,this.proc=Yn(this.cmd,["--server"],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("csharp indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{re(`[CSharpIndexer] ${e.toString("utf8").trim()}`)}),this.proc.stdin.on("error",e=>this.handleExit(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`csharp indexer exited with code ${e}`))),te(this.proc)}}handleExit(e){if(!this.closed){this.closed=!0;for(let[,t]of this.pending)t.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.indexOf(`
|
|
4
4
|
`);if(t<0)break;let r=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!r)continue;let i=null;try{i=JSON.parse(r)}catch{continue}let s=this.pending.get(i.id);s&&(this.pending.delete(i.id),i.ok?s.resolve(i):s.reject(new Error(i.error||"csharp server error")))}}async request(e,t=1){this.ensureProcess();let r=this.seq++;return new Promise((i,s)=>{let o={id:r,...e};this.pending.set(r,{resolve:i,reject:s});try{this.proc.stdin.write(`${JSON.stringify(o)}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{b as k}from"./chunk-RRIZV7YJ.mjs";var O=k(()=>{"use strict"});import s from"path";import $ from"os";import l from"fs";import E from"crypto";function D(){return process.env.PANDO_DATA_DIR||s.join($.homedir(),h)}function P(t){let n=t,r=s.parse(n);for(;n.length>r.root.length&&/[\\/]+$/.test(n);)n=n.replace(/[\\/]+$/,"");return n}function g(t){let n=s.resolve(t),r=n;try{let e=l.realpathSync.native;r=typeof e=="function"?e(n):l.realpathSync(n)}catch{}return P(r)}function W(t){let n=t.trim().replace(/\.git$/,"");if(!n)return null;let r=n.match(/^git@([^:]+):(.+)$/);if(r){let e=r[1],i=r[2].replace(/^\/+/,"").split("/");if(i.length>=2)return`${e}/${i[0]}/${i[1]}`}try{let e=new URL(n),o=e.hostname,c=e.pathname.replace(/^\/+/,"").split("/");if(o&&c.length>=2)return`${o}/${c[0]}/${c[1]}`}catch{}return null}function m(t){return E.createHash("sha1").update(t).digest("hex").slice(0,12)}function L(t){return t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-._]+|[-._]+$/g,"").slice(0,64).replace(/^[-._]+|[-._]+$/g,"")||"workspace"}function C(t,n){let r=s.basename(P(t));return`${L(r)}-${n}`}function N(){return s.join(D(),"workspace-registry.json")}function p(t){try{return l.readFileSync(t,"utf8").trim()}catch{return null}}function _(t){let n=s.join(t,".git");try{let r=l.statSync(n);if(r.isDirectory())return n;if(r.isFile()){let o=p(n)?.match(/^gitdir:\s*(.+)$/i);if(o){let i=o[1].trim();return s.isAbsolute(i)?i:s.resolve(t,i)}}}catch{return null}return null}function G(t){let n=s.join(t,"commondir"),r=p(n);if(!r)return g(t);let e=s.isAbsolute(r)?r:s.resolve(t,r);return g(e)}function T(t){return g(s.join(t,"objects"))}function F(t){let n=g(t);for(;;){let r=s.join(n,".git");if(l.existsSync(r))return n;let e=s.dirname(n);if(e===n)break;n=e}return null}function M(t){let n=g(t),r=F(n);return r?g(r):null}function H(t){let n=s.join(t,"config"),r=p(n);if(!r)return null;let e=r.split(/\r?\n/),o=!1,i=null;for(let c of e){if(c.match(/^\s*\[remote\s+"([^"]+)"\]\s*$/)){o=!0;continue}if(c.startsWith("[")&&(o=!1),o){let a=c.match(/^\s*url\s*=\s*(.+)$/);if(a&&(i=a[1].trim(),i))return i}}return i}function z(t){let n=s.join(t,"HEAD"),r=p(n);if(!r)return{branch:null,commit:null};if(r.startsWith("ref:")){let e=r.replace("ref:","").trim(),o=e.split("/").slice(-1)[0]||null,i=s.join(t,e),c=p(i);if(!c){let u=p(s.join(t,"packed-refs"));if(u){let a=u.split(/\r?\n/).find(f=>f.endsWith(` ${e}`));a&&(c=a.split(" ")[0])}}return{branch:o,commit:c||null}}return{branch:"HEAD",commit:r||null}}function U(){try{let t=l.readFileSync(N(),"utf8"),n=JSON.parse(t);if(n&&n.version===1&&n.entries&&typeof n.entries=="object")return{version:1,entries:n.entries}}catch{}return{version:1,entries:{}}}function J(t){let n=N(),r=s.dirname(n);l.mkdirSync(r,{recursive:!0});let e=`${n}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,"utf8"),l.renameSync(e,n)}function B(t,n){if(!n)return{canonicalRepoRoot:t,gitCommonDir:null,gitObjectDir:null,fingerprint:`non-git:path:${t}`};let r=_(n),e=r?G(r):null,o=e?T(e):null;return{canonicalRepoRoot:n,gitCommonDir:e,gitObjectDir:o,fingerprint:["git",`root:${n}`,`common:${e??""}`,`objects:${o??""}`].join("|")}}function X(t){try{let n=U();n.entries[t.storageRoot]={workspaceId:t.id,workspaceDirName:t.dirName,locationId:t.locationId,incarnationId:t.incarnationId,canonicalProjectRoot:t.canonicalProjectRoot,canonicalRepoRoot:t.canonicalRepoRoot,storageRoot:t.storageRoot,repoIdentity:t.repoIdentity??null,gitCommonDir:t.gitCommonDir??null,gitObjectDir:t.gitObjectDir??null,remote:t.remote??null,branch:t.branch??null,commit:t.commit??null,updatedAt:new Date().toISOString()},J(n)}catch{}}function V(t){let n=g(t),r=M(n),e=r??n,o=r,i=m(e),c=B(e,o),u=m(c.fingerprint),a=`ws-${m(`${i}:${u}`)}`,f=C(e,a);if(!o)return{id:a,dirName:f,locationId:i,incarnationId:u,canonicalProjectRoot:n,canonicalRepoRoot:e,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:null,remote:null,branch:null,commit:null};let d=_(o),I=d?H(d):null,w=I?W(I):null,S=d?z(d):{branch:null,commit:null};return{id:a,dirName:f,locationId:i,incarnationId:u,canonicalProjectRoot:n,canonicalRepoRoot:o,storageRoot:e,gitCommonDir:c.gitCommonDir,gitObjectDir:c.gitObjectDir,repoIdentity:w??`local:${m(e)}`,remote:I,branch:S.branch,commit:S.commit}}function K(t){let n=V(t);return X(n),s.join(D(),"workspaces",n.dirName)}function yt(t){return s.join(K(t),".pando-snapshots.db")}var h,x=k(()=>{"use strict";O();h=".pando-data"});x();import j from"fs";import A from"os";import b from"path";import{inspect as q}from"util";function v(){let t=process.env.PANDO_LOG_DIR||process.env.PANDO_WORKSPACE_DATA_DIR;if(t)return t;try{return D()}catch{let r=typeof A.homedir=="function"?A.homedir():process.env.HOME;if(r)return b.join(r,h)}let n=process.env.HOME||process.cwd();return b.join(n,h)}function Q(){return b.join(v(),"pando.log")}var y=t=>{if(t==null)return!1;let n=t.trim().toLowerCase();return n!=="0"&&n!=="false"&&n!=="off"&&n!=="no"},Y=y(process.env.PANDO_LOG_DISABLED),R=!Y&&(process.env.PANDO_DEBUG==null||y(process.env.PANDO_DEBUG)),Z=R&&(process.env.PANDO_INDEX_HOT_LOG==null||y(process.env.PANDO_INDEX_HOT_LOG)),tt=R&&(process.env.PANDO_INDEX_TIMING==null||y(process.env.PANDO_INDEX_TIMING)),nt=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),rt=new Set(["IndexTiming"]);function et(){try{j.mkdirSync(v(),{recursive:!0})}catch{}}function ot(t){if(t!==void 0)try{return typeof t=="string"?t:q(t,{depth:null,breakLength:1/0,maxArrayLength:1/0})}catch{try{return JSON.stringify(t)}catch{return String(t)}}}var it=!1;function Pt(){return R}function st(t){return R?rt.has(t)?tt:!(!Z&&nt.has(t)):!1}function Nt(t,n,r){if(!st(t))return;let e=new Date().toISOString(),o=ot(r),i=o?`[${e}] [${t}] ${n} :: ${o}`:`[${e}] [${t}] ${n}`;if(!it&&!process.env.PANDO_QUIET)try{process.stderr.write(i+`
|
|
3
|
+
`)}catch{}try{et(),j.appendFileSync(Q(),i+`
|
|
4
|
+
`,"utf8")}catch{}}import{createHash as ct}from"crypto";var at=/^-?\d+$/,lt=(1n<<63n)-1n;function ut(t){let n=ct("sha1").update(t).digest(),r=0n;for(let e=0;e<8;e+=1)r=r<<8n|BigInt(n[e]);return r<}function At(t){if(t==null)return null;if(typeof t=="bigint")return t;if(typeof t=="number"&&Number.isFinite(t))return BigInt(Math.trunc(t));if(typeof t=="string"){let n=t.trim();if(!n)return null;if(at.test(n))try{return BigInt(n)}catch{return null}return ut(n)}return null}export{K as a,yt as b,x as c,Pt as d,Nt as e,At as f};
|