@easbot/codebase 0.2.48 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkWNWTOLMW_cjs=require('./chunks/chunk-WNWTOLMW.cjs'),z=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),ie=require('fs'),Ee=require('better-sqlite3'),utils=require('@easbot/utils'),url=require('url'),Ce=require('fs/promises'),crypto=require('crypto'),Re=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var z__default=/*#__PURE__*/_interopDefault(z);var ie__default=/*#__PURE__*/_interopDefault(ie);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var Ce__default=/*#__PURE__*/_interopDefault(Ce);var Re__default=/*#__PURE__*/_interopDefault(Re);var ne={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var $=class y extends Error{constructor(t,r,n){super(t);chunkWNWTOLMW_cjs.a(this,"name","ParserError");chunkWNWTOLMW_cjs.a(this,"filePath");chunkWNWTOLMW_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},P=class y extends Error{constructor(t,r,n){super(t);chunkWNWTOLMW_cjs.a(this,"name","DatabaseError");chunkWNWTOLMW_cjs.a(this,"operation");chunkWNWTOLMW_cjs.a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},Q=class y extends Error{constructor(t,r,n){super(t);chunkWNWTOLMW_cjs.a(this,"name","FileSystemError");chunkWNWTOLMW_cjs.a(this,"filePath");chunkWNWTOLMW_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r){super(t);chunkWNWTOLMW_cjs.a(this,"name","SchemaError");chunkWNWTOLMW_cjs.a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},H=class y extends Error{constructor(t,r){super(t);chunkWNWTOLMW_cjs.a(this,"name","ConfigError");chunkWNWTOLMW_cjs.a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},V=class y extends Error{constructor(t,r,n){super(t);chunkWNWTOLMW_cjs.a(this,"name","IndexError");chunkWNWTOLMW_cjs.a(this,"filePath");chunkWNWTOLMW_cjs.a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},B=class y extends Error{constructor(t,r,n){super(t);chunkWNWTOLMW_cjs.a(this,"name","QueryError");chunkWNWTOLMW_cjs.a(this,"params");chunkWNWTOLMW_cjs.a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Y=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);chunkWNWTOLMW_cjs.a(this,"name","UnsupportedLanguageError");chunkWNWTOLMW_cjs.a(this,"extension");chunkWNWTOLMW_cjs.a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=utils.Filesystem.normalize,T=chunkWNWTOLMW_cjs.c.create({service:"codebase-database"}),q=class{constructor(e){chunkWNWTOLMW_cjs.a(this,"db");chunkWNWTOLMW_cjs.a(this,"dbPath");chunkWNWTOLMW_cjs.a(this,"closed",false);chunkWNWTOLMW_cjs.a(this,"ftsAvailable",false);this.dbPath=w(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=z__default.default.dirname(this.dbPath);ie__default.default.existsSync(e)||ie__default.default.mkdirSync(e,{recursive:true});let t=new Ee__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
1
+ 'use strict';var q=require('path'),xdgBasedir=require('xdg-basedir'),types=require('@easbot/types'),se=require('fs'),utils=require('@easbot/utils'),xe=require('better-sqlite3'),url=require('url'),Pe=require('fs/promises'),crypto=require('crypto'),Oe=require('fast-glob');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var q__default=/*#__PURE__*/_interopDefault(q);var se__default=/*#__PURE__*/_interopDefault(se);var xe__default=/*#__PURE__*/_interopDefault(xe);var Pe__default=/*#__PURE__*/_interopDefault(Pe);var Oe__default=/*#__PURE__*/_interopDefault(Oe);var fe=Object.defineProperty;var ye=(f,e,t)=>e in f?fe(f,e,{enumerable:true,configurable:true,writable:true,value:t}):f[e]=t;var u=(f,e,t)=>ye(f,typeof e!="symbol"?e+"":e,t);var Ee=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,S=Ee();var re={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var k=class f extends Error{constructor(t,r,n){super(t);u(this,"name","ParserError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},F=class f extends Error{constructor(t,r,n){super(t);u(this,"name","DatabaseError");u(this,"operation");u(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},X=class f extends Error{constructor(t,r,n){super(t);u(this,"name","FileSystemError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},Q=class f extends Error{constructor(t,r){super(t);u(this,"name","SchemaError");u(this,"missing");this.missing=r,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},z=class f extends Error{constructor(t,r){super(t);u(this,"name","ConfigError");u(this,"field");this.field=r,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},G=class f extends Error{constructor(t,r,n){super(t);u(this,"name","IndexError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},H=class f extends Error{constructor(t,r,n){super(t);u(this,"name","QueryError");u(this,"params");u(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},V=class f extends Error{constructor(t,r){super(`Unsupported language: ${t}`);u(this,"name","UnsupportedLanguageError");u(this,"extension");u(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,f.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=utils.Filesystem.normalize,T=utils.Log.create({service:"codebase-database"}),$=class{constructor(e){u(this,"db");u(this,"dbPath");u(this,"closed",false);u(this,"ftsAvailable",false);this.dbPath=w(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=q__default.default.dirname(this.dbPath);se__default.default.existsSync(e)||se__default.default.mkdirSync(e,{recursive:true});let t=new xe__default.default(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  id TEXT PRIMARY KEY,
4
4
  name TEXT NOT NULL,
@@ -55,7 +55,7 @@
55
55
  embedding BLOB NOT NULL,
56
56
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
57
57
  )
58
- `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new G("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:w(e.file_path)};this.db.prepare(`
58
+ `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new Q("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:w(e.file_path)};this.db.prepare(`
59
59
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
60
60
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
61
61
  `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(s=>({...s,file_path:w(s.file_path)})),r=this.db.prepare(`
@@ -67,7 +67,7 @@
67
67
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
68
68
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
69
69
  VALUES (?, ?, ?, ?, ?)
70
- `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${w(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new P("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
70
+ `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${w(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new F("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new F("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new F("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
71
71
  SELECT
72
72
  nodes_fts.id,
73
73
  nodes_fts.name,
@@ -103,6 +103,6 @@
103
103
  `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
104
104
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
105
105
  VALUES (?, ?, ?)
106
- `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new P("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ae=chunkWNWTOLMW_cjs.c.create({service:"codebase-parser"}),Ne={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function Se(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&chunkWNWTOLMW_cjs.b?z__default.default.dirname(url.fileURLToPath(chunkWNWTOLMW_cjs.b)):typeof __dirname<"u"?__dirname:process.cwd()}function Te(y,e){let t=Se(),r=t;for(let n=0;n<10;n++){let s=z__default.default.join(r,"node_modules",y,e);if(utils.Filesystem.stat(s)!==void 0)return s;let i=z__default.default.dirname(r);if(i===r)break;r=i;}return z__default.default.join(t,"node_modules",y,e)}var O=class{constructor(){chunkWNWTOLMW_cjs.a(this,"parsers",new Map);chunkWNWTOLMW_cjs.a(this,"initialized",false);chunkWNWTOLMW_cjs.a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],s=await Promise.allSettled(n.map(async i=>{try{let o=Ne[i];if(!o)return ae.warn("No WASM config for language",{lang:i}),null;let a=Te(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return ae.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=z__default.default.extname(e).toLowerCase();return ne[t]??null}parse(e,t){if(!this.initialized)throw new $("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new $(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new $("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new Y(z__default.default.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},L=null;async function oe(){return L||(L=new O,await L.initialize()),L}function de(){L&&(L.dispose(),L=null);}var Ie={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},ve=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),M=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
- `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(ve.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let s=this.findNameInChildren(n,r);if(s)return s}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Ie))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function ce(){return new M}var A=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let F=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:F,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function le(){return new A}var D=class{constructor(e,t,r){chunkWNWTOLMW_cjs.a(this,"db");chunkWNWTOLMW_cjs.a(this,"parserManager");chunkWNWTOLMW_cjs.a(this,"nodeExtractor");chunkWNWTOLMW_cjs.a(this,"edgeExtractor");chunkWNWTOLMW_cjs.a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new M,this.edgeExtractor=new A,this.config=r;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new V("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),F=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Re__default.default(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=utils.Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Ce__default.default.readFile(e,"utf-8")}catch(t){throw new Q("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function ge(y,e,t){return new D(y,e,t)}var ue=utils.Filesystem.normalize,N=chunkWNWTOLMW_cjs.c.create({service:"codebase.query"}),k=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){chunkWNWTOLMW_cjs.a(this,"db");chunkWNWTOLMW_cjs.a(this,"embedding");chunkWNWTOLMW_cjs.a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(ue(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(ue(i)))continue;let W=b.name.toLowerCase(),U=b.text.toLowerCase(),re=0;if(E.some(v=>W.includes(v))){let v=0;for(let j of E){let ee=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),X=W.match(ee);v+=X?X.length:0;}re=.8*Math.min(v/E.length,1);}let J=0;if(E.some(v=>U.includes(v))){let v=0;for(let X of E){let fe=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),se=U.match(fe);v+=se?se.length:0;}J=.5*Math.min(v/E.length,1);let j=U.indexOf(_),ee=j===-1?0:Math.max(0,1-j/U.length)*.2;J+=ee;}let Z=Math.max(re,J);Z>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:Z,source:"basic",hybridScore:Z});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let F=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&F.length>0){let h=F.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return F.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return F.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new B("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new B("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function pe(y){return new k(y)}var R=chunkWNWTOLMW_cjs.c.create({service:"codebase"}),ke={database:{path:types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:types.DEFAULT_SYNC_CONFIG},K=class{constructor(e={}){chunkWNWTOLMW_cjs.a(this,"config");chunkWNWTOLMW_cjs.a(this,"db");chunkWNWTOLMW_cjs.a(this,"parserManager");chunkWNWTOLMW_cjs.a(this,"indexer");chunkWNWTOLMW_cjs.a(this,"queryInterface");chunkWNWTOLMW_cjs.a(this,"initialized",false);chunkWNWTOLMW_cjs.a(this,"dirty",false);chunkWNWTOLMW_cjs.a(this,"syncTimer");chunkWNWTOLMW_cjs.a(this,"syncingInProgress",false);this.config={...ke,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new q(n),this.parserManager=new O;let s={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new D(this.db,this.parserManager,s),this.queryInterface=new k(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await chunkWNWTOLMW_cjs.c.init({logDir:this.config.logDir||z__default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>R.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,R.debug("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0}));}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){R.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{R.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{R.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return z__default.default.isAbsolute(e)?e:z__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return R.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return R.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),t}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,R.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function $e(y){let e=new K(y);return await e.initialize(),e}async function tr(y){let{Log:e}=await import('./chunks/log-7EJGLOQV.cjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}exports.CodeBase=K;exports.ConfigError=H;exports.DatabaseError=P;exports.DatabaseManager=q;exports.EdgeExtractor=A;exports.FILE_EXTENSION_MAP=ne;exports.FileSystemError=Q;exports.IndexError=V;exports.Indexer=D;exports.NodeExtractor=M;exports.ParserError=$;exports.ParserManager=O;exports.QueryError=B;exports.QueryInterface=k;exports.SchemaError=G;exports.UnsupportedLanguageError=Y;exports.createCodebase=$e;exports.createEdgeExtractor=le;exports.createIndexer=ge;exports.createNodeExtractor=ce;exports.createQueryInterface=pe;exports.getParserManager=oe;exports.initLog=tr;exports.resetParserManager=de;
106
+ `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new F("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ne=utils.Log.create({service:"codebase-parser"}),Ce={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function we(){return typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) })<"u"&&S?q__default.default.dirname(url.fileURLToPath(S)):typeof __dirname<"u"?__dirname:process.cwd()}function ve(f,e){let t=we(),r=t;for(let n=0;n<10;n++){let s=q__default.default.join(r,"node_modules",f,e);if(utils.Filesystem.stat(s)!==void 0)return s;let i=q__default.default.dirname(r);if(i===r)break;r=i;}return q__default.default.join(t,"node_modules",f,e)}var L=class{constructor(){u(this,"parsers",new Map);u(this,"initialized",false);u(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],s=await Promise.allSettled(n.map(async i=>{try{let o=Ce[i];if(!o)return ne.warn("No WASM config for language",{lang:i}),null;let a=ve(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return ne.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=q__default.default.extname(e).toLowerCase();return re[t]??null}parse(e,t){if(!this.initialized)throw new k("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new k(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new k("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new V(q__default.default.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},P=null;async function ie(){return P||(P=new L,await P.initialize()),P}function ae(){P&&(P.dispose(),P=null);}var Re={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Fe=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),O=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
+ `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(Fe.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let s=this.findNameInChildren(n,r);if(s)return s}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Re))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function oe(){return new O}var M=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let R=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:R,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function de(){return new M}var A=class{constructor(e,t,r){u(this,"db");u(this,"parserManager");u(this,"nodeExtractor");u(this,"edgeExtractor");u(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new O,this.edgeExtractor=new M,this.config=r;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new G("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),R=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let y=this.db.getFileHash(h.filePath);if(y)if(y!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Oe__default.default(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=utils.Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Pe__default.default.readFile(e,"utf-8")}catch(t){throw new X("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return crypto.createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function ce(f,e,t){return new A(f,e,t)}var le=utils.Filesystem.normalize,N=utils.Log.create({service:"codebase.query"}),D=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){u(this,"db");u(this,"embedding");u(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let y of h){let _=o?y.astType===o:true;N.debug("vector result",{astType:y.astType,name:y.name,match:_}),!(s&&y.language!==s)&&(o&&y.astType!==o||p.push({...y,source:"vector",vectorScore:y.score,hybridScore:y.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let y of h){let _=o?y.ast_type===o:true;if(N.debug("FTS result",{astType:y.ast_type,name:y.name,filterAstType:o,match:_}),s&&y.language!==s||i&&!y.file_path.includes(le(i))||o&&y.ast_type!==o)continue;let E=this.normalizeScore(y.score),I=p.find(b=>b.id===y.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:y.id,name:y.name,astType:y.ast_type,language:y.language,filePath:y.file_path,text:y.text,snippet:y.text.slice(0,200),startLine:y.start_line,startCol:y.start_col,endLine:y.end_line,endCol:y.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),y=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(y.has(b.id)||i&&!b.file_path.includes(le(i)))continue;let B=b.name.toLowerCase(),U=b.text.toLowerCase(),ee=0;if(E.some(C=>B.includes(C))){let C=0;for(let W of E){let Z=new RegExp(W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),j=B.match(Z);C+=j?j.length:0;}ee=.8*Math.min(C/E.length,1);}let K=0;if(E.some(C=>U.includes(C))){let C=0;for(let j of E){let me=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),te=U.match(me);C+=te?te.length:0;}K=.5*Math.min(C/E.length,1);let W=U.indexOf(_),Z=W===-1?0:Math.max(0,1-W/U.length)*.2;K+=Z;}let J=Math.max(ee,K);J>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:J,source:"basic",hybridScore:J});}I.sort((b,B)=>B.score-b.score),p.push(...I.slice(0,r));}catch{}let R=p.filter(h=>h.hybridScore>=n).sort((h,y)=>y.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&R.length>0){let h=R.map(E=>E.id),y=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of y)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return R.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return R.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new H("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new H("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function ge(f){return new D(f)}var v=utils.Log.create({service:"codebase"}),Ue={database:{path:types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:types.DEFAULT_SYNC_CONFIG},Y=class{constructor(e={}){u(this,"config");u(this,"db");u(this,"parserManager");u(this,"indexer");u(this,"queryInterface");u(this,"initialized",false);u(this,"dirty",false);u(this,"syncTimer");u(this,"syncingInProgress",false);this.config={...Ue,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||types.getDefaultDatabasePath(xdgBasedir.xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...types.DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...types.DEFAULT_SEARCH_CONFIG,...e.search},parser:{...types.DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...types.DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new $(n),this.parserManager=new L;let s={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new A(this.db,this.parserManager,s),this.queryInterface=new D(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>v.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,v.debug("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0}));}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){v.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{v.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{v.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new z("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new z("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return q__default.default.isAbsolute(e)?e:q__default.default.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return v.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return v.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),t}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,v.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function We(f){let e=new Y(f);return await e.initialize(),e}exports.CodeBase=Y;exports.ConfigError=z;exports.DatabaseError=F;exports.DatabaseManager=$;exports.EdgeExtractor=M;exports.FILE_EXTENSION_MAP=re;exports.FileSystemError=X;exports.IndexError=G;exports.Indexer=A;exports.NodeExtractor=O;exports.ParserError=k;exports.ParserManager=L;exports.QueryError=H;exports.QueryInterface=D;exports.SchemaError=Q;exports.UnsupportedLanguageError=V;exports.createCodebase=We;exports.createEdgeExtractor=de;exports.createIndexer=ce;exports.createNodeExtractor=oe;exports.createQueryInterface=ge;exports.getParserManager=ie;exports.resetParserManager=ae;
package/dist/index.d.cts CHANGED
@@ -572,12 +572,4 @@ declare class CodeBase implements ICodebase {
572
572
  }
573
573
  declare function createCodebase(config?: Partial<CodebaseConfig>): Promise<ICodebase>;
574
574
 
575
- declare function initLog(options: {
576
- print: boolean;
577
- logDir: string;
578
- logFile?: string;
579
- dev?: boolean;
580
- level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
581
- }): Promise<void>;
582
-
583
- export { type ASTNodeType, CodeBase, type CodeKnowledgeGraphConfig, type CodebaseConfig, ConfigError, DatabaseError, DatabaseManager, type Edge, EdgeExtractor, type EdgeQueryFilter, type EdgeWithNodes, type ExtractedEdge, type ExtractedNode, FILE_EXTENSION_MAP, type FileHashRecord, FileSystemError, type GraphStatus, type HealthCheckResult, type HybridSearchResult, type ICodebase, type IEdgeExtractor, type INodeExtractor, type IParser, IndexError, type IndexResult, Indexer, type IndexerConfig, type Language, type Node, NodeExtractor, type NodeQueryFilter, type NodeWithEdges, ParserError, ParserManager, type ProgressCallback, QueryError, QueryInterface, type RelationQueryOptions, type RelationType, SchemaError, type SearchOptions, type SearchResult, type SyncResult, UnsupportedLanguageError, createCodebase, createEdgeExtractor, createIndexer, createNodeExtractor, createQueryInterface, getParserManager, initLog, resetParserManager };
575
+ export { type ASTNodeType, CodeBase, type CodeKnowledgeGraphConfig, type CodebaseConfig, ConfigError, DatabaseError, DatabaseManager, type Edge, EdgeExtractor, type EdgeQueryFilter, type EdgeWithNodes, type ExtractedEdge, type ExtractedNode, FILE_EXTENSION_MAP, type FileHashRecord, FileSystemError, type GraphStatus, type HealthCheckResult, type HybridSearchResult, type ICodebase, type IEdgeExtractor, type INodeExtractor, type IParser, IndexError, type IndexResult, Indexer, type IndexerConfig, type Language, type Node, NodeExtractor, type NodeQueryFilter, type NodeWithEdges, ParserError, ParserManager, type ProgressCallback, QueryError, QueryInterface, type RelationQueryOptions, type RelationType, SchemaError, type SearchOptions, type SearchResult, type SyncResult, UnsupportedLanguageError, createCodebase, createEdgeExtractor, createIndexer, createNodeExtractor, createQueryInterface, getParserManager, resetParserManager };
package/dist/index.d.ts CHANGED
@@ -572,12 +572,4 @@ declare class CodeBase implements ICodebase {
572
572
  }
573
573
  declare function createCodebase(config?: Partial<CodebaseConfig>): Promise<ICodebase>;
574
574
 
575
- declare function initLog(options: {
576
- print: boolean;
577
- logDir: string;
578
- logFile?: string;
579
- dev?: boolean;
580
- level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
581
- }): Promise<void>;
582
-
583
- export { type ASTNodeType, CodeBase, type CodeKnowledgeGraphConfig, type CodebaseConfig, ConfigError, DatabaseError, DatabaseManager, type Edge, EdgeExtractor, type EdgeQueryFilter, type EdgeWithNodes, type ExtractedEdge, type ExtractedNode, FILE_EXTENSION_MAP, type FileHashRecord, FileSystemError, type GraphStatus, type HealthCheckResult, type HybridSearchResult, type ICodebase, type IEdgeExtractor, type INodeExtractor, type IParser, IndexError, type IndexResult, Indexer, type IndexerConfig, type Language, type Node, NodeExtractor, type NodeQueryFilter, type NodeWithEdges, ParserError, ParserManager, type ProgressCallback, QueryError, QueryInterface, type RelationQueryOptions, type RelationType, SchemaError, type SearchOptions, type SearchResult, type SyncResult, UnsupportedLanguageError, createCodebase, createEdgeExtractor, createIndexer, createNodeExtractor, createQueryInterface, getParserManager, initLog, resetParserManager };
575
+ export { type ASTNodeType, CodeBase, type CodeKnowledgeGraphConfig, type CodebaseConfig, ConfigError, DatabaseError, DatabaseManager, type Edge, EdgeExtractor, type EdgeQueryFilter, type EdgeWithNodes, type ExtractedEdge, type ExtractedNode, FILE_EXTENSION_MAP, type FileHashRecord, FileSystemError, type GraphStatus, type HealthCheckResult, type HybridSearchResult, type ICodebase, type IEdgeExtractor, type INodeExtractor, type IParser, IndexError, type IndexResult, Indexer, type IndexerConfig, type Language, type Node, NodeExtractor, type NodeQueryFilter, type NodeWithEdges, ParserError, ParserManager, type ProgressCallback, QueryError, QueryInterface, type RelationQueryOptions, type RelationType, SchemaError, type SearchOptions, type SearchResult, type SyncResult, UnsupportedLanguageError, createCodebase, createEdgeExtractor, createIndexer, createNodeExtractor, createQueryInterface, getParserManager, resetParserManager };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {c,a,b}from'./chunks/chunk-KWEU4PKH.mjs';import H from'path';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import ae from'fs';import be from'better-sqlite3';import {Filesystem}from'@easbot/utils';import {fileURLToPath}from'url';import we from'fs/promises';import {createHash}from'crypto';import Fe from'fast-glob';var ie={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var q=class y extends Error{constructor(t,r,n){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},L=class y extends Error{constructor(t,r,n){super(t);a(this,"name","DatabaseError");a(this,"operation");a(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},G=class y extends Error{constructor(t,r,n){super(t);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},V=class y extends Error{constructor(t,r){super(t);a(this,"name","SchemaError");a(this,"missing");this.missing=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},B=class y extends Error{constructor(t,r){super(t);a(this,"name","ConfigError");a(this,"field");this.field=r,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},Y=class y extends Error{constructor(t,r,n){super(t);a(this,"name","IndexError");a(this,"filePath");a(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},U=class y extends Error{constructor(t,r,n){super(t);a(this,"name","QueryError");a(this,"params");a(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,y.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},K=class y extends Error{constructor(t,r){super(`Unsupported language: ${t}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");a(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,y.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var R=Filesystem.normalize,T=c.create({service:"codebase-database"}),z=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=R(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=H.dirname(this.dbPath);ae.existsSync(e)||ae.mkdirSync(e,{recursive:true});let t=new be(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
1
+ import z from'path';import {fileURLToPath}from'url';import {xdgData}from'xdg-basedir';import {getDefaultDatabasePath,DEFAULT_SYNC_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_SEARCH_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import ne from'fs';import {Filesystem,Log}from'@easbot/utils';import Ie from'better-sqlite3';import Ae from'fs/promises';import {createHash}from'crypto';import ke from'fast-glob';var ye=Object.defineProperty;var Ee=(f,e,t)=>e in f?ye(f,e,{enumerable:true,configurable:true,writable:true,value:t}):f[e]=t;var u=(f,e,t)=>Ee(f,typeof e!="symbol"?e+"":e,t);var xe=()=>fileURLToPath(import.meta.url),Ne=()=>z.dirname(xe()),S=Ne();var se={".ts":"ts",".tsx":"tsx",".js":"js",".jsx":"js",".mjs":"js",".cjs":"js",".py":"py",".rs":"rs",".go":"go",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".java":"java",".scala":"scala",".rb":"ruby",".php":"php",".zig":"zig"};var $=class f extends Error{constructor(t,r,n){super(t);u(this,"name","ParserError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},P=class f extends Error{constructor(t,r,n){super(t);u(this,"name","DatabaseError");u(this,"operation");u(this,"cause");this.operation=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},Q=class f extends Error{constructor(t,r,n){super(t);u(this,"name","FileSystemError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},G=class f extends Error{constructor(t,r){super(t);u(this,"name","SchemaError");u(this,"missing");this.missing=r,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},H=class f extends Error{constructor(t,r){super(t);u(this,"name","ConfigError");u(this,"field");this.field=r,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},V=class f extends Error{constructor(t,r,n){super(t);u(this,"name","IndexError");u(this,"filePath");u(this,"cause");this.filePath=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},B=class f extends Error{constructor(t,r,n){super(t);u(this,"name","QueryError");u(this,"params");u(this,"cause");this.params=r,this.cause=n,Object.setPrototypeOf(this,f.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",r=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${r}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},Y=class f extends Error{constructor(t,r){super(`Unsupported language: ${t}`);u(this,"name","UnsupportedLanguageError");u(this,"extension");u(this,"filePath");this.extension=t,this.filePath=r,Object.setPrototypeOf(this,f.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var w=Filesystem.normalize,T=Log.create({service:"codebase-database"}),q=class{constructor(e){u(this,"db");u(this,"dbPath");u(this,"closed",false);u(this,"ftsAvailable",false);this.dbPath=w(e),this.db=this.openDatabase(),this.ensureSchema(),this.ftsAvailable=this.checkFtsAvailability();}openDatabase(){let e=z.dirname(this.dbPath);ne.existsSync(e)||ne.mkdirSync(e,{recursive:true});let t=new Ie(this.dbPath);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 5000"),t.pragma("cache_size = -64000"),t.pragma("foreign_keys = ON"),t}ensureSchema(){let e=this.db;try{e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS nodes (
3
3
  id TEXT PRIMARY KEY,
4
4
  name TEXT NOT NULL,
@@ -55,10 +55,10 @@ import {c,a,b}from'./chunks/chunk-KWEU4PKH.mjs';import H from'path';import {xdgD
55
55
  embedding BLOB NOT NULL,
56
56
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
57
57
  )
58
- `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new V("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:R(e.file_path)};this.db.prepare(`
58
+ `);let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]],r=e.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[n,s]of t)r.run(n,s);}catch(t){throw new G("Failed to create database schema",t instanceof Error?[t.message]:[String(t)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:w(e.file_path)};this.db.prepare(`
59
59
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
60
60
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
61
- `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(s=>({...s,file_path:R(s.file_path)})),r=this.db.prepare(`
61
+ `).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(s=>({...s,file_path:w(s.file_path)})),r=this.db.prepare(`
62
62
  INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
63
63
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
64
  `);this.db.transaction(s=>{for(let i of s)r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(s);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let s of e)try{let i=r.get(s.id);i&&t.run(i.rowid),n.run(s.id,s.name,s.ast_type,s.language,s.file_path,s.text);}catch(i){T.warn("FTS update failed for node",{nodeId:s.id,error:String(i)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){T.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(i=>{for(let o of i)try{let a=r.get(o.id);a&&t.run(a.rowid),n.run(o.id,o.name,o.ast_type,o.language,o.file_path,o.text);}catch(a){T.warn("FTS update failed for node",{nodeId:o.id,error:String(a)});}})(e);}insertEdge(e){this.db.prepare(`
@@ -67,7 +67,7 @@ import {c,a,b}from'./chunks/chunk-KWEU4PKH.mjs';import H from'path';import {xdgD
67
67
  `).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
68
68
  INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
69
69
  VALUES (?, ?, ?, ?, ?)
70
- `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${R(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new L("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new L("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new L("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
70
+ `);this.db.transaction(n=>{for(let s of n)t.run(s.id,s.source,s.target,s.relation,s.created_at);})(e);}queryNodes(e){let t=[],r=[];e.filePath&&(t.push("file_path LIKE ?"),r.push(`%${w(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),r.push(e.astType)),e.name&&(t.push("name LIKE ?"),r.push(`%${e.name}%`)),e.language&&(t.push("language = ?"),r.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query nodes","queryNodes",s instanceof Error?s:new Error(String(s)))}}queryEdges(e){let t=[],r=[];e.source&&(t.push("source = ?"),r.push(e.source)),e.target&&(t.push("target = ?"),r.push(e.target)),e.relation&&(t.push("relation = ?"),r.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",r.push(e.limit)),e.offset&&(n+=" OFFSET ?",r.push(e.offset));try{return this.db.prepare(n).all(...r)}catch(s){throw new P("Failed to query edges","queryEdges",s instanceof Error?s:new Error(String(s)))}}queryAll(e,t){try{let r=this.db.prepare(e);return t?r.all(...t):r.all()}catch(r){throw new P("Failed to execute query","queryAll",r instanceof Error?r:new Error(String(r)))}}searchNodesFts(e,t=20){if(T.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return T.debug("searchNodesFts skip - FTS not available"),[];try{let r=e.split(/\s+/).map(o=>`${o}*`).join(" ");T.debug("searchNodesFts query",{ftsQuery:r});let i=this.db.prepare(`
71
71
  SELECT
72
72
  nodes_fts.id,
73
73
  nodes_fts.name,
@@ -85,14 +85,14 @@ import {c,a,b}from'./chunks/chunk-KWEU4PKH.mjs';import H from'path';import {xdgD
85
85
  WHERE nodes_fts.text MATCH ?
86
86
  ORDER BY score DESC
87
87
  LIMIT ?
88
- `).all(r,t);return T.debug("searchNodesFts done",{resultCount:i.length}),i}catch(r){return T.warn("searchNodesFts failed",{error:String(r)}),[]}}deleteNodesByFile(e){let t=R(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let s of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(s.rowid);}catch(n){T.warn("FTS delete failed for file",{filePath:t,error:String(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=R(e);return this.db.prepare(`
88
+ `).all(r,t);return T.debug("searchNodesFts done",{resultCount:i.length}),i}catch(r){return T.warn("searchNodesFts failed",{error:String(r)}),[]}}deleteNodesByFile(e){let t=w(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let s of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(s.rowid);}catch(n){T.warn("FTS delete failed for file",{filePath:t,error:String(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=w(e);return this.db.prepare(`
89
89
  DELETE FROM edges
90
90
  WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
91
91
  OR target IN (SELECT id FROM nodes WHERE file_path = ?)
92
- `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(R(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
92
+ `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(w(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
93
93
  INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
94
94
  VALUES (?, ?, ?)
95
- `).run(R(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(R(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),s={};for(let i of n)s[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:s}}setLastSync(){this.db.prepare(`
95
+ `).run(w(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(w(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),r=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),s={};for(let i of n)s[i.key]=i.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:r?.c??0,dbPath:this.dbPath,meta:s}}setLastSync(){this.db.prepare(`
96
96
  INSERT OR REPLACE INTO meta (key, value)
97
97
  VALUES ('lastSync', ?)
98
98
  `).run(new Date().toISOString());}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache"),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let r=this.db.prepare(`
@@ -103,6 +103,6 @@ import {c,a,b}from'./chunks/chunk-KWEU4PKH.mjs';import H from'path';import {xdgD
103
103
  `).run(e,t);}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
104
104
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
105
105
  VALUES (?, ?, ?)
106
- `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new L("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var oe=c.create({service:"codebase-parser"}),Se={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function Te(){return typeof import.meta<"u"&&import.meta.url?H.dirname(fileURLToPath(import.meta.url)):typeof b<"u"?b:process.cwd()}function Ie(y,e){let t=Te(),r=t;for(let n=0;n<10;n++){let s=H.join(r,"node_modules",y,e);if(Filesystem.stat(s)!==void 0)return s;let i=H.dirname(r);if(i===r)break;r=i;}return H.join(t,"node_modules",y,e)}var M=class{constructor(){a(this,"parsers",new Map);a(this,"initialized",false);a(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],s=await Promise.allSettled(n.map(async i=>{try{let o=Se[i];if(!o)return oe.warn("No WASM config for language",{lang:i}),null;let a=Ie(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return oe.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=H.extname(e).toLowerCase();return ie[t]??null}parse(e,t){if(!this.initialized)throw new q("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new q(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new q("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new K(H.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},O=null;async function de(){return O||(O=new M,await O.initialize()),O}function ce(){O&&(O.dispose(),O=null);}var ve={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Ce=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),A=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
- `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(Ce.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let s=this.findNameInChildren(n,r);if(s)return s}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(ve))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
- `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function le(){return new A}var D=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let P=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:P,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function ge(){return new D}var k=class{constructor(e,t,r){a(this,"db");a(this,"parserManager");a(this,"nodeExtractor");a(this,"edgeExtractor");a(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new A,this.edgeExtractor=new D,this.config=r;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new Y("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),P=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let f=this.db.getFileHash(h.filePath);if(f)if(f!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await Fe(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await we.readFile(e,"utf-8")}catch(t){throw new G("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function ue(y,e,t){return new k(y,e,t)}var pe=Filesystem.normalize,N=c.create({service:"codebase.query"}),$=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){a(this,"db");a(this,"embedding");a(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let f of h){let _=o?f.astType===o:true;N.debug("vector result",{astType:f.astType,name:f.name,match:_}),!(s&&f.language!==s)&&(o&&f.astType!==o||p.push({...f,source:"vector",vectorScore:f.score,hybridScore:f.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let f of h){let _=o?f.ast_type===o:true;if(N.debug("FTS result",{astType:f.ast_type,name:f.name,filterAstType:o,match:_}),s&&f.language!==s||i&&!f.file_path.includes(pe(i))||o&&f.ast_type!==o)continue;let E=this.normalizeScore(f.score),I=p.find(b=>b.id===f.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:f.id,name:f.name,astType:f.ast_type,language:f.language,filePath:f.file_path,text:f.text,snippet:f.text.slice(0,200),startLine:f.start_line,startCol:f.start_col,endLine:f.end_line,endCol:f.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),f=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(f.has(b.id)||i&&!b.file_path.includes(pe(i)))continue;let W=b.name.toLowerCase(),j=b.text.toLowerCase(),se=0;if(E.some(v=>W.includes(v))){let v=0;for(let X of E){let te=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),Q=W.match(te);v+=Q?Q.length:0;}se=.8*Math.min(v/E.length,1);}let Z=0;if(E.some(v=>j.includes(v))){let v=0;for(let Q of E){let ye=new RegExp(Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),ne=j.match(ye);v+=ne?ne.length:0;}Z=.5*Math.min(v/E.length,1);let X=j.indexOf(_),te=X===-1?0:Math.max(0,1-X/j.length)*.2;Z+=te;}let ee=Math.max(se,Z);ee>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:ee,source:"basic",hybridScore:ee});}I.sort((b,W)=>W.score-b.score),p.push(...I.slice(0,r));}catch{}let P=p.filter(h=>h.hybridScore>=n).sort((h,f)=>f.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&P.length>0){let h=P.map(E=>E.id),f=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of f)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return P.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return P.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new U("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new U("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function he(y){return new $(y)}var F=c.create({service:"codebase"}),$e={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},J=class{constructor(e={}){a(this,"config");a(this,"db");a(this,"parserManager");a(this,"indexer");a(this,"queryInterface");a(this,"initialized",false);a(this,"dirty",false);a(this,"syncTimer");a(this,"syncingInProgress",false);this.config={...$e,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new z(n),this.parserManager=new M;let s={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new k(this.db,this.parserManager,s),this.queryInterface=new $(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(await c.init({logDir:this.config.logDir||H.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>F.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,F.debug("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0}));}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){F.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{F.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{F.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new B("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new B("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return H.isAbsolute(e)?e:H.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return F.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return F.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),t}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,F.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function qe(y){let e=new J(y);return await e.initialize(),e}async function rr(y){let{Log:e}=await import('./chunks/log-PXYUHFLU.mjs'),t=false;await e.init({logDir:y.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:y.print??false,dev:y.dev??t,level:y.level??("INFO")});}export{J as CodeBase,B as ConfigError,L as DatabaseError,z as DatabaseManager,D as EdgeExtractor,ie as FILE_EXTENSION_MAP,G as FileSystemError,Y as IndexError,k as Indexer,A as NodeExtractor,q as ParserError,M as ParserManager,U as QueryError,$ as QueryInterface,V as SchemaError,K as UnsupportedLanguageError,qe as createCodebase,ge as createEdgeExtractor,ue as createIndexer,le as createNodeExtractor,he as createQueryInterface,de as getParserManager,rr as initLog,ce as resetParserManager};
106
+ `);this.db.transaction(n=>{for(let s of n)try{t.run(s.nodeId,s.embeddingText,s.embedding);}catch(i){T.warn("Failed to store embedding for node",{nodeId:s.nodeId,error:String(i)});}})(e);}initialize(){if(this.closed)throw new P("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){T.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var ie=Log.create({service:"codebase-parser"}),Fe={js:{package:"tree-sitter-javascript",wasmFile:"tree-sitter-javascript.wasm"},ts:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-typescript.wasm"},tsx:{package:"tree-sitter-typescript",wasmFile:"tree-sitter-tsx.wasm"},py:{package:"tree-sitter-python",wasmFile:"tree-sitter-python.wasm"},rs:{package:"tree-sitter-rust",wasmFile:"tree-sitter-rust.wasm"},go:{package:"tree-sitter-go",wasmFile:"tree-sitter-go.wasm"},c:{package:"tree-sitter-c",wasmFile:"tree-sitter-c.wasm"},cpp:{package:"tree-sitter-cpp",wasmFile:"tree-sitter-cpp.wasm"},csharp:{package:"tree-sitter-c-sharp",wasmFile:"tree-sitter-c_sharp.wasm"},java:{package:"tree-sitter-java",wasmFile:"tree-sitter-java.wasm"},ruby:{package:"tree-sitter-ruby",wasmFile:"tree-sitter-ruby.wasm"},php:{package:"tree-sitter-php",wasmFile:"tree-sitter-php.wasm"},scala:{package:"tree-sitter-scala",wasmFile:"tree-sitter-scala.wasm"}};function Pe(){return typeof import.meta<"u"&&import.meta.url?z.dirname(fileURLToPath(import.meta.url)):typeof S<"u"?S:process.cwd()}function Le(f,e){let t=Pe(),r=t;for(let n=0;n<10;n++){let s=z.join(r,"node_modules",f,e);if(Filesystem.stat(s)!==void 0)return s;let i=z.dirname(r);if(i===r)break;r=i;}return z.join(t,"node_modules",f,e)}var O=class{constructor(){u(this,"parsers",new Map);u(this,"initialized",false);u(this,"initPromise",null);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initPromise=null;}}async doInitialize(){let e=await import('web-tree-sitter'),t=e.default?.default||e.default?.Parser||e.default||e.Parser,r=t?.Language||e.Language||e.default?.Language;if(typeof t?.init=="function"&&await t.init(),typeof t!="function")throw new Error(`web-tree-sitter did not export a Parser constructor. Got: ${typeof t}`);if(typeof r!="function")throw new Error(`web-tree-sitter did not export a Language class. Got: ${typeof r}`);let n=["ts","tsx","js","py","rs","go","c","cpp","csharp","java","ruby","php","scala"],s=await Promise.allSettled(n.map(async i=>{try{let o=Fe[i];if(!o)return ie.warn("No WASM config for language",{lang:i}),null;let a=Le(o.package,o.wasmFile),d=await r.load(a),g=new t;return g.setLanguage(d),{lang:i,parser:g,language:d}}catch(o){return ie.warn("Failed to load parser",{lang:i,error:String(o)}),null}}));for(let i of s)if(i.status==="fulfilled"&&i.value){let{lang:o,parser:a,language:d}=i.value;this.parsers.set(o,{parser:a,language:d});}this.initialized=true;}getParser(e){return this.parsers.get(e)?.parser??null}getLanguage(e){return this.parsers.get(e)?.language??null}detectLanguage(e){let t=z.extname(e).toLowerCase();return se[t]??null}parse(e,t){if(!this.initialized)throw new $("Parser not initialized","");let r=this.parsers.get(t);if(!r)throw new $(`No parser available for language: ${t}`,"");try{return r.parser.parse(e)}catch(n){throw new $("Failed to parse code","",n instanceof Error?n:new Error(String(n)))}}parseFile(e,t){let r=this.detectLanguage(e);if(!r)throw new Y(z.extname(e),e);return this.parse(t,r)}isLanguageSupported(e){return this.parsers.has(e)}getSupportedLanguages(){return Array.from(this.parsers.keys())}isInitialized(){return this.initialized}getStatus(){let e={},t=["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"];for(let r of t)e[r]=this.parsers.has(r);return e}dispose(){this.parsers.clear(),this.initialized=false;}},L=null;async function ae(){return L||(L=new O,await L.initialize()),L}function oe(){L&&(L.dispose(),L=null);}var Oe={class_declaration:["class_item"],function_definition:["function_item"],variable_declaration:["lexical_declaration","variable_declarator","assignment"],import_declaration:["import_statement","import_clause","use_declaration","include_directive"],enum_declaration:["enum_item"],struct_declaration:["struct_item","struct_definition"],module_declaration:["namespace_declaration"],constant_declaration:["const_item"]},Me=new Set(["class_declaration","function_declaration","method_definition","interface_declaration","type_alias_declaration","enum_declaration","variable_declaration","lexical_declaration","import_declaration","import_statement","export_statement","function_expression","arrow_function","class_definition","function_definition","import_statement","import_from_statement","struct_item","enum_item","function_item","impl_item","trait_item","use_declaration","mod_item","const_item","type_declaration","function_declaration","method_declaration","import_declaration","function_definition","class_specifier","struct_specifier","enum_specifier","preproc_include","class_declaration","interface_declaration","enum_declaration","method_declaration","import_declaration","class_declaration","interface_declaration","struct_declaration","enum_declaration","method_declaration","using_directive","class","module","method","method_definition","class_declaration","function_definition","method_declaration","use_declaration","class_definition","trait_definition","object_definition","function_definition","function_declaration","struct_declaration","enum_declaration"]),M=class{extractNodes(e,t,r,n){let s=[],i=t.split(`
107
+ `);return this.walkTree(e.rootNode,s,r,n,i),s}walkTree(e,t,r,n,s,i){if(Me.has(e.type)){let o=this.extractNode(e,r,n,s,i);o&&(t.push(o),i=o.name?this.generateNodeId(o):i);}for(let o=0;o<e.childCount;o++){let a=e.children[o];a&&this.walkTree(a,t,r,n,s,i);}}extractNode(e,t,r,n,s){let i=this.getNodeName(e);if(!i)return null;let o=e.startPosition,a=e.endPosition,d=this.getNodeText(e,n);return {name:i,ast_type:this.normalizeAstType(e.type),language:t,file_path:r,start_line:o.row,start_col:o.column,end_line:a.row,end_col:a.column,text:d,parent_id:s}}getNodeName(e){switch(e.type){case "class_declaration":case "class_definition":case "interface_declaration":case "trait_item":case "struct_item":case "enum_item":case "enum_declaration":case "type_alias_declaration":return this.findNameInChildren(e,["name","identifier","type_identifier","type_name"]);case "function_declaration":case "function_definition":case "function_item":case "method_definition":case "method_declaration":return this.findNameInChildren(e,["name","identifier","property_identifier","function_name"]);case "variable_declaration":case "lexical_declaration":case "variable_declarator":return this.findNameInChildren(e,["name","identifier","variable_name"])??this.findNameInGrandchildren(e,["variable_declarator"],["name","identifier"]);case "import_declaration":case "import_statement":case "use_declaration":return this.extractImportName(e);case "const_item":case "constant_declaration":return this.findNameInChildren(e,["name","identifier"]);default:return this.findNameInChildren(e,["name","identifier"])}}findNameInChildren(e,t){for(let r of t){let n=e.childForFieldName?.(r);if(n?.text)return n.text}for(let r of e.children)if(r.type==="identifier"||r.type==="type_identifier"||r.type==="property_identifier"||r.type==="field_identifier"||r.type==="name")return r.text;return null}findNameInGrandchildren(e,t,r){for(let n of e.children)if(t.includes(n.type)){let s=this.findNameInChildren(n,r);if(s)return s}return null}extractImportName(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"||t.type==="module_name"||t.type==="identifier"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return e.text.slice(0,100)}normalizeAstType(e){for(let[t,r]of Object.entries(Oe))if(r.includes(e))return t;return e}getNodeText(e,t){let r=e.startPosition.row,n=e.endPosition.row;return r===n?t[r]?.trim()??"":t.slice(r,n+1).join(`
108
+ `)}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}};function de(){return new M}var A=class{extractEdges(e,t,r,n){let s=[],i=new Map;for(let o of t){let a=this.generateNodeId(o);i.set(a,o);}return this.extractContainsEdges(t,s),this.extractCallEdges(e.rootNode,t,s,r,n,i),this.extractInheritanceEdges(e.rootNode,t,s,r,n,i),this.extractImportEdges(e.rootNode,t,s,r,n),this.extractTypeReferences(e.rootNode,t,s,r,n,i),this.extractParameterEdges(e.rootNode,t,s,r,n,i),this.extractDefinesEdges(t,s,r,n,i),this.extractAnnotationEdges(e.rootNode,t,s,r,n),s}extractContainsEdges(e,t){for(let r of e)r.parent_id&&t.push({source:r.parent_id,target:this.generateNodeId(r),relation:"CONTAINS"});}extractCallEdges(e,t,r,n,s,i){let o=["call_expression","call","method_call_expression","function_call"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findEnclosingFunction(a,t),g=this.extractCalleeName(a);if(d&&g){let l=`${n}:${s}:function_declaration:${g}`;r.push({source:d.id,target:l,relation:"CALLS"});}}});}extractInheritanceEdges(e,t,r,n,s,i){let o=["class_declaration","class_definition","class_specifier"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=`${n}:${s}:class_declaration:${d}`,l=this.findDescendantByType(a,["class_heritage","extends_clause","superclass"]);if(l){let p=this.findChildByType(l,["extends_clause","superclass"])??l,x=this.extractIdentifier(p);if(x&&x!==d){let F=`${n}:${s}:class_declaration:${x}`;r.push({source:g,target:F,relation:"INHERITS_FROM"});}}let c=this.findDescendantByType(a,["implements_clause","interface_list","implements"]);if(c){let m=this.extractIdentifiers(c);for(let p of m){let x=`${n}:${s}:interface_declaration:${p}`;r.push({source:g,target:x,relation:"IMPLEMENTS"});}}}});}extractImportEdges(e,t,r,n,s){let i=["import_declaration","import_statement","use_declaration","include_directive"];this.walkTree(e,o=>{if(i.includes(o.type)){let a=this.extractImportPath(o);if(a){let d=`${n}:${s}:module:file`;r.push({source:d,target:a,relation:"IMPORTS"});}}});}walkTree(e,t){t(e);for(let r of e.children)this.walkTree(r,t);}findEnclosingFunction(e,t){let r=e;for(;r;){if(["function_declaration","function_definition","method_definition","method_declaration","function_item"].includes(r.type)){let s=this.findNameInChildren(r);if(s){let i=t.find(l=>l.name===s);if(i)return {id:this.generateNodeId(i),name:s};r.startPosition;let a=t[0],d=a?.language??"ts",g=a?.file_path??"";return {id:`${d}:${g}:function_declaration:${s}`,name:s}}}r=r.parent;}return null}extractCalleeName(e){let t=e.firstChild;if(!t)return null;if(t.type==="member_expression"||t.type==="field_access"){let r=t.childForFieldName?.("property");if(r)return r.text;let n=t.children[t.children.length-1];if(n)return n.text}return t.type==="identifier"||t.type==="property_identifier"?t.text:null}findNameInChildren(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier"||t.type==="property_identifier")return t.text;return null}findChildByType(e,t){for(let r of e.children)if(t.includes(r.type))return r;return null}findDescendantByType(e,t){for(let r of e.children){if(t.includes(r.type))return r;if(!["class_declaration","class_definition"].includes(r.type)){let s=this.findDescendantByType(r,t);if(s)return s}}return null}extractIdentifier(e){for(let t of e.children)if(t.type==="identifier"||t.type==="type_identifier")return t.text;return null}extractIdentifiers(e){let t=[];for(let r of e.children)(r.type==="identifier"||r.type==="type_identifier")&&t.push(r.text);return t}extractImportPath(e){for(let t of e.children)if(t.type==="string"||t.type==="string_literal"){let r=t.text;return (r.startsWith('"')||r.startsWith("'"))&&(r=r.slice(1,-1)),r}return null}generateNodeId(e){return `${e.language}:${e.file_path}:${e.ast_type}:${e.name}`}extractTypeReferences(e,t,r,n,s,i){let a=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","lexical_declaration","parameter","typed_param","identifier"];this.walkTree(e,d=>{if(a.includes(d.type)){let l=this.findNameInChildren(d);if(!l)return;let c=this.findChildByType(d,["return_type","type_annotation","type"]);if(c){let p=this.extractTypeName(c);if(p&&p!=="void"&&p!=="any"&&p!=="null"){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}let m=this.findDescendantByType(d,["type_parameter","generic_type"]);if(m){let p=this.extractTypeName(m);if(p){let x=this.resolveTypeNodeId(p,n,s);x&&r.push({source:this.generateNodeIdFromName(l,d.type,n,s),target:x,relation:"TYPE_REFERENCES"});}}}if(["formal_parameters","parameter","typed_param","argument"].includes(d.type)){for(let l of d.children)if(l.type==="type_annotation"||l.type==="annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findEnclosingFunction(d,t);p&&r.push({source:p.id,target:m,relation:"TYPE_REFERENCES"});}}}}if(d.type==="variable_declaration"||d.type==="lexical_declaration"){for(let l of d.children)if(l.type==="type_annotation"){let c=this.extractTypeName(l);if(c&&c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="any"){let m=this.resolveTypeNodeId(c,n,s);if(m){let p=this.findNameInChildren(d);p&&r.push({source:this.generateNodeIdFromName(p,"variable_declaration",n,s),target:m,relation:"TYPE_REFERENCES"});}}}}});}extractParameterEdges(e,t,r,n,s,i){let o=["function_declaration","function_definition","method_declaration","method_definition"];this.walkTree(e,a=>{if(o.includes(a.type)){let d=this.findNameInChildren(a);if(!d)return;let g=this.generateNodeIdFromName(d,a.type,n,s),l=this.findChildrenByType(a,["formal_parameters","parameters","parameter_list","parameter"]);for(let c of l)for(let m of c.children)if(m.type==="identifier"||m.type==="parameter"||m.type==="typed_param"){let p=this.findNameInChildren(m);if(p&&p!=="self"&&p!=="this"){let x=`${n}:${s}:parameter:${d}:${p}`;r.push({source:g,target:x,relation:"HAS_PARAMETER"});}}}});}extractDefinesEdges(e,t,r,n,s){let i=["class_declaration","class_definition","interface_declaration","module_declaration","namespace_declaration","struct_declaration"],o=["function_declaration","function_definition","method_declaration","method_definition","variable_declaration","property_declaration"];for(let a of e)if(i.includes(a.ast_type)){let d=this.generateNodeId(a);for(let g of e)if(g.file_path===a.file_path&&o.includes(g.ast_type)&&g.start_line>=a.start_line&&g.end_line<=a.end_line){let l=this.generateNodeId(g);d!==l&&t.push({source:d,target:l,relation:"DEFINES"});}}}extractAnnotationEdges(e,t,r,n,s){let i=["decorator","attribute","annotation","decorated_expression","attribute_decorator"],o=["function_declaration","function_definition","method_declaration","method_definition","class_declaration","class_definition"];this.walkTree(e,a=>{if(i.includes(a.type)){let d=this.extractTypeName(a)||this.findNameInChildren(a);if(!d)return;let g=a.parent;for(;g;){if(o.includes(g.type)){let l=this.findNameInChildren(g);if(l){let c=this.generateNodeIdFromName(l,g.type,n,s),m=`${n}:${s}:annotation:${d}`;r.push({source:m,target:c,relation:"ANNOTATES"});}break}g=g.parent;}}});}extractTypeName(e){for(let t of e.children)if(t.type==="type_identifier"||t.type==="identifier")return t.text;for(let t of e.children)if(t.type==="predefined_type")return t.text;return null}resolveTypeNodeId(e,t,r){let n=["interface_declaration","type_alias_declaration","class_declaration","enum_declaration","struct_declaration"];for(let s of n)return `${t}:${r}:${s}:${e}`;return null}generateNodeIdFromName(e,t,r,n){return `${r}:${n}:${t}:${e}`}findChildrenByType(e,t){let r=[];for(let n of e.children)t.includes(n.type)&&r.push(n);return r}};function ce(){return new A}var D=class{constructor(e,t,r){u(this,"db");u(this,"parserManager");u(this,"nodeExtractor");u(this,"edgeExtractor");u(this,"config");this.db=e,this.parserManager=t,this.nodeExtractor=new M,this.edgeExtractor=new A,this.config=r;}generateNodeEmbeddingText(e){return [e.name,e.ast_type,e.language,e.text].join(" | ")}async embedText(e){if(!this.config.embedding)return null;try{let t=this.computeHash(e),r=this.db.getCachedEmbedding?.(t);if(r)return new Float32Array(r.buffer,r.byteOffset,r.length/4);let s=(await this.config.embedding.doEmbed({values:[e]})).embeddings[0];if(s){let i=new Float32Array(s);return this.db.cacheEmbedding?.(t,i),i}return null}catch{return null}}async indexFile(e,t){let r=Date.now(),n=[],s=0,i=0;try{let o=this.parserManager.detectLanguage(e);if(!o)throw new V("Unsupported file type",e);t?.({currentFile:e,processed:0,total:1,stage:"parsing"});let a=await this.readFile(e),d=this.computeHash(a);if(this.config.incremental&&this.db.getFileHash(e)===d)return {success:!0,filesProcessed:1,nodesCreated:0,edgesCreated:0,errors:[],duration:Date.now()-r};this.db.deleteEdgesByFile(e),this.db.deleteNodesByFile(e),t?.({currentFile:e,processed:0,total:1,stage:"extracting"});let g=this.parserManager.parse(a,o),l=this.nodeExtractor.extractNodes(g,a,o,e);s=l.length;let c=this.edgeExtractor.extractEdges(g,l,o,e);t?.({currentFile:e,processed:0,total:1,stage:"storing"}),this.storeNodes(l);let m=this.getValidEdgeCount(c,l);this.storeEdges(c,l),i=m,this.config.embedding&&l.length>0&&(t?.({currentFile:e,processed:0,total:1,stage:"embedding"}),await this.embedNodes(l)),this.db.setFileHash(e,d),g.delete();}catch(o){let a=o instanceof Error?o.message:String(o);n.push({filePath:e,error:a});}return {success:n.length===0,filesProcessed:1,nodesCreated:s,edgesCreated:i,errors:n,duration:Date.now()-r}}async indexDirectory(e,t){let r=Date.now(),n=e??this.config.workspaceDir,s=[],i=0,o=0,a=0;try{let d=await this.scanFiles(n),g=d.length;for(let l=0;l<d.length;l+=this.config.batchSize){let c=d.slice(l,l+this.config.batchSize);for(let m of c){let p=await this.indexFile(m.filePath,t);i++,o+=p.nodesCreated,a+=p.edgesCreated,!p.success&&p.errors.length>0&&s.push(...p.errors);}}}catch(d){let g=d instanceof Error?d.message:String(d);s.push({filePath:n,error:g});}return this.db.setLastSync(),{success:s.length===0,filesProcessed:i,nodesCreated:o,edgesCreated:a,errors:s,duration:Date.now()-r}}async sync(e){let t=Date.now(),r=[],n=0,s=0,i=0,o=0,a=0,d=0;try{let m=await this.scanFiles(this.config.workspaceDir),p=new Set(m.map(h=>h.filePath)),x=this.db.getAllFileHashes(),F=new Set(x.map(h=>h.file_path));for(let h of x)p.has(h.file_path)||(this.db.deleteNodesByFile(h.file_path),this.db.deleteEdgesByFile(h.file_path),this.db.deleteFileHash(h.file_path),i++);for(let h of m){let y=this.db.getFileHash(h.filePath);if(y)if(y!==h.contentHash){let _=await this.indexFile(h.filePath,e);_.success?(s++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}else o++;else {let _=await this.indexFile(h.filePath,e);_.success?(n++,a+=_.nodesCreated,d+=_.edgesCreated):r.push(..._.errors);}}}catch(m){let p=m instanceof Error?m.message:String(m);r.push({filePath:this.config.workspaceDir,error:p});}this.db.setLastSync();let g=new Date().toISOString(),l=Date.now()-t,c={timestamp:g,success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errorCount:r.length,errors:r,duration:l};return this.db.setMeta("lastSyncResult",JSON.stringify(c)),{success:r.length===0,filesAdded:n,filesUpdated:s,filesDeleted:i,filesSkipped:o,nodesCreated:a,edgesCreated:d,errors:r,duration:l}}async scanFiles(e){let t=[],n=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".go",".c",".h",".cpp",".cc",".cxx",".hpp",".cs",".java",".scala",".rb",".php",".zig"].map(g=>`**/*${g}`),s=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/__pycache__/**","**/*.min.js","**/*.min.ts"],i=this.config.ignorePatterns.map(g=>g.includes("/")||g.includes("*")?g:`**/${g}/**`),o=[...s,...i],a=e.replace(/\\/g,"/"),d=await ke(n,{cwd:a,absolute:true,ignore:o,onlyFiles:true});for(let g of d){let l=Filesystem.normalize(g),c=this.parserManager.detectLanguage(l);if(c)try{let m=await this.readFile(l),p=this.computeHash(m);t.push({filePath:l,language:c,contentHash:p,content:m});}catch{}}return t}async readFile(e){try{return await Ae.readFile(e,"utf-8")}catch(t){throw new Q("Failed to read file",e,t instanceof Error?t:new Error(String(t)))}}computeHash(e){return createHash("sha256").update(e).digest("hex")}storeNodes(e){let t=e.map(r=>({id:this.nodeExtractor.generateNodeId(r),name:r.name,ast_type:r.ast_type,language:r.language,file_path:r.file_path,start_line:r.start_line,start_col:r.start_col,end_line:r.end_line,end_col:r.end_col,text:r.text,created_at:new Date().toISOString()}));this.db.insertNodes(t);}storeEdges(e,t){let r=new Set(t.map(s=>this.nodeExtractor.generateNodeId(s))),n=e.filter(s=>r.has(s.source)&&r.has(s.target)).map((s,i)=>({id:`${s.source}:${s.relation}:${s.target}:${i}`,source:s.source,target:s.target,relation:s.relation,created_at:new Date().toISOString()}));n.length>0&&this.db.insertEdges(n);}getValidEdgeCount(e,t){let r=new Set(t.map(n=>this.nodeExtractor.generateNodeId(n)));return e.filter(n=>r.has(n.source)&&r.has(n.target)).length}async embedNodes(e){if(!this.config.embedding)return;let t=this.config.embedding.maxEmbeddingsPerCall||10,r=this.chunkArray(e,t),n=[];for(let s of r){let i=s.map(o=>this.generateNodeEmbeddingText(o));try{let o=await this.config.embedding.doEmbed({values:i});for(let a=0;a<s.length;a++){let d=s[a];if(!d)continue;let g=o.embeddings[a];if(g){let l=new Float32Array(g),c=this.computeHash(this.generateNodeEmbeddingText(d));this.db.cacheEmbedding?.(c,l),n.push({nodeId:this.nodeExtractor.generateNodeId(d),embeddingText:i[a]||"",embedding:l});}}}catch{for(let a of s){if(!a)continue;let d=this.generateNodeEmbeddingText(a),g=await this.embedText(d);g&&n.push({nodeId:this.nodeExtractor.generateNodeId(a),embeddingText:d,embedding:g});}}}n.length>0&&this.db.storeNodeEmbeddings?.(n);}chunkArray(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}};function le(f,e,t){return new D(f,e,t)}var ge=Filesystem.normalize,N=Log.create({service:"codebase.query"}),k=class{constructor(e,t,r={maxResults:20,minScore:.1,hybrid:{enabled:true,vectorWeight:.7,textWeight:.3}}){u(this,"db");u(this,"embedding");u(this,"config");this.db=e,this.embedding=t,this.config=r;}async search(e,t={}){let{maxResults:r=this.config.maxResults,minScore:n=this.config.minScore,language:s,filePath:i,astType:o,enableFts:a=true,includeEdges:d=true,edgesLimit:g=100,vectorWeight:l=this.config.hybrid.vectorWeight,textWeight:c=this.config.hybrid.textWeight,enableEmbedding:m=true}=t;N.debug("search() called",{query:e,astType:o,language:s,enableEmbedding:m,enableFts:a,minScore:n});let p=[];if(m&&this.embedding){let h=await this.vectorSearchNodes(e,r*2,n);N.debug("vectorSearchNodes results",{count:h.length,astTypeFilter:o});for(let y of h){let _=o?y.astType===o:true;N.debug("vector result",{astType:y.astType,name:y.name,match:_}),!(s&&y.language!==s)&&(o&&y.astType!==o||p.push({...y,source:"vector",vectorScore:y.score,hybridScore:y.score*l}));}N.debug("after vector filter",{resultsCount:p.length});}if(a&&this.db.isFtsAvailable()){let h=this.db.searchNodesFts(e,r*2);N.debug("FTS results before filter",{count:h.length});for(let y of h){let _=o?y.ast_type===o:true;if(N.debug("FTS result",{astType:y.ast_type,name:y.name,filterAstType:o,match:_}),s&&y.language!==s||i&&!y.file_path.includes(ge(i))||o&&y.ast_type!==o)continue;let E=this.normalizeScore(y.score),I=p.find(b=>b.id===y.id);I?(I.ftsScore=E,I.hybridScore=I.vectorScore*l+E*c):p.push({id:y.id,name:y.name,astType:y.ast_type,language:y.language,filePath:y.file_path,text:y.text,snippet:y.text.slice(0,200),startLine:y.start_line,startCol:y.start_col,endLine:y.end_line,endCol:y.end_col,score:E,source:"fts",ftsScore:E,hybridScore:E*c});}N.debug("after FTS filter",{resultsCount:p.length});}if(!a||!this.db.isFtsAvailable()||p.length===0)try{let h=this.db.queryNodes({limit:r*2,astType:o,language:s,filePath:i}),y=new Set(p.map(b=>b.id)),_=e.toLowerCase(),E=_.split(/\s+/).filter(b=>b.length>0),I=[];for(let b of h){if(y.has(b.id)||i&&!b.file_path.includes(ge(i)))continue;let U=b.name.toLowerCase(),W=b.text.toLowerCase(),te=0;if(E.some(C=>U.includes(C))){let C=0;for(let j of E){let ee=new RegExp(j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),X=U.match(ee);C+=X?X.length:0;}te=.8*Math.min(C/E.length,1);}let J=0;if(E.some(C=>W.includes(C))){let C=0;for(let X of E){let fe=new RegExp(X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),re=W.match(fe);C+=re?re.length:0;}J=.5*Math.min(C/E.length,1);let j=W.indexOf(_),ee=j===-1?0:Math.max(0,1-j/W.length)*.2;J+=ee;}let Z=Math.max(te,J);Z>0&&I.push({id:b.id,name:b.name,astType:b.ast_type,language:b.language,filePath:b.file_path,text:b.text,snippet:b.text.slice(0,200),startLine:b.start_line,startCol:b.start_col,endLine:b.end_line,endCol:b.end_col,score:Z,source:"basic",hybridScore:Z});}I.sort((b,U)=>U.score-b.score),p.push(...I.slice(0,r));}catch{}let F=p.filter(h=>h.hybridScore>=n).sort((h,y)=>y.hybridScore-h.hybridScore).slice(0,r).map(h=>({id:h.id,name:h.name,ast_type:h.astType,language:h.language,file_path:h.filePath,start_line:h.startLine,start_col:h.startCol,end_line:h.endLine,end_col:h.endCol,text:h.text,created_at:new Date().toISOString()}));if(d&&F.length>0){let h=F.map(E=>E.id),y=this.db.queryEdges({sourceOrTarget:h}),_=new Map;for(let E of y)E.source!==E.target&&(_.has(E.source)||_.set(E.source,[]),_.get(E.source).push(E));return F.map(E=>{let I=_.get(E.id)||[];return {...E,edges:I.slice(0,g)}})}return F.map(h=>({...h,edges:[]}))}async vectorSearchNodes(e,t,r,n){if(N.debug("vectorSearchNodes start",{query:e,limit:t,minScore:r,hasEmbedding:!!this.embedding,candidateCount:n?.length}),!this.embedding)return N.debug("vectorSearchNodes skip - no embedding model"),[];let s=await this.embedText(e);if(!s)return N.debug("vectorSearchNodes skip - no embedding result"),[];let i=new Float32Array(s),o;if(n&&n.length>0){let c=n.map(()=>"?").join(",");o=this.db.queryAll(`SELECT node_id, embedding FROM node_embeddings WHERE node_id IN (${c})`,n);}else o=this.db.queryAll("SELECT node_id, embedding FROM node_embeddings LIMIT ?",[Math.max(t*100,1e3)]);N.debug("vectorSearchNodes vectors loaded",{count:o.length});let a=[];for(let c of o){let m=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),p=this.cosineSimilarity(i,m);a.push({nodeId:c.node_id,score:p});}a.sort((c,m)=>m.score-c.score);let d=a.slice(0,t).map(c=>c.nodeId);N.debug("vectorSearchNodes query nodes",{nodeIdsCount:d.length});let g=this.db.queryNodes({ids:d}),l=new Map(a.slice(0,t).map(c=>[c.nodeId,c.score]));return N.debug("vectorSearchNodes done",{nodesFound:g.length}),g.map(c=>({id:c.id,name:c.name,astType:c.ast_type,language:c.language,filePath:c.file_path,text:c.text??"",snippet:(c.text??"").slice(0,200),startLine:c.start_line??0,startCol:c.start_col??0,endLine:c.end_line??0,endCol:c.end_col??0,score:l.get(c.id)||0,source:"vector"}))}async getEdgesForNode(e,t=100){let r=this.db.queryEdges({source:e.id,target:e.id,limit:t});return {...e,edges:r}}async embedText(e){if(!this.embedding)return null;try{let r=(await this.embedding.doEmbed({values:[e]})).embeddings[0];return r?new Float32Array(r):null}catch{return null}}cosineSimilarity(e,t){let r=0,n=0,s=0;for(let i=0;i<e.length;i++){let o=e[i],a=t[i];r+=o*a,n+=o*o,s+=a*a;}return n===0||s===0?0:r/(Math.sqrt(n)*Math.sqrt(s))}structuralSearch(e,t){let r=[],n=this.db.queryNodes({name:e,language:t.language,filePath:t.filePath,astType:t.astType,limit:t.maxResults??20});for(let s of n){let i=this.calculateNameSimilarity(e,s.name);r.push({id:s.id,name:s.name,astType:s.ast_type,language:s.language,filePath:s.file_path,text:s.text??"",snippet:(s.text??"").slice(0,200),startLine:s.start_line??0,startCol:s.start_col??0,endLine:s.end_line??0,endCol:s.end_col??0,score:i,source:"structural"});}return r}calculateNameSimilarity(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(r===n)return 1;if(n.startsWith(r))return .9;if(n.includes(r))return .7;let s=new Set(r.split("")),i=new Set(n.split("")),o=0;for(let a of s)i.has(a)&&o++;return o/s.size*.5}normalizeScore(e){return 1/(1+Math.exp(-e/10))}queryNodes(e){try{return this.db.queryNodes(e)}catch(t){throw new B("Failed to query nodes",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdges(e){try{return this.db.queryEdges(e)}catch(t){throw new B("Failed to query edges",{filter:e},t instanceof Error?t:new Error(String(t)))}}queryEdgesWithNodes(e){let t=this.db.queryEdges(e),r=[];for(let n of t){let s=this.db.getNodeById(n.source),i=this.db.getNodeById(n.target);s&&i&&r.push({edge:n,sourceNode:s,targetNode:i});}return r}queryNeighbors(e,t={}){let{relationTypes:r,direction:n="both",limit:s=100}=t,i=[],o=[],a=new Set;if(n==="outgoing"||n==="both"){let d=this.db.queryEdges({source:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.target);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}if(n==="incoming"||n==="both"){let d=this.db.queryEdges({target:e,relation:r?.[0],limit:s});for(let g of d){if(r&&!r.includes(g.relation))continue;i.push(g);let l=this.db.getNodeById(g.source);l&&!a.has(l.id)&&(o.push(l),a.add(l.id));}}return {nodes:o.slice(0,s),edges:i.slice(0,s)}}queryCallGraph(e,t=2){let r=new Map,n=new Set,s=(i,o)=>{if(o>t||n.has(i))return;n.add(i);let a=[],d=[],g=this.db.queryEdges({target:i,relation:"CALLS"});for(let c of g)a.push(c.source),s(c.source,o+1);let l=this.db.queryEdges({source:i,relation:"CALLS"});for(let c of l)d.push(c.target),s(c.target,o+1);r.set(i,{callers:a,callees:d});};return s(e,0),r}queryInheritance(e){let t=[],r=[],n=new Set,s=new Set,i=a=>{if(n.has(a))return;n.add(a);let d=this.db.queryEdges({source:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({source:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.target);c&&(t.push(c),i(l.target));}},o=a=>{if(s.has(a))return;s.add(a);let d=this.db.queryEdges({target:a,relation:"INHERITS_FROM"}),g=this.db.queryEdges({target:a,relation:"IMPLEMENTS"});for(let l of [...d,...g]){let c=this.db.getNodeById(l.source);c&&(r.push(c),o(l.source));}};return i(e),o(e),{ancestors:t,descendants:r}}getNode(e){return this.db.getNodeById(e)}getEdge(e){return this.db.getEdgeById(e)}};function ue(f){return new k(f)}var R=Log.create({service:"codebase"}),Qe={database:{path:getDefaultDatabasePath(xdgData,"codebase.db"),walMode:true},parser:{languages:["ts","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"],lazyLoad:true},indexer:{batchSize:50,ignorePatterns:["node_modules/**","dist/**","build/**",".git/**","__pycache__/**","*.min.js","*.min.ts"],incremental:true},sync:DEFAULT_SYNC_CONFIG},K=class{constructor(e={}){u(this,"config");u(this,"db");u(this,"parserManager");u(this,"indexer");u(this,"queryInterface");u(this,"initialized",false);u(this,"dirty",false);u(this,"syncTimer");u(this,"syncingInProgress",false);this.config={...Qe,...e};let t=e.workspaceDir??process.cwd(),r=e.database?.path||getDefaultDatabasePath(xdgData,"codebase.db");this.config={workspaceDir:t,database:{path:r,walMode:e.database?.walMode??true},embedding:{...DEFAULT_EMBEDDING_CONFIG,...e.embedding},search:{...DEFAULT_SEARCH_CONFIG,...e.search},parser:{...DEFAULT_PARSER_CONFIG,...e.parser},indexer:{...DEFAULT_INDEXER_CONFIG,...e.indexer},logDir:e.logDir,embeddingLlm:e.embeddingLlm},this.validateConfig();let n=this.resolveDbPath();this.db=new q(n),this.parserManager=new O;let s={workspaceDir:this.config.workspaceDir,batchSize:this.config.indexer?.batchSize??50,ignorePatterns:this.config.indexer?.ignorePatterns??[],incremental:this.config.indexer?.incremental??true,embedding:this.config.embeddingLlm};this.indexer=new D(this.db,this.parserManager,s),this.queryInterface=new k(this.db,this.config.embeddingLlm,this.config.search);}async initialize(){this.initialized||(this.db.initialize(),await this.parserManager.initialize(),this.config.sync?.intervalMs&&this.startSyncTimer(this.config.sync.intervalMs),this.config.sync?.onBoot&&this.sync().catch(e=>R.warn("codebase sync on boot failed",{error:String(e)})),this.initialized=true,R.debug("Codebase initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path,embeddingEnabled:!!this.config.embeddingLlm,syncOnBoot:!!this.config.sync?.onBoot,syncIntervalMs:this.config.sync?.intervalMs??0,batchSize:this.config.indexer?.batchSize,incremental:this.config.indexer?.incremental,languages:this.config.parser?.languages?.length??0}));}startSyncTimer(e){this.syncTimer&&clearInterval(this.syncTimer),e>0&&(this.syncTimer=setInterval(()=>{if(this.syncingInProgress){R.debug("Sync already in progress, skipping timer sync...");return}this.dirty&&(this.dirty=false,this.sync().catch(t=>{R.error("Interval sync failed",{error:String(t)});}));},e));}stopSyncTimer(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=void 0);}ensureSynced(){this.dirty&&!this.syncingInProgress&&this.config.sync?.onSearch&&(this.dirty=false,this.sync().catch(e=>{R.error("Background sync failed",{error:String(e)});}));}markDirty(){this.dirty=true;}validateConfig(){if(!this.config.workspaceDir)throw new H("workspaceDir is required","workspaceDir");if(!this.config.database?.path)throw new H("database.path is required","database.path")}resolveDbPath(){let e=this.config.database.path;return z.isAbsolute(e)?e:z.join(this.config.workspaceDir,e)}async indexFile(e,t){return await this.ensureInitialized(),this.indexer.indexFile(e,t)}async indexDirectory(e,t){return await this.ensureInitialized(),this.indexer.indexDirectory(e,t)}async sync(e){if(await this.ensureInitialized(),this.syncingInProgress)return R.debug("Sync already in progress, skipping..."),{success:true,filesAdded:0,filesUpdated:0,filesDeleted:0,filesSkipped:0,nodesCreated:0,edgesCreated:0,errors:[],duration:0};this.syncingInProgress=true;try{let t=await this.indexer.sync(e);return R.debug("Codebase sync completed",{success:t.success,filesAdded:t.filesAdded,filesUpdated:t.filesUpdated,filesDeleted:t.filesDeleted,filesSkipped:t.filesSkipped,nodesCreated:t.nodesCreated,edgesCreated:t.edgesCreated,errors:t.errors.length,duration:t.duration}),t}finally{this.syncingInProgress=false;}}async search(e,t){return await this.ensureInitialized(),this.ensureSynced(),this.queryInterface.search(e,t)}async queryNodes(e){return await this.ensureInitialized(),this.queryInterface.queryNodes(e)}async queryEdges(e){return await this.ensureInitialized(),this.queryInterface.queryEdges(e)}async queryNeighbors(e,t){return await this.ensureInitialized(),this.queryInterface.queryNeighbors(e,t)}async queryCallGraph(e,t){return await this.ensureInitialized(),this.queryInterface.queryCallGraph(e,t)}async queryInheritance(e){return await this.ensureInitialized(),this.queryInterface.queryInheritance(e)}async getNode(e){return await this.ensureInitialized(),this.queryInterface.getNode(e)}async getEdge(e){return await this.ensureInitialized(),this.queryInterface.getEdge(e)}async getStatus(){let e=this.db.getStatus();return {dbPath:e.dbPath,nodeCount:e.nodeCount,edgeCount:e.edgeCount,indexedFiles:e.indexedFiles,workspaceDir:this.config.workspaceDir,meta:e.meta,healthy:this.initialized}}async healthCheck(){let e=[];this.db.isClosed()&&e.push("Database is closed"),this.parserManager.isInitialized()||e.push("Parser not initialized"),this.db.isFtsAvailable()||e.push("FTS not available");let t=this.db.getNodeCount();return t===0&&e.push("No nodes indexed"),{healthy:e.length===0,issues:e,nodeCount:t,edgeCount:this.db.getEdgeCount(),fileCount:this.db.getFileCount(),ftsAvailable:this.db.isFtsAvailable(),parserStatus:this.parserManager.getStatus()}}async clear(){this.db.clearAll();}async close(){this.initialized&&(this.stopSyncTimer(),this.db.close(),this.parserManager.dispose(),this.initialized=false,R.info("Codebase closed"));}async ensureInitialized(){this.initialized||await this.initialize();}getDatabase(){return this.db}getParser(){return this.parserManager}getQuery(){return this.queryInterface}};async function Ge(f){let e=new K(f);return await e.initialize(),e}export{K as CodeBase,H as ConfigError,P as DatabaseError,q as DatabaseManager,A as EdgeExtractor,se as FILE_EXTENSION_MAP,Q as FileSystemError,V as IndexError,D as Indexer,M as NodeExtractor,$ as ParserError,O as ParserManager,B as QueryError,k as QueryInterface,G as SchemaError,Y as UnsupportedLanguageError,Ge as createCodebase,ce as createEdgeExtractor,le as createIndexer,de as createNodeExtractor,ue as createQueryInterface,ae as getParserManager,oe as resetParserManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/codebase",
3
- "version": "0.2.48",
3
+ "version": "0.3.0",
4
4
  "description": "Code Knowledge Graph SDK for EASBot - Property Graph model for code indexing and querying with Tree-sitter parsing, FTS hybrid search, and incremental updates",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -69,9 +69,9 @@
69
69
  "web-tree-sitter": "^0.26.8",
70
70
  "xdg-basedir": "^5.1.0",
71
71
  "zod": "^4.4.3",
72
- "@easbot/local-model-sdk": "0.2.48",
73
- "@easbot/types": "0.2.48",
74
- "@easbot/utils": "0.2.48"
72
+ "@easbot/local-model-sdk": "0.3.0",
73
+ "@easbot/types": "0.3.0",
74
+ "@easbot/utils": "0.3.0"
75
75
  },
76
76
  "devDependencies": {
77
77
  "@biomejs/biome": "^2.4.14",
@@ -1,4 +0,0 @@
1
- import Zi,{win32,posix}from'path';import {fileURLToPath}from'url';import uh,{realpath,readlink,readdir,lstat}from'fs/promises';import*as Dn from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import So from'zod';import {EventEmitter}from'events';import Nr from'stream';import {StringDecoder}from'string_decoder';import {formatLogTime}from'@easbot/utils';var dh=Object.defineProperty;var Rs=e=>{throw TypeError(e)};var gh=(e,t,i)=>t in e?dh(e,t,{enumerable:true,configurable:true,writable:true,value:i}):e[t]=i;var p=(e,t,i)=>gh(e,typeof t!="symbol"?t+"":t,i),Yi=(e,t,i)=>t.has(e)||Rs("Cannot "+i);var r=(e,t,i)=>(Yi(e,t,"read from private field"),i?i.call(e):t.get(e)),m=(e,t,i)=>t.has(e)?Rs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),c=(e,t,i,s)=>(Yi(e,t,"write to private field"),t.set(e,i),i),g=(e,t,i)=>(Yi(e,t,"access private method"),i);var ki=(e,t,i,s)=>({set _(h){c(e,t,h);},get _(){return r(e,t,s)}});var yh=()=>fileURLToPath(import.meta.url),bh=()=>Zi.dirname(yh()),Os=bh();var Sr=(e,t,i)=>{let s=e instanceof RegExp?As(e,i):e,h=t instanceof RegExp?As(t,i):t,n=s!==null&&h!=null&&vh(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},As=(e,t)=>{let i=t.match(e);return i?i[0]:null},vh=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},vr="\0SLASH"+Math.random()+"\0",Er="\0OPEN"+Math.random()+"\0",Ss="\0CLOSE"+Math.random()+"\0",xr="\0COMMA"+Math.random()+"\0",kr="\0PERIOD"+Math.random()+"\0",Eh=new RegExp(vr,"g"),xh=new RegExp(Er,"g"),kh=new RegExp(Ss,"g"),Ch=new RegExp(xr,"g"),Rh=new RegExp(kr,"g"),Oh=/\\\\/g,Ah=/\\{/g,Fh=/\\}/g,Th=/\\,/g,Mh=/\\./g,Lh=1e5;function Xi(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Wh(e){return e.replace(Oh,vr).replace(Ah,Er).replace(Fh,Ss).replace(Th,xr).replace(Mh,kr)}function Ph(e){return e.replace(Eh,"\\").replace(xh,"{").replace(kh,"}").replace(Ch,",").replace(Rh,".")}function Cr(e){if(!e)return [""];let t=[],i=Sr("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=Cr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Dh(e,t={}){if(!e)return [];let{max:i=Lh}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),qe(Wh(e),i,true).map(Ph)}function jh(e){return "{"+e+"}"}function _h(e){return /^-?0\d/.test(e)}function Nh(e,t){return e<=t}function zh(e,t){return e>=t}function qe(e,t,i){let s=[],h=Sr("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?qe(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+Ss+h.post,qe(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=Cr(h.body),f.length===1&&f[0]!==void 0&&(f=qe(f[0],t,false).map(jh),f.length===1))return o.map(v=>h.pre+f[0]+v);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let v=Xi(f[0]),S=Xi(f[1]),y=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Xi(f[2])):1,E=Nh;S<v&&(x*=-1,E=zh);let O=f.some(_h);w=[];for(let A=v;E(A,S);A+=x){let T;if(l)T=String.fromCharCode(A),T==="\\"&&(T="");else if(T=String(A),O){let M=y-T.length;if(M>0){let mt=new Array(M+1).join("0");A<0?T="-"+mt+T.slice(1):T=mt+T;}}w.push(T);}}else {w=[];for(let v=0;v<f.length;v++)w.push.apply(w,qe(f[v],t,false));}for(let v=0;v<w.length;v++)for(let S=0;S<o.length&&s.length<t;S++){let y=n+w[v]+o[S];(!i||u||y)&&s.push(y);}}return s}var $i=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Bh={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},$e=e=>e.replace(/[[\]\\-]/g,"\\$&"),$h=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Fs=e=>e.join(""),Uh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let S=e.charAt(n);if((S==="!"||S==="^")&&n===i+1){u=true,n++;continue}if(S==="]"&&o&&!l){d=n+1;break}if(o=true,S==="\\"&&!l){l=true,n++;continue}if(S==="["&&!l){for(let[y,[x,E,O]]of Object.entries(Bh))if(e.startsWith(y,n)){if(f)return ["$.",false,e.length-i,true];n+=y.length,O?h.push(x):s.push(x),a=a||E;continue t}}if(l=false,f){S>f?s.push($e(f)+"-"+$e(S)):S===f&&s.push($e(S)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push($e(S+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=S,n+=2;continue}s.push($e(S)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let S=s[0].length===2?s[0].slice(-1):s[0];return [$h(S),false,d-i,false]}let w="["+(u?"^":"")+Fs(s)+"]",v="["+(u?"":"^")+Fs(h)+"]";return [s.length&&h.length?"("+w+"|"+v+")":s.length?w:v,a,d-i,true]},Oe=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),Ih=new Set(["!","?","+","*","@"]),Ts=e=>Ih.has(e),Gh="(?!(?:^|/)\\.\\.?(?:$|/))",Ci="(?!\\.)",Hh=new Set(["[","."]),Jh=new Set(["..","."]),qh=new Set("().*{}+?[]^$\\!"),Zh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vs="[^/]",Ms=vs+"*?",Ls=vs+"+?",$,Z,$t,W,z,te,pe,ee,Dt,fe,ti,Ee,Or,oe,Y,Wi,ns,Ar,Rr=(Y=class{constructor(t,i,s={}){m(this,Ee);p(this,"type");m(this,$);m(this,Z);m(this,$t,false);m(this,W,[]);m(this,z);m(this,te);m(this,pe);m(this,ee,false);m(this,Dt);m(this,fe);m(this,ti,false);this.type=t,t&&c(this,Z,true),c(this,z,i),c(this,$,r(this,z)?r(r(this,z),$):this),c(this,Dt,r(this,$)===this?s:r(r(this,$),Dt)),c(this,pe,r(this,$)===this?[]:r(r(this,$),pe)),t==="!"&&!r(r(this,$),ee)&&r(this,pe).push(this),c(this,te,r(this,z)?r(r(this,z),W).length:0);}get hasMagic(){if(r(this,Z)!==void 0)return r(this,Z);for(let t of r(this,W))if(typeof t!="string"&&(t.type||t.hasMagic))return c(this,Z,true);return r(this,Z)}toString(){return r(this,fe)!==void 0?r(this,fe):this.type?c(this,fe,this.type+"("+r(this,W).map(t=>String(t)).join("|")+")"):c(this,fe,r(this,W).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof Y&&r(i,z)===this))throw new Error("invalid part: "+i);r(this,W).push(i);}}toJSON(){let t=this.type===null?r(this,W).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...r(this,W).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===r(this,$)||r(r(this,$),ee)&&r(this,z)?.type==="!")&&t.push({}),t}isStart(){if(r(this,$)===this)return true;if(!r(this,z)?.isStart())return false;if(r(this,te)===0)return true;let t=r(this,z);for(let i=0;i<r(this,te);i++){let s=r(t,W)[i];if(!(s instanceof Y&&s.type==="!"))return false}return true}isEnd(){if(r(this,$)===this||r(this,z)?.type==="!")return true;if(!r(this,z)?.isEnd())return false;if(!this.type)return r(this,z)?.isEnd();let t=r(this,z)?r(r(this,z),W).length:0;return r(this,te)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new Y(this.type,t);for(let s of r(this,W))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new Y(null,void 0,i);return g(h=Y,oe,Wi).call(h,t,s,0,i),s}toMMPattern(){if(this!==r(this,$))return r(this,$).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||r(this,Z)||r(this,Dt).nocase&&!r(this,Dt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(r(this,Dt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return r(this,Dt)}toRegExpSource(t){let i=t??!!r(this,Dt).dot;if(r(this,$)===this&&g(this,Ee,Or).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!r(this,W).some(w=>typeof w!="string"),u=r(this,W).map(w=>{var E;let[v,S,y,x]=typeof w=="string"?g(E=Y,oe,Ar).call(E,w,r(this,Z),l):w.toRegExpSource(t);return c(this,Z,r(this,Z)||y),c(this,$t,r(this,$t)||x),v}).join(""),d="";if(this.isStart()&&typeof r(this,W)[0]=="string"&&!(r(this,W).length===1&&Jh.has(r(this,W)[0]))){let w=Hh,v=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),S=!i&&!t&&w.has(u.charAt(0));d=v?Gh:S?Ci:"";}let f="";return this.isEnd()&&r(r(this,$),ee)&&r(this,z)?.type==="!"&&(f="(?:$|\\/)"),[d+u+f,Oe(u),c(this,Z,!!r(this,Z)),r(this,$t)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=g(this,Ee,ns).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return c(this,W,[l]),this.type=null,c(this,Z,void 0),[l,Oe(this.toString()),false,false]}let o=!s||t||i||!Ci?"":g(this,Ee,ns).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&r(this,ti))a=(this.isStart()&&!i?Ci:"")+Ls;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?Ci:"")+Ms+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Oe(n),c(this,Z,!!r(this,Z)),r(this,$t)]}},$=new WeakMap,Z=new WeakMap,$t=new WeakMap,W=new WeakMap,z=new WeakMap,te=new WeakMap,pe=new WeakMap,ee=new WeakMap,Dt=new WeakMap,fe=new WeakMap,ti=new WeakMap,Ee=new WeakSet,Or=function(){if(this!==r(this,$))throw new Error("should only call on root");if(r(this,ee))return this;this.toString(),c(this,ee,true);let t;for(;t=r(this,pe).pop();){if(t.type!=="!")continue;let i=t,s=r(i,z);for(;s;){for(let h=r(i,te)+1;!s.type&&h<r(s,W).length;h++)for(let n of r(t,W)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(r(s,W)[h]);}i=s,s=r(i,z);}}return this},oe=new WeakSet,Wi=function(t,i,s,h){var v,S;let n=false,o=false,a=-1,l=false;if(i.type===null){let y=s,x="";for(;y<t.length;){let E=t.charAt(y++);if(n||E==="\\"){n=!n,x+=E;continue}if(o){y===a+1?(E==="^"||E==="!")&&(l=true):E==="]"&&!(y===a+2&&l)&&(o=false),x+=E;continue}else if(E==="["){o=true,a=y,l=false,x+=E;continue}if(!h.noext&&Ts(E)&&t.charAt(y)==="("){i.push(x),x="";let O=new Y(E,i);y=g(v=Y,oe,Wi).call(v,t,O,y,h),i.push(O);continue}x+=E;}return i.push(x),y}let u=s+1,d=new Y(null,i),f=[],w="";for(;u<t.length;){let y=t.charAt(u++);if(n||y==="\\"){n=!n,w+=y;continue}if(o){u===a+1?(y==="^"||y==="!")&&(l=true):y==="]"&&!(u===a+2&&l)&&(o=false),w+=y;continue}else if(y==="["){o=true,a=u,l=false,w+=y;continue}if(Ts(y)&&t.charAt(u)==="("){d.push(w),w="";let x=new Y(y,d);d.push(x),u=g(S=Y,oe,Wi).call(S,t,x,u,h);continue}if(y==="|"){d.push(w),w="",f.push(d),d=new Y(null,i);continue}if(y===")")return w===""&&r(i,W).length===0&&c(i,ti,true),d.push(w),w="",i.push(...f,d),u;w+=y;}return i.type=null,c(i,Z,void 0),c(i,W,[t.substring(s-1)]),u},ns=function(t){return r(this,W).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return c(this,$t,r(this,$t)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},Ar=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(qh.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?Ls:Ms,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,v]=Uh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||v;continue}}if(u==="?"){n+=vs,i=true;continue}n+=Zh(u);}return [n,Oe(t),!!i,o]},m(Y,oe),Y),Fr=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),ht=(e,t,i={})=>($i(t),!i.nocomment&&t.charAt(0)==="#"?false:new ae(t,i).match(e)),Vh=/^\*+([^+@!?\*\[\(]*)$/,Kh=e=>t=>!t.startsWith(".")&&t.endsWith(e),Yh=e=>t=>t.endsWith(e),Xh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Qh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),tn=/^\*+\.\*+$/,en=e=>!e.startsWith(".")&&e.includes("."),sn=e=>e!=="."&&e!==".."&&e.includes("."),rn=/^\.\*+$/,hn=e=>e!=="."&&e!==".."&&e.startsWith("."),nn=/^\*+$/,on=e=>e.length!==0&&!e.startsWith("."),an=e=>e.length!==0&&e!=="."&&e!=="..",ln=/^\?+([^+@!?\*\[\(]*)?$/,cn=([e,t=""])=>{let i=Tr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},un=([e,t=""])=>{let i=Mr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},pn=([e,t=""])=>{let i=Mr([e]);return t?s=>i(s)&&s.endsWith(t):i},fn=([e,t=""])=>{let i=Tr([e]);return t?s=>i(s)&&s.endsWith(t):i},Tr=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Mr=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Lr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ws={win32:{sep:"\\"},posix:{sep:"/"}},dn=Lr==="win32"?Ws.win32.sep:Ws.posix.sep;ht.sep=dn;var rt=Symbol("globstar **");ht.GLOBSTAR=rt;var gn="[^/]",mn=gn+"*?",wn="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",yn="(?:(?!(?:\\/|^)\\.).)*?",bn=(e,t={})=>i=>ht(i,e,t);ht.filter=bn;var wt=(e,t={})=>Object.assign({},e,t),Sn=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return ht;let t=ht;return Object.assign((i,s,h={})=>t(i,s,wt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,wt(e,s));}static defaults(i){return t.defaults(wt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,wt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,wt(e,s))}},unescape:(i,s={})=>t.unescape(i,wt(e,s)),escape:(i,s={})=>t.escape(i,wt(e,s)),filter:(i,s={})=>t.filter(i,wt(e,s)),defaults:i=>t.defaults(wt(e,i)),makeRe:(i,s={})=>t.makeRe(i,wt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,wt(e,s)),match:(i,s,h={})=>t.match(i,s,wt(e,h)),sep:t.sep,GLOBSTAR:rt})};ht.defaults=Sn;var Wr=(e,t={})=>($i(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Dh(e,{max:t.braceExpandMax}));ht.braceExpand=Wr;var vn=(e,t={})=>new ae(e,t).makeRe();ht.makeRe=vn;var En=(e,t,i={})=>{let s=new ae(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};ht.match=En;var Ps=/[?*]|[+@!]\(.*?\)|\[|\]/,xn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ae=class{constructor(e,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");$i(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Lr,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ps.test(h[2]))&&!Ps.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let S=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!S&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),E=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),O=y?3:S?0:void 0,A=E?3:x?0:void 0;if(typeof O=="number"&&typeof A=="number"){let[T,M]=[e[O],t[A]];T.toLowerCase()===M.toLowerCase()&&(t[A]=T,A>O?t=t.slice(A):O>A&&(e=e.slice(O)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===rt){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var v=e[f];if(this.debug(`
2
- globstar while`,e,f,t,w,v),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,v),true;if(v==="."||v===".."||!s.dot&&v.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
3
- >>> no match, partial?`,e,f,t,w),f===a))}let S;if(typeof u=="string"?(S=d===u,this.debug("string match",u,d,S)):(S=u.test(d),this.debug("pattern match",u,d,S)),!S)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Wr(this.pattern,this.options)}parse(e){$i(e);let t=this.options;if(e==="**")return rt;if(e==="")return "";let i,s=null;(i=e.match(nn))?s=t.dot?an:on:(i=e.match(Vh))?s=(t.nocase?t.dot?Qh:Xh:t.dot?Yh:Kh)(i[1]):(i=e.match(ln))?s=(t.nocase?t.dot?un:cn:t.dot?pn:fn)(i):(i=e.match(tn))?s=t.dot?sn:en:(i=e.match(rn))&&(s=hn);let h=Rr.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?mn:t.dot?wn:yn,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?xn(d):d===rt?rt:d._src});l.forEach((d,f)=>{let w=l[f+1],v=l[f-1];d!==rt||v===rt||(v===void 0?w!==void 0&&w!==rt?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=v+"(?:\\/|\\/"+i+")?":w!==rt&&(l[f-1]=v+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=rt));});let u=l.filter(d=>d!==rt);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return ht.defaults(e).Minimatch}};ht.AST=Rr;ht.Minimatch=ae;ht.escape=Fr;ht.unescape=Oe;var Cn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Pr=new Set,os=typeof process=="object"&&process?process:{},Dr=(e,t,i,s)=>{typeof os.emitWarning=="function"?os.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Ui=globalThis.AbortController,Ds=globalThis.AbortSignal;if(typeof Ui>"u"){Ds=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Ui=class{constructor(){p(this,"signal",new Ds);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e=os.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Dr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var Rn=e=>!Pr.has(e),Kt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),jr=e=>Kt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Pi:null:null,Pi=class extends Array{constructor(e){super(e),this.fill(0);}},Nt,Ae,On=(Nt=class{constructor(t,i){p(this,"heap");p(this,"length");if(!r(Nt,Ae))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=jr(t);if(!i)return [];c(Nt,Ae,true);let s=new Nt(t,i);return c(Nt,Ae,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Ae=new WeakMap,m(Nt,Ae,false),Nt),Ks,Ys,bt,ut,kt,de,Ct,Fe,Te,Rt,U,Ot,B,P,R,et,pt,Q,V,At,K,Ft,Tt,ft,dt,Mt,ie,it,Me,b,as,ge,Ut,ei,gt,_r,me,Le,ii,Yt,Xt,ls,Di,ji,L,cs,Ze,Qt,us,We,Hi=(We=class{constructor(t){m(this,b);m(this,bt);m(this,ut);m(this,kt);m(this,de);m(this,Ct);m(this,Fe);m(this,Te);m(this,Rt);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");m(this,U);m(this,Ot);m(this,B);m(this,P);m(this,R);m(this,et);m(this,pt);m(this,Q);m(this,V);m(this,At);m(this,K);m(this,Ft);m(this,Tt);m(this,ft);m(this,dt);m(this,Mt);m(this,ie);m(this,it);m(this,Me);m(this,ge,()=>{});m(this,Ut,()=>{});m(this,ei,()=>{});m(this,gt,()=>false);m(this,me,t=>{});m(this,Le,(t,i,s)=>{});m(this,ii,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Ks,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:u,onInsert:d,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:v,maxSize:S=0,maxEntrySize:y=0,sizeCalculation:x,fetchMethod:E,memoMethod:O,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:mt,ignoreFetchAbort:F,perf:D}=t;if(D!==void 0&&typeof D?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(c(this,Rt,D??Cn),i!==0&&!Kt(i))throw new TypeError("max option must be a nonnegative integer");let _=i?jr(i):Array;if(!_)throw new Error("invalid max value: "+i);if(c(this,bt,i),c(this,ut,S),this.maxEntrySize=y||r(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!r(this,ut)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(O!==void 0&&typeof O!="function")throw new TypeError("memoMethod must be a function if defined");if(c(this,Te,O),E!==void 0&&typeof E!="function")throw new TypeError("fetchMethod must be a function if specified");if(c(this,Fe,E),c(this,ie,!!E),c(this,B,new Map),c(this,P,new Array(i).fill(void 0)),c(this,R,new Array(i).fill(void 0)),c(this,et,new _(i)),c(this,pt,new _(i)),c(this,Q,0),c(this,V,0),c(this,At,On.create(i)),c(this,U,0),c(this,Ot,0),typeof u=="function"&&c(this,kt,u),typeof d=="function"&&c(this,de,d),typeof f=="function"?(c(this,Ct,f),c(this,K,[])):(c(this,Ct,void 0),c(this,K,void 0)),c(this,Mt,!!r(this,kt)),c(this,Me,!!r(this,de)),c(this,it,!!r(this,Ct)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!M,this.allowStaleOnFetchAbort=!!mt,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(r(this,ut)!==0&&!Kt(r(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Kt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");g(this,b,_r).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Kt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Kt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");g(this,b,as).call(this);}if(r(this,bt)===0&&this.ttl===0&&r(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!r(this,bt)&&!r(this,ut)){let nt="LRU_CACHE_UNBOUNDED";Rn(nt)&&(Pr.add(nt),Dr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",nt,We));}}get perf(){return r(this,Rt)}static unsafeExposeInternals(t){return {starts:r(t,Tt),ttls:r(t,ft),autopurgeTimers:r(t,dt),sizes:r(t,Ft),keyMap:r(t,B),keyList:r(t,P),valList:r(t,R),next:r(t,et),prev:r(t,pt),get head(){return r(t,Q)},get tail(){return r(t,V)},free:r(t,At),isBackgroundFetch:i=>{var s;return g(s=t,b,L).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return g(o=t,b,ji).call(o,i,s,h,n)},moveToTail:i=>{var s;return g(s=t,b,Ze).call(s,i)},indexes:i=>{var s;return g(s=t,b,Yt).call(s,i)},rindexes:i=>{var s;return g(s=t,b,Xt).call(s,i)},isStale:i=>{var s;return r(s=t,gt).call(s,i)}}}get max(){return r(this,bt)}get maxSize(){return r(this,ut)}get calculatedSize(){return r(this,Ot)}get size(){return r(this,U)}get fetchMethod(){return r(this,Fe)}get memoMethod(){return r(this,Te)}get dispose(){return r(this,kt)}get onInsert(){return r(this,de)}get disposeAfter(){return r(this,Ct)}getRemainingTTL(t){return r(this,B).has(t)?1/0:0}*entries(){for(let t of g(this,b,Yt).call(this))r(this,R)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield [r(this,P)[t],r(this,R)[t]]);}*rentries(){for(let t of g(this,b,Xt).call(this))r(this,R)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield [r(this,P)[t],r(this,R)[t]]);}*keys(){for(let t of g(this,b,Yt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield i);}}*rkeys(){for(let t of g(this,b,Xt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield i);}}*values(){for(let t of g(this,b,Yt).call(this))r(this,R)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield r(this,R)[t]);}*rvalues(){for(let t of g(this,b,Xt).call(this))r(this,R)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield r(this,R)[t]);}[(Ys=Symbol.iterator,Ks=Symbol.toStringTag,Ys)](){return this.entries()}find(t,i={}){for(let s of g(this,b,Yt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,r(this,P)[s],this))return this.get(r(this,P)[s],i)}}forEach(t,i=this){for(let s of g(this,b,Yt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}rforEach(t,i=this){for(let s of g(this,b,Xt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}purgeStale(){let t=false;for(let i of g(this,b,Xt).call(this,{allowStale:true}))r(this,gt).call(this,i)&&(g(this,b,Qt).call(this,r(this,P)[i],"expire"),t=true);return t}info(t){let i=r(this,B).get(t);if(i===void 0)return;let s=r(this,R)[i],h=g(this,b,L).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(r(this,ft)&&r(this,Tt)){let o=r(this,ft)[i],a=r(this,Tt)[i];if(o&&a){let l=o-(r(this,Rt).now()-a);n.ttl=l,n.start=Date.now();}}return r(this,Ft)&&(n.size=r(this,Ft)[i]),n}dump(){let t=[];for(let i of g(this,b,Yt).call(this,{allowStale:true})){let s=r(this,P)[i],h=r(this,R)[i],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(r(this,ft)&&r(this,Tt)){o.ttl=r(this,ft)[i];let a=r(this,Rt).now()-r(this,Tt)[i];o.start=Math.floor(Date.now()-a);}r(this,Ft)&&(o.size=r(this,Ft)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=r(this,Rt).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,v,S,y;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d=r(this,ii).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),g(this,b,Qt).call(this,t,"set"),this;let f=r(this,U)===0?void 0:r(this,B).get(t);if(f===void 0)f=r(this,U)===0?r(this,V):r(this,At).length!==0?r(this,At).pop():r(this,U)===r(this,bt)?g(this,b,Di).call(this,false):r(this,U),r(this,P)[f]=t,r(this,R)[f]=i,r(this,B).set(t,f),r(this,et)[r(this,V)]=f,r(this,pt)[f]=r(this,V),c(this,V,f),ki(this,U)._++,r(this,Le).call(this,f,d,l),l&&(l.set="add"),u=false,r(this,Me)&&((w=r(this,de))==null||w.call(this,i,t,"add"));else {g(this,b,Ze).call(this,f);let x=r(this,R)[f];if(i!==x){if(r(this,ie)&&g(this,b,L).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:E}=x;E!==void 0&&!o&&(r(this,Mt)&&((v=r(this,kt))==null||v.call(this,E,t,"set")),r(this,it)&&r(this,K)?.push([E,t,"set"]));}else o||(r(this,Mt)&&((S=r(this,kt))==null||S.call(this,x,t,"set")),r(this,it)&&r(this,K)?.push([x,t,"set"]));if(r(this,me).call(this,f),r(this,Le).call(this,f,d,l),r(this,R)[f]=i,l){l.set="replace";let E=x&&g(this,b,L).call(this,x)?x.__staleWhileFetching:x;E!==void 0&&(l.oldValue=E);}}else l&&(l.set="update");r(this,Me)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!r(this,ft)&&g(this,b,as).call(this),r(this,ft)&&(u||r(this,ei).call(this,f,h,n),l&&r(this,Ut).call(this,l,f)),!o&&r(this,it)&&r(this,K)){let x=r(this,K),E;for(;E=x?.shift();)(y=r(this,Ct))==null||y.call(this,...E);}return this}pop(){var t;try{for(;r(this,U);){let i=r(this,R)[r(this,Q)];if(g(this,b,Di).call(this,!0),g(this,b,L).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(r(this,it)&&r(this,K)){let i=r(this,K),s;for(;s=i?.shift();)(t=r(this,Ct))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=r(this,B).get(t);if(n!==void 0){let o=r(this,R)[n];if(g(this,b,L).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(r(this,gt).call(this,n))h&&(h.has="stale",r(this,Ut).call(this,h,n));else return s&&r(this,ge).call(this,n),h&&(h.has="hit",r(this,Ut).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=r(this,B).get(t);if(h===void 0||!s&&r(this,gt).call(this,h))return;let n=r(this,R)[h];return g(this,b,L).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:v=this.ignoreFetchAbort,allowStaleOnFetchAbort:S=this.allowStaleOnFetchAbort,context:y,forceRefresh:x=false,status:E,signal:O}=i;if(!r(this,ie))return E&&(E.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:E});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:S,ignoreFetchAbort:v,status:E,signal:O},T=r(this,B).get(t);if(T===void 0){E&&(E.fetch="miss");let M=g(this,b,ji).call(this,t,T,A,y);return M.__returned=M}else {let M=r(this,R)[T];if(g(this,b,L).call(this,M)){let _=s&&M.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",_&&(E.returnedStale=true)),_?M.__staleWhileFetching:M.__returned=M}let mt=r(this,gt).call(this,T);if(!x&&!mt)return E&&(E.fetch="hit"),g(this,b,Ze).call(this,T),h&&r(this,ge).call(this,T),E&&r(this,Ut).call(this,E,T),M;let F=g(this,b,ji).call(this,t,T,A,y),D=F.__staleWhileFetching!==void 0&&s;return E&&(E.fetch=mt?"stale":"refresh",D&&mt&&(E.returnedStale=true)),D?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=r(this,Te);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=r(this,B).get(t);if(a!==void 0){let l=r(this,R)[a],u=g(this,b,L).call(this,l);return o&&r(this,Ut).call(this,o,a),r(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||g(this,b,Qt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(g(this,b,Ze).call(this,a),h&&r(this,ge).call(this,a),l))}else o&&(o.get="miss");}delete(t){return g(this,b,Qt).call(this,t,"delete")}clear(){return g(this,b,us).call(this,"delete")}},bt=new WeakMap,ut=new WeakMap,kt=new WeakMap,de=new WeakMap,Ct=new WeakMap,Fe=new WeakMap,Te=new WeakMap,Rt=new WeakMap,U=new WeakMap,Ot=new WeakMap,B=new WeakMap,P=new WeakMap,R=new WeakMap,et=new WeakMap,pt=new WeakMap,Q=new WeakMap,V=new WeakMap,At=new WeakMap,K=new WeakMap,Ft=new WeakMap,Tt=new WeakMap,ft=new WeakMap,dt=new WeakMap,Mt=new WeakMap,ie=new WeakMap,it=new WeakMap,Me=new WeakMap,b=new WeakSet,as=function(){let t=new Pi(r(this,bt)),i=new Pi(r(this,bt));c(this,ft,t),c(this,Tt,i);let s=this.ttlAutopurge?new Array(r(this,bt)):void 0;c(this,dt,s),c(this,ei,(o,a,l=r(this,Rt).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{r(this,gt).call(this,o)&&g(this,b,Qt).call(this,r(this,P)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),c(this,ge,o=>{i[o]=t[o]!==0?r(this,Rt).now():0;}),c(this,Ut,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=r(this,Rt).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=r(this,B).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},c(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},ge=new WeakMap,Ut=new WeakMap,ei=new WeakMap,gt=new WeakMap,_r=function(){let t=new Pi(r(this,bt));c(this,Ot,0),c(this,Ft,t),c(this,me,i=>{c(this,Ot,r(this,Ot)-t[i]),t[i]=0;}),c(this,ii,(i,s,h,n)=>{if(g(this,b,L).call(this,s))return 0;if(!Kt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Kt(h))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return h}),c(this,Le,(i,s,h)=>{if(t[i]=s,r(this,ut)){let n=r(this,ut)-t[i];for(;r(this,Ot)>n;)g(this,b,Di).call(this,true);}c(this,Ot,r(this,Ot)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=r(this,Ot));});},me=new WeakMap,Le=new WeakMap,ii=new WeakMap,Yt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,V);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,Q)));)i=r(this,pt)[i];},Xt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,Q);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,V)));)i=r(this,et)[i];},ls=function(t){return t!==void 0&&r(this,B).get(r(this,P)[t])===t},Di=function(t){var n;let i=r(this,Q),s=r(this,P)[i],h=r(this,R)[i];return r(this,ie)&&g(this,b,L).call(this,h)?h.__abortController.abort(new Error("evicted")):(r(this,Mt)||r(this,it))&&(r(this,Mt)&&((n=r(this,kt))==null||n.call(this,h,s,"evict")),r(this,it)&&r(this,K)?.push([h,s,"evict"])),r(this,me).call(this,i),r(this,dt)?.[i]&&(clearTimeout(r(this,dt)[i]),r(this,dt)[i]=void 0),t&&(r(this,P)[i]=void 0,r(this,R)[i]=void 0,r(this,At).push(i)),r(this,U)===1?(c(this,Q,c(this,V,0)),r(this,At).length=0):c(this,Q,r(this,et)[i]),r(this,B).delete(s),ki(this,U)._--,i},ji=function(t,i,s,h){let n=i===void 0?void 0:r(this,R)[i];if(g(this,b,L).call(this,n))return n;let o=new Ui,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(y,x=false)=>{let{aborted:E}=o.signal,O=s.ignoreFetchAbort&&y!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&y!==void 0);if(s.status&&(E&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,O&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),E&&!O&&!x)return f(o.signal.reason,A);let T=v,M=r(this,R)[i];return (M===v||O&&x&&M===void 0)&&(y===void 0?T.__staleWhileFetching!==void 0?r(this,R)[i]=T.__staleWhileFetching:g(this,b,Qt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,y,l.options))),y},d=y=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=y),f(y,false)),f=(y,x)=>{let{aborted:E}=o.signal,O=E&&s.allowStaleOnFetchAbort,A=O||s.allowStaleOnFetchRejection,T=A||s.noDeleteOnFetchRejection,M=v;if(r(this,R)[i]===v&&(!T||!x&&M.__staleWhileFetching===void 0?g(this,b,Qt).call(this,t,"fetch"):O||(r(this,R)[i]=M.__staleWhileFetching)),A)return s.status&&M.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),M.__staleWhileFetching;if(M.__returned===M)throw y},w=(y,x)=>{var O;let E=(O=r(this,Fe))==null?void 0:O.call(this,t,n,l);E&&E instanceof Promise&&E.then(A=>y(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(y(void 0),s.allowStaleOnFetchAbort&&(y=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let v=new Promise(w).then(u,d),S=Object.assign(v,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,S,{...l.options,status:void 0}),i=r(this,B).get(t)):r(this,R)[i]=S,S},L=function(t){if(!r(this,ie))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Ui},cs=function(t,i){r(this,pt)[i]=t,r(this,et)[t]=i;},Ze=function(t){t!==r(this,V)&&(t===r(this,Q)?c(this,Q,r(this,et)[t]):g(this,b,cs).call(this,r(this,pt)[t],r(this,et)[t]),g(this,b,cs).call(this,r(this,V),t),c(this,V,t));},Qt=function(t,i){var h,n;let s=false;if(r(this,U)!==0){let o=r(this,B).get(t);if(o!==void 0)if(r(this,dt)?.[o]&&(clearTimeout(r(this,dt)?.[o]),r(this,dt)[o]=void 0),s=true,r(this,U)===1)g(this,b,us).call(this,i);else {r(this,me).call(this,o);let a=r(this,R)[o];if(g(this,b,L).call(this,a)?a.__abortController.abort(new Error("deleted")):(r(this,Mt)||r(this,it))&&(r(this,Mt)&&((h=r(this,kt))==null||h.call(this,a,t,i)),r(this,it)&&r(this,K)?.push([a,t,i])),r(this,B).delete(t),r(this,P)[o]=void 0,r(this,R)[o]=void 0,o===r(this,V))c(this,V,r(this,pt)[o]);else if(o===r(this,Q))c(this,Q,r(this,et)[o]);else {let l=r(this,pt)[o];r(this,et)[l]=r(this,et)[o];let u=r(this,et)[o];r(this,pt)[u]=r(this,pt)[o];}ki(this,U)._--,r(this,At).push(o);}}if(r(this,it)&&r(this,K)?.length){let o=r(this,K),a;for(;a=o?.shift();)(n=r(this,Ct))==null||n.call(this,...a);}return s},us=function(t){var i,s;for(let h of g(this,b,Xt).call(this,{allowStale:true})){let n=r(this,R)[h];if(g(this,b,L).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=r(this,P)[h];r(this,Mt)&&((i=r(this,kt))==null||i.call(this,n,o,t)),r(this,it)&&r(this,K)?.push([n,o,t]);}}if(r(this,B).clear(),r(this,R).fill(void 0),r(this,P).fill(void 0),r(this,ft)&&r(this,Tt)){r(this,ft).fill(0),r(this,Tt).fill(0);for(let h of r(this,dt)??[])h!==void 0&&clearTimeout(h);r(this,dt)?.fill(void 0);}if(r(this,Ft)&&r(this,Ft).fill(0),c(this,Q,0),c(this,V,0),r(this,At).length=0,c(this,Ot,0),c(this,U,0),r(this,it)&&r(this,K)){let h=r(this,K),n;for(;n=h?.shift();)(s=r(this,Ct))==null||s.call(this,...n);}},We),js=typeof process=="object"&&process?process:{stdout:null,stderr:null},$n=e=>!!e&&typeof e=="object"&&(e instanceof Ii||e instanceof Nr||Un(e)||In(e)),Un=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.pipe=="function"&&e.pipe!==Nr.Writable.prototype.pipe,In=e=>!!e&&typeof e=="object"&&e instanceof EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",zt=Symbol("EOF"),Bt=Symbol("maybeEmitEnd"),Vt=Symbol("emittedEnd"),Ri=Symbol("emittingEnd"),Ue=Symbol("emittedError"),Oi=Symbol("closed"),_s=Symbol("read"),Ai=Symbol("flush"),Ns=Symbol("flushChunk"),Et=Symbol("encoding"),Ce=Symbol("decoder"),H=Symbol("flowing"),Ie=Symbol("paused"),Re=Symbol("resume"),J=Symbol("buffer"),tt=Symbol("pipes"),q=Symbol("bufferLength"),Qi=Symbol("bufferPush"),Fi=Symbol("bufferShift"),X=Symbol("objectMode"),N=Symbol("destroyed"),ts=Symbol("error"),es=Symbol("emitData"),zs=Symbol("emitEnd"),is=Symbol("emitEnd2"),Wt=Symbol("async"),ss=Symbol("abort"),Ti=Symbol("aborted"),Ge=Symbol("signal"),le=Symbol("dataListeners"),ct=Symbol("discarded"),He=e=>Promise.resolve().then(e),Gn=e=>e(),Hn=e=>e==="end"||e==="finish"||e==="prefinish",Jn=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,qn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),zr=class{constructor(e,t,i){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Re](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Zn=class extends zr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},Vn=e=>!!e.objectMode,Kn=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,fr,dr,gr,mr,Ii=class extends EventEmitter{constructor(...t){let i=t[0]||{};super();p(this,mr,false);p(this,gr,false);p(this,dr,[]);p(this,fr,[]);p(this,pr);p(this,ur);p(this,cr);p(this,lr);p(this,ar,false);p(this,or,false);p(this,nr,false);p(this,hr,false);p(this,rr,null);p(this,sr,0);p(this,ir,false);p(this,er);p(this,tr,false);p(this,Qs,0);p(this,Xs,false);p(this,"writable",true);p(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Vn(i)?(this[X]=true,this[Et]=null):Kn(i)?(this[Et]=i.encoding,this[X]=false):(this[X]=false,this[Et]=null),this[Wt]=!!i.async,this[Ce]=this[Et]?new StringDecoder(this[Et]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[J]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[tt]});let{signal:s}=i;s&&(this[Ge]=s,s.aborted?this[ss]():s.addEventListener("abort",()=>this[ss]()));}get bufferLength(){return this[q]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[X]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Wt]}set async(t){this[Wt]=this[Wt]||!!t;}[(mr=H,gr=Ie,dr=tt,fr=J,pr=X,ur=Et,cr=Wt,lr=Ce,ar=zt,or=Vt,nr=Ri,hr=Oi,rr=Ue,sr=q,ir=N,er=Ge,tr=Ti,Qs=le,Xs=ct,ss)](){this[Ti]=true,this.emit("abort",this[Ge]?.reason),this.destroy(this[Ge]?.reason);}get aborted(){return this[Ti]}set aborted(t){}write(t,i,s){if(this[Ti])return false;if(this[zt])throw new Error("write after end");if(this[N])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let h=this[Wt]?He:Gn;if(!this[X]&&!Buffer.isBuffer(t)){if(qn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Jn(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[X]?(this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):t.length?(typeof t=="string"&&!(i===this[Et]&&!this[Ce]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[Et]&&(t=this[Ce].write(t)),this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):(this[q]!==0&&this.emit("readable"),s&&h(s),this[H])}read(t){if(this[N])return null;if(this[ct]=false,this[q]===0||t===0||t&&t>this[q])return this[Bt](),null;this[X]&&(t=null),this[J].length>1&&!this[X]&&(this[J]=[this[Et]?this[J].join(""):Buffer.concat(this[J],this[q])]);let i=this[_s](t||null,this[J][0]);return this[Bt](),i}[_s](t,i){if(this[X])this[Fi]();else {let s=i;t===s.length||t===null?this[Fi]():typeof s=="string"?(this[J][0]=s.slice(t),i=s.slice(0,t),this[q]-=t):(this[J][0]=s.subarray(t),i=s.subarray(0,t),this[q]-=t);}return this.emit("data",i),!this[J].length&&!this[zt]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[zt]=true,this.writable=false,(this[H]||!this[Ie])&&this[Bt](),this}[Re](){this[N]||(!this[le]&&!this[tt].length&&(this[ct]=true),this[Ie]=false,this[H]=true,this.emit("resume"),this[J].length?this[Ai]():this[zt]?this[Bt]():this.emit("drain"));}resume(){return this[Re]()}pause(){this[H]=false,this[Ie]=true,this[ct]=false;}get destroyed(){return this[N]}get flowing(){return this[H]}get paused(){return this[Ie]}[Qi](t){this[X]?this[q]+=1:this[q]+=t.length,this[J].push(t);}[Fi](){return this[X]?this[q]-=1:this[q]-=this[J][0].length,this[J].shift()}[Ai](t=false){do;while(this[Ns](this[Fi]())&&this[J].length);!t&&!this[J].length&&!this[zt]&&this.emit("drain");}[Ns](t){return this.emit("data",t),this[H]}pipe(t,i){if(this[N])return t;this[ct]=false;let s=this[Vt];return i=i||{},t===js.stdout||t===js.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[tt].push(i.proxyErrors?new Zn(this,t,i):new zr(this,t,i)),this[Wt]?He(()=>this[Re]()):this[Re]()),t}unpipe(t){let i=this[tt].find(s=>s.dest===t);i&&(this[tt].length===1?(this[H]&&this[le]===0&&(this[H]=false),this[tt]=[]):this[tt].splice(this[tt].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[le]++,!this[tt].length&&!this[H]&&this[Re]();else if(t==="readable"&&this[q]!==0)super.emit("readable");else if(Hn(t)&&this[Vt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ue]){let h=i;this[Wt]?He(()=>h.call(this,this[Ue])):h.call(this,this[Ue]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[le]=this.listeners("data").length,this[le]===0&&!this[ct]&&!this[tt].length&&(this[H]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[le]=0,!this[ct]&&!this[tt].length&&(this[H]=false)),i}get emittedEnd(){return this[Vt]}[Bt](){!this[Ri]&&!this[Vt]&&!this[N]&&this[J].length===0&&this[zt]&&(this[Ri]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Oi]&&this.emit("close"),this[Ri]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==N&&this[N])return false;if(t==="data")return !this[X]&&!s?false:this[Wt]?(He(()=>this[es](s)),true):this[es](s);if(t==="end")return this[zs]();if(t==="close"){if(this[Oi]=true,!this[Vt]&&!this[N])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Ue]=s,super.emit(ts,s);let n=!this[Ge]||this.listeners("error").length?super.emit("error",s):false;return this[Bt](),n}else if(t==="resume"){let n=super.emit("resume");return this[Bt](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[Bt](),h}[es](t){for(let s of this[tt])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[Bt](),i}[zs](){return this[Vt]?false:(this[Vt]=true,this.readable=false,this[Wt]?(He(()=>this[is]()),true):this[is]())}[is](){if(this[Ce]){let i=this[Ce].end();if(i){for(let s of this[tt])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[tt])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[X]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[X]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[X])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(N,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[zt])return i();let h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(N,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(N,u),this.pause(),h({value:d,done:!!this[zt]});},l=()=>{this.off("error",o),this.off("data",a),this.off(N,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(N,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(ts,i),this.off(N,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(ts,i),this.once(N,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[N])return t?this.emit("error",t):this.emit(N),this;this[N]=true,this[ct]=true,this[J].length=0,this[q]=0;let i=this;return typeof i.close=="function"&&!this[Oi]&&i.close(),t?this.emit("error",t):this.emit(N),this}static get isStream(){return $n}},Yn=realpathSync.native,Ve={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Yn,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Br=e=>!e||e===Ve||e===Dn?Ve:{...Ve,...e,promises:{...Ve.promises,...e.promises||{}}},$r=/^\\\\\?\\([a-z]:)\\?$/i,Xn=e=>e.replace(/\//g,"\\").replace($r,"$1\\"),Qn=/[\\\/]/,St=0,Ur=1,Ir=2,Pt=4,Gr=6,Hr=8,ce=10,Jr=12,yt=15,Je=~yt,rs=16,Bs=32,Ke=64,xt=128,Mi=256,_i=512,$s=Ke|xt|_i,to=1023,hs=e=>e.isFile()?Hr:e.isDirectory()?Pt:e.isSymbolicLink()?ce:e.isCharacterDevice()?Ir:e.isBlockDevice()?Gr:e.isSocket()?Jr:e.isFIFO()?Ur:St,Us=new Hi({max:2**12}),Ye=e=>{let t=Us.get(e);if(t)return t;let i=e.normalize("NFKD");return Us.set(e,i),i},Is=new Hi({max:2**12}),Li=e=>{let t=Is.get(e);if(t)return t;let i=Ye(e.toLowerCase());return Is.set(e,i),i},Gs=class extends Hi{constructor(){super({max:256});}},eo=class extends Hi{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},qr=Symbol("PathScurry setAsCwd"),st,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,Si,se,we,jt,It,Gt,Ht,C,ye,Jt,_t,k,fs,Ni,Xe,ds,gs,Qe,zi,ms,ws,Bi,Zr,Vr,Kr,ys,Pe,De,Yr,be,wr,at=(wr=class{constructor(e,t=St,i,s,h,n,o){m(this,k);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);m(this,st);m(this,si);m(this,ri);m(this,hi);m(this,ni);m(this,oi);m(this,ai);m(this,li);m(this,ci);m(this,ui);m(this,pi);m(this,fi);m(this,di);m(this,gi);m(this,mi);m(this,wi);m(this,yi);m(this,bi);m(this,Si);m(this,se);m(this,we);m(this,jt);m(this,It);m(this,Gt);m(this,Ht);m(this,C);m(this,ye);m(this,Jt);m(this,_t);m(this,Pe,[]);m(this,De,false);m(this,be);this.name=e,c(this,se,h?Li(e):Ye(e)),c(this,C,t&to),this.nocase=h,this.roots=s,this.root=i||this,c(this,ye,n),c(this,jt,o.fullpath),c(this,Gt,o.relative),c(this,Ht,o.relativePosix),this.parent=o.parent,this.parent?c(this,st,r(this.parent,st)):c(this,st,Br(o.fs));}get dev(){return r(this,si)}get mode(){return r(this,ri)}get nlink(){return r(this,hi)}get uid(){return r(this,ni)}get gid(){return r(this,oi)}get rdev(){return r(this,ai)}get blksize(){return r(this,li)}get ino(){return r(this,ci)}get size(){return r(this,ui)}get blocks(){return r(this,pi)}get atimeMs(){return r(this,fi)}get mtimeMs(){return r(this,di)}get ctimeMs(){return r(this,gi)}get birthtimeMs(){return r(this,mi)}get atime(){return r(this,wi)}get mtime(){return r(this,yi)}get ctime(){return r(this,bi)}get birthtime(){return r(this,Si)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return r(this,we)!==void 0?r(this,we):this.parent?c(this,we,this.parent.depth()+1):c(this,we,0)}childrenCache(){return r(this,ye)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i=e.substring(t.length).split(this.splitSep);return t?g(s=this.getRoot(t),k,fs).call(s,i):g(this,k,fs).call(this,i)}children(){let e=r(this,ye).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return r(this,ye).set(this,t),c(this,C,r(this,C)&~rs),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Li(e):Ye(e);for(let a of i)if(r(a,se)===s)return a;let h=this.parent?this.sep:"",n=r(this,jt)?r(this,jt)+h+e:void 0,o=this.newChild(e,St,{...t,parent:this,fullpath:n});return this.canReaddir()||c(o,C,r(o,C)|xt),i.push(o),o}relative(){if(this.isCWD)return "";if(r(this,Gt)!==void 0)return r(this,Gt);let e=this.name,t=this.parent;if(!t)return c(this,Gt,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(r(this,Ht)!==void 0)return r(this,Ht);let e=this.name,t=this.parent;if(!t)return c(this,Ht,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(r(this,jt)!==void 0)return r(this,jt);let e=this.name,t=this.parent;if(!t)return c(this,jt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return c(this,jt,i)}fullpathPosix(){if(r(this,It)!==void 0)return r(this,It);if(this.sep==="/")return c(this,It,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?c(this,It,`//?/${s}`):c(this,It,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return c(this,It,i)}isUnknown(){return (r(this,C)&yt)===St}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (r(this,C)&yt)===Hr}isDirectory(){return (r(this,C)&yt)===Pt}isCharacterDevice(){return (r(this,C)&yt)===Ir}isBlockDevice(){return (r(this,C)&yt)===Gr}isFIFO(){return (r(this,C)&yt)===Ur}isSocket(){return (r(this,C)&yt)===Jr}isSymbolicLink(){return (r(this,C)&ce)===ce}lstatCached(){return r(this,C)&Bs?this:void 0}readlinkCached(){return r(this,Jt)}realpathCached(){return r(this,_t)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(r(this,Jt))return true;if(!this.parent)return false;let e=r(this,C)&yt;return !(e!==St&&e!==ce||r(this,C)&Mi||r(this,C)&xt)}calledReaddir(){return !!(r(this,C)&rs)}isENOENT(){return !!(r(this,C)&xt)}isNamed(e){return this.nocase?r(this,se)===Li(e):r(this,se)===Ye(e)}async readlink(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await r(this,st).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}readlinkSync(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=r(this,st).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}async lstat(){if((r(this,C)&xt)===0)try{return g(this,k,ys).call(this,await r(this,st).promises.lstat(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}lstatSync(){if((r(this,C)&xt)===0)try{return g(this,k,ys).call(this,r(this,st).lstatSync(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e(null,h):queueMicrotask(()=>e(null,h));return}if(r(this,Pe).push(e),r(this,De))return;c(this,De,true);let s=this.fullpath();r(this,st).readdir(s,{withFileTypes:true},(h,n)=>{if(h)g(this,k,zi).call(this,h.code),i.provisional=0;else {for(let o of n)g(this,k,Bi).call(this,o,i);g(this,k,Ni).call(this,i);}g(this,k,Yr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(r(this,be))await r(this,be);else {let i=()=>{};c(this,be,new Promise(s=>i=s));try{for(let s of await r(this,st).promises.readdir(t,{withFileTypes:!0}))g(this,k,Bi).call(this,s,e);g(this,k,Ni).call(this,e);}catch(s){g(this,k,zi).call(this,s.code),e.provisional=0;}c(this,be,void 0),i();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i of r(this,st).readdirSync(t,{withFileTypes:!0}))g(this,k,Bi).call(this,i,e);g(this,k,Ni).call(this,e);}catch(i){g(this,k,zi).call(this,i.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(r(this,C)&$s)return false;let e=yt&r(this,C);return e===St||e===Pt||e===ce}shouldWalk(e,t){return (r(this,C)&Pt)===Pt&&!(r(this,C)&$s)&&!e.has(this)&&(!t||t(this))}async realpath(){if(r(this,_t))return r(this,_t);if(!((_i|Mi|xt)&r(this,C)))try{let e=await r(this,st).promises.realpath(this.fullpath());return c(this,_t,this.resolve(e))}catch{g(this,k,gs).call(this);}}realpathSync(){if(r(this,_t))return r(this,_t);if(!((_i|Mi|xt)&r(this,C)))try{let e=r(this,st).realpathSync(this.fullpath());return c(this,_t,this.resolve(e))}catch{g(this,k,gs).call(this);}}[qr](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),c(s,Gt,i.join(this.sep)),c(s,Ht,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)c(s,Gt,void 0),c(s,Ht,void 0),s=s.parent;}},st=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,Si=new WeakMap,se=new WeakMap,we=new WeakMap,jt=new WeakMap,It=new WeakMap,Gt=new WeakMap,Ht=new WeakMap,C=new WeakMap,ye=new WeakMap,Jt=new WeakMap,_t=new WeakMap,k=new WeakSet,fs=function(e){let t=this;for(let i of e)t=t.child(i);return t},Ni=function(e){var t;c(this,C,r(this,C)|rs);for(let i=e.provisional;i<e.length;i++){let s=e[i];s&&g(t=s,k,Xe).call(t);}},Xe=function(){r(this,C)&xt||(c(this,C,(r(this,C)|xt)&Je),g(this,k,ds).call(this));},ds=function(){var t;let e=this.children();e.provisional=0;for(let i of e)g(t=i,k,Xe).call(t);},gs=function(){c(this,C,r(this,C)|_i),g(this,k,Qe).call(this);},Qe=function(){if(r(this,C)&Ke)return;let e=r(this,C);(e&yt)===Pt&&(e&=Je),c(this,C,e|Ke),g(this,k,ds).call(this);},zi=function(e=""){e==="ENOTDIR"||e==="EPERM"?g(this,k,Qe).call(this):e==="ENOENT"?g(this,k,Xe).call(this):this.children().provisional=0;},ms=function(e=""){var t;e==="ENOTDIR"?g(t=this.parent,k,Qe).call(t):e==="ENOENT"&&g(this,k,Xe).call(this);},ws=function(e=""){var i;let t=r(this,C);t|=Mi,e==="ENOENT"&&(t|=xt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Je),c(this,C,t),e==="ENOTDIR"&&this.parent&&g(i=this.parent,k,Qe).call(i);},Bi=function(e,t){return g(this,k,Vr).call(this,e,t)||g(this,k,Zr).call(this,e,t)},Zr=function(e,t){let i=hs(e),s=this.newChild(e.name,i,{parent:this}),h=r(s,C)&yt;return h!==Pt&&h!==ce&&h!==St&&c(s,C,r(s,C)|Ke),t.unshift(s),t.provisional++,s},Vr=function(e,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Li(e.name):Ye(e.name))===r(s,se))return g(this,k,Kr).call(this,e,s,i,t)}},Kr=function(e,t,i,s){let h=t.name;return c(t,C,r(t,C)&Je|hs(e)),h!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},ys=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d,ino:f,mode:w,mtime:v,mtimeMs:S,nlink:y,rdev:x,size:E,uid:O}=e;c(this,wi,t),c(this,fi,i),c(this,Si,s),c(this,mi,h),c(this,li,n),c(this,pi,o),c(this,bi,a),c(this,gi,l),c(this,si,u),c(this,oi,d),c(this,ci,f),c(this,ri,w),c(this,yi,v),c(this,di,S),c(this,hi,y),c(this,ai,x),c(this,ui,E),c(this,ni,O);let A=hs(e);c(this,C,r(this,C)&Je|A|Bs),A!==St&&A!==Pt&&A!==ce&&c(this,C,r(this,C)|Ke);},Pe=new WeakMap,De=new WeakMap,Yr=function(e){c(this,De,false);let t=r(this,Pe).slice();r(this,Pe).length=0,t.forEach(i=>i(null,e));},be=new WeakMap,wr),Xr=class Qr extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"sep","\\");p(this,"splitSep",Qn);}newChild(i,s=St,h={}){return new Qr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return win32.parse(i).root}getRoot(i){if(i=Xn(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new xs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace($r,"$1\\"),i===s}},th=class eh extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"splitSep","/");p(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=St,h={}){return new eh(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},je,_e,vi,Ei,yr,ih=(yr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ve}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");m(this,je);m(this,_e);m(this,vi);p(this,"nocase");m(this,Ei);c(this,Ei,Br(n)),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),c(this,je,new Gs),c(this,_e,new Gs),c(this,vi,new eo(h));let a=o.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(r(this,Ei)),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,d=t.sep,f=this.rootPath,w=false;for(let v of a){let S=u--;l=l.child(v,{relative:new Array(S).fill("..").join(d),relativePosix:new Array(S).fill("..").join("/"),fullpath:f+=(w?"":d)+v}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return r(this,vi)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return r(this,je).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,_e).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return r(this,_e).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,v)=>{if(w)return f(w);let S=v.length;if(!S)return f();let y=()=>{--S===0&&f();};for(let x of v)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(E=>E?.isUnknown()?E.lstat():E).then(E=>E?.shouldWalk(a,n)?l(E,y):y()):x.shouldWalk(a,n)?l(x,y):y();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ii({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=(y,x,E=false)=>{if(y)return o.emit("error",y);if(s&&!E){let O=[];for(let A of x)A.isSymbolicLink()&&O.push(A.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(O.length){Promise.all(O).then(()=>v(null,x,true));return}}for(let O of x)O&&(!h||h(O))&&(o.write(i?O:O.fullpath())||(f=true));u--;for(let O of x){let A=O.realpathCached()||O;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):S||d();},S=true;w.readdirCB(v,true),S=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ii({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=w.readdirSync();for(let S of v)(!h||h(S))&&(o.write(i?S:S.fullpath())||(f=true));u--;for(let S of v){let y=S;if(S.isSymbolicLink()){if(!(s&&(y=S.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(a,n)&&l.push(y);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[qr](t);}},je=new WeakMap,_e=new WeakMap,vi=new WeakMap,Ei=new WeakMap,yr),xs=class extends ih{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,win32,"\\",{...i,nocase:s});p(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return win32.parse(t).root.toUpperCase()}newRoot(t){return new Xr(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},ks=class extends ih{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,posix,"/",{...i,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new th(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},sh=class extends ks{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Xr:th;var io=process.platform==="win32"?xs:process.platform==="darwin"?sh:ks,so=e=>e.length>=1,ro=e=>e.length>=1,ho=Symbol.for("nodejs.util.inspect.custom"),I,lt,G,Se,Lt,xi,re,he,ne,Ne,ze,rh=(ze=class{constructor(t,i,s,h){m(this,I);m(this,lt);m(this,G);p(this,"length");m(this,Se);m(this,Lt);m(this,xi);m(this,re);m(this,he);m(this,ne);m(this,Ne,true);if(!so(t))throw new TypeError("empty pattern list");if(!ro(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(c(this,I,t),c(this,lt,i),c(this,G,s),c(this,Se,h),r(this,G)===0){if(this.isUNC()){let[n,o,a,l,...u]=r(this,I),[d,f,w,v,...S]=r(this,lt);u[0]===""&&(u.shift(),S.shift());let y=[n,o,a,l,""].join("/"),x=[d,f,w,v,""].join("/");c(this,I,[y,...u]),c(this,lt,[x,...S]),this.length=r(this,I).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=r(this,I),[a,...l]=r(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d=a+"/";c(this,I,[u,...o]),c(this,lt,[d,...l]),this.length=r(this,I).length;}}}[ho](){return "Pattern <"+r(this,lt).slice(r(this,G)).join("/")+">"}pattern(){return r(this,I)[r(this,G)]}isString(){return typeof r(this,I)[r(this,G)]=="string"}isGlobstar(){return r(this,I)[r(this,G)]===rt}isRegExp(){return r(this,I)[r(this,G)]instanceof RegExp}globString(){return c(this,xi,r(this,xi)||(r(this,G)===0?this.isAbsolute()?r(this,lt)[0]+r(this,lt).slice(1).join("/"):r(this,lt).join("/"):r(this,lt).slice(r(this,G)).join("/")))}hasMore(){return this.length>r(this,G)+1}rest(){return r(this,Lt)!==void 0?r(this,Lt):this.hasMore()?(c(this,Lt,new ze(r(this,I),r(this,lt),r(this,G)+1,r(this,Se))),c(r(this,Lt),ne,r(this,ne)),c(r(this,Lt),he,r(this,he)),c(r(this,Lt),re,r(this,re)),r(this,Lt)):c(this,Lt,null)}isUNC(){let t=r(this,I);return r(this,he)!==void 0?r(this,he):c(this,he,r(this,Se)==="win32"&&r(this,G)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=r(this,I);return r(this,re)!==void 0?r(this,re):c(this,re,r(this,Se)==="win32"&&r(this,G)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=r(this,I);return r(this,ne)!==void 0?r(this,ne):c(this,ne,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=r(this,I)[0];return typeof t=="string"&&this.isAbsolute()&&r(this,G)===0?t:""}checkFollowGlobstar(){return !(r(this,G)===0||!this.isGlobstar()||!r(this,Ne))}markFollowGlobstar(){return r(this,G)===0||!this.isGlobstar()||!r(this,Ne)?false:(c(this,Ne,false),true)}},I=new WeakMap,lt=new WeakMap,G=new WeakMap,Se=new WeakMap,Lt=new WeakMap,xi=new WeakMap,re=new WeakMap,he=new WeakMap,ne=new WeakMap,Ne=new WeakMap,ze),no=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Hs=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=no}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new ae(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new rh(s,h,0,this.platform),o=new ae(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},oo=class hh{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new hh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},ao=class{constructor(){p(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},lo=class{constructor(){p(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Js=class nh{constructor(t,i){p(this,"hasWalkedCache");p(this,"matches",new ao);p(this,"subwalks",new lo);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new oo;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===rt){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let v=h.parent||h;w?this.hasWalkedCache.hasWalked(v,w)||this.subwalks.add(v,w):this.matches.add(v,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new nh(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===rt?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},co=(e,t)=>typeof e=="string"?new Hs([e],t):Array.isArray(e)?new Hs(e,t):e,Be,qt,ve,vt,ue,bs,br,oh=(br=class{constructor(e,t,i){m(this,vt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);m(this,Be,[]);m(this,qt);m(this,ve);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,c(this,ve,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(c(this,qt,co(i.ignore??[],i)),!this.includeChildMatches&&typeof r(this,qt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{r(this,Be).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=r(this,Be).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?r(this,Be).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!g(this,vt,ue).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(g(this,vt,ue).call(this,e))return;if(!this.includeChildMatches&&r(this,qt)?.add){let h=`${e.relativePosix()}/**`;r(this,qt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?r(this,ve):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i){let h=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+r(this,ve))?"."+r(this,ve):"";this.matchEmit(h?n+h+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new Js(this.opts),i);}walkCB2(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Js(this.opts),i);}walkCB2Sync(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},Be=new WeakMap,qt=new WeakMap,ve=new WeakMap,vt=new WeakSet,ue=function(e){return this.seen.has(e)||!!r(this,qt)?.ignored?.(e)},bs=function(e){return !!r(this,qt)?.childrenIgnored?.(e)},br),qs=class extends oh{constructor(t,i,s){super(t,i,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Zs=class extends oh{constructor(t,i,s){super(t,i,s);p(this,"results");this.results=new Ii({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},uo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",xe=class{constructor(e,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||uo,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=t.platform==="win32"?xs:t.platform==="darwin"?sh:t.platform?ks:io;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},h=this.pattern.map(a=>new ae(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new rh(a,u,0,this.platform)});}async walk(){return [...await new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Zs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Zs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},po=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new ae(i,t).hasMagic())return true;return false};function Ji(e,t={}){return new xe(e,t).streamSync()}function ah(e,t={}){return new xe(e,t).stream()}function lh(e,t={}){return new xe(e,t).walkSync()}async function Vs(e,t={}){return new xe(e,t).walk()}function qi(e,t={}){return new xe(e,t).iterateSync()}function ch(e,t={}){return new xe(e,t).iterate()}var fo=Ji,go=Object.assign(ah,{sync:Ji}),mo=qi,wo=Object.assign(ch,{sync:qi}),yo=Object.assign(lh,{stream:Ji,iterate:qi}),Gi=Object.assign(Vs,{glob:Vs,globSync:lh,sync:yo,globStream:ah,stream:go,globStreamSync:Ji,streamSync:fo,globIterate:ch,iterate:wo,globIterateSync:qi,iterateSync:mo,Glob:xe,hasMagic:po,escape:Fr,unescape:Oe});Gi.glob=Gi;var ph;(mt=>{mt.Level=So.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(F){return t[F]>=t[i]}function h(){return i}mt.getLevel=h;let n=new Map;mt.Default=M({service:"default"});let a="";function l(){return a}mt.file=l;let u,d,f=false,w=false,v=F=>{try{w&&process.stderr.write(F);}catch{}},S=false,y=false;async function x(F){if(f)return;if(F.level&&(i=F.level),F.print&&(w=F.print??false),F.print){f=true;return}let D=F.logDir||Zi.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");F.logFile?a=Zi.join(D,F.logFile??"codebase.log"):a=Zi.join(D,"codebase.log");try{await uh.mkdir(D,{recursive:!0}),u=await uh.open(a,"a"),d=createWriteStream("",{fd:u.fd,autoClose:!1}),v=_=>{if(!(S||y||!d||d.destroyed))try{if(!d.writable)return;d.write(_,nt=>{if(nt&&!S){let j=nt;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(nt){let j=nt;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch{v=_=>{try{process.stderr.write(_);}catch{}},f=true;}}mt.init=x;async function E(){f&&(d&&!d.destroyed&&(await new Promise((F,D)=>{d.end(_=>{_?D(_):F();});}).catch(()=>{}),d=void 0),u&&(await u.close().catch(()=>{}),u=void 0),v=F=>{try{process.stderr.write(F);}catch{}},f=false);}mt.close=E;function A(F,D=0){let _=F.message;return F.cause instanceof Error&&D<10?_+" Caused by: "+A(F.cause,D+1):_}let T=Date.now();function M(F){F=F||{};let D=F.service;if(D&&typeof D=="string"){let j=n.get(D);if(j)return j}function _(j,ot){let Vi=Object.entries({...F,...ot}).filter(([Cs,Zt])=>Zt!=null).map(([Cs,Zt])=>{let Ki=`${Cs}=`;return Zt instanceof Error?Ki+A(Zt):typeof Zt=="object"?Ki+JSON.stringify(Zt):Ki+Zt}).join(" "),ke=new Date,fh=ke.getTime()-T;return T=ke.getTime(),[formatLogTime(ke),"+"+fh+"ms",Vi,j].filter(Boolean).join(" ")+`
4
- `}let nt={debug(j,ot){s("DEBUG")&&v("DEBUG "+_(j,ot));},info(j,ot){s("INFO")&&v("INFO "+_(j,ot));},error(j,ot){s("ERROR")&&v("ERROR "+_(j,ot));},warn(j,ot){s("WARN")&&v("WARN "+_(j,ot));},tag(j,ot){return F&&(F[j]=ot),nt},clone(){return mt.create({...F})},time(j,ot){let Vi=Date.now();nt.info(j,{status:"started",...ot});function ke(){nt.info(j,{status:"completed",duration:Date.now()-Vi,...ot});}return {stop:ke,[Symbol.dispose](){ke();}}}};return D&&typeof D=="string"&&n.set(D,nt),nt}mt.create=M;})(ph||(ph={}));export{p as a,Os as b,ph as c};
@@ -1,4 +0,0 @@
1
- 'use strict';var Zi=require('path'),uh=require('fs/promises'),Mn=require('fs'),mo=require('zod'),url=require('url'),events=require('events'),zr=require('stream'),string_decoder=require('string_decoder'),utils=require('@easbot/utils');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Zi__default=/*#__PURE__*/_interopDefault(Zi);var uh__default=/*#__PURE__*/_interopDefault(uh);var Mn__namespace=/*#__PURE__*/_interopNamespace(Mn);var mo__default=/*#__PURE__*/_interopDefault(mo);var zr__default=/*#__PURE__*/_interopDefault(zr);var dh=Object.defineProperty;var Rs=e=>{throw TypeError(e)};var gh=(e,t,i)=>t in e?dh(e,t,{enumerable:true,configurable:true,writable:true,value:i}):e[t]=i;var p=(e,t,i)=>gh(e,typeof t!="symbol"?t+"":t,i),Yi=(e,t,i)=>t.has(e)||Rs("Cannot "+i);var r=(e,t,i)=>(Yi(e,t,"read from private field"),i?i.call(e):t.get(e)),m=(e,t,i)=>t.has(e)?Rs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),c=(e,t,i,s)=>(Yi(e,t,"write to private field"),t.set(e,i),i),g=(e,t,i)=>(Yi(e,t,"access private method"),i);var ki=(e,t,i,s)=>({set _(h){c(e,t,h);},get _(){return r(e,t,s)}});var mh=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,Os=mh();var Sr=(e,t,i)=>{let s=e instanceof RegExp?As(e,i):e,h=t instanceof RegExp?As(t,i):t,n=s!==null&&h!=null&&wh(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},As=(e,t)=>{let i=t.match(e);return i?i[0]:null},wh=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},vr="\0SLASH"+Math.random()+"\0",Er="\0OPEN"+Math.random()+"\0",Ss="\0CLOSE"+Math.random()+"\0",xr="\0COMMA"+Math.random()+"\0",kr="\0PERIOD"+Math.random()+"\0",yh=new RegExp(vr,"g"),bh=new RegExp(Er,"g"),Sh=new RegExp(Ss,"g"),vh=new RegExp(xr,"g"),Eh=new RegExp(kr,"g"),xh=/\\\\/g,kh=/\\{/g,Ch=/\\}/g,Rh=/\\,/g,Oh=/\\./g,Ah=1e5;function Xi(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Th(e){return e.replace(xh,vr).replace(kh,Er).replace(Ch,Ss).replace(Rh,xr).replace(Oh,kr)}function Fh(e){return e.replace(yh,"\\").replace(bh,"{").replace(Sh,"}").replace(vh,",").replace(Eh,".")}function Cr(e){if(!e)return [""];let t=[],i=Sr("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=Cr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Mh(e,t={}){if(!e)return [];let{max:i=Ah}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),qe(Th(e),i,true).map(Fh)}function Lh(e){return "{"+e+"}"}function Wh(e){return /^-?0\d/.test(e)}function Ph(e,t){return e<=t}function Dh(e,t){return e>=t}function qe(e,t,i){let s=[],h=Sr("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?qe(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+Ss+h.post,qe(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=Cr(h.body),f.length===1&&f[0]!==void 0&&(f=qe(f[0],t,false).map(Lh),f.length===1))return o.map(v=>h.pre+f[0]+v);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let v=Xi(f[0]),S=Xi(f[1]),y=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Xi(f[2])):1,E=Ph;S<v&&(x*=-1,E=Dh);let O=f.some(Wh);w=[];for(let A=v;E(A,S);A+=x){let F;if(l)F=String.fromCharCode(A),F==="\\"&&(F="");else if(F=String(A),O){let M=y-F.length;if(M>0){let mt=new Array(M+1).join("0");A<0?F="-"+mt+F.slice(1):F=mt+F;}}w.push(F);}}else {w=[];for(let v=0;v<f.length;v++)w.push.apply(w,qe(f[v],t,false));}for(let v=0;v<w.length;v++)for(let S=0;S<o.length&&s.length<t;S++){let y=n+w[v]+o[S];(!i||u||y)&&s.push(y);}}return s}var $i=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},jh={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},$e=e=>e.replace(/[[\]\\-]/g,"\\$&"),Nh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ts=e=>e.join(""),zh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let S=e.charAt(n);if((S==="!"||S==="^")&&n===i+1){u=true,n++;continue}if(S==="]"&&o&&!l){d=n+1;break}if(o=true,S==="\\"&&!l){l=true,n++;continue}if(S==="["&&!l){for(let[y,[x,E,O]]of Object.entries(jh))if(e.startsWith(y,n)){if(f)return ["$.",false,e.length-i,true];n+=y.length,O?h.push(x):s.push(x),a=a||E;continue t}}if(l=false,f){S>f?s.push($e(f)+"-"+$e(S)):S===f&&s.push($e(S)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push($e(S+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=S,n+=2;continue}s.push($e(S)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let S=s[0].length===2?s[0].slice(-1):s[0];return [Nh(S),false,d-i,false]}let w="["+(u?"^":"")+Ts(s)+"]",v="["+(u?"":"^")+Ts(h)+"]";return [s.length&&h.length?"("+w+"|"+v+")":s.length?w:v,a,d-i,true]},Oe=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),_h=new Set(["!","?","+","*","@"]),Fs=e=>_h.has(e),Bh="(?!(?:^|/)\\.\\.?(?:$|/))",Ci="(?!\\.)",$h=new Set(["[","."]),Uh=new Set(["..","."]),Ih=new Set("().*{}+?[]^$\\!"),Gh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vs="[^/]",Ms=vs+"*?",Ls=vs+"+?",$,Z,$t,W,_,te,pe,ee,Dt,fe,ti,Ee,Or,oe,Y,Wi,ns,Ar,Rr=(Y=class{constructor(t,i,s={}){m(this,Ee);p(this,"type");m(this,$);m(this,Z);m(this,$t,false);m(this,W,[]);m(this,_);m(this,te);m(this,pe);m(this,ee,false);m(this,Dt);m(this,fe);m(this,ti,false);this.type=t,t&&c(this,Z,true),c(this,_,i),c(this,$,r(this,_)?r(r(this,_),$):this),c(this,Dt,r(this,$)===this?s:r(r(this,$),Dt)),c(this,pe,r(this,$)===this?[]:r(r(this,$),pe)),t==="!"&&!r(r(this,$),ee)&&r(this,pe).push(this),c(this,te,r(this,_)?r(r(this,_),W).length:0);}get hasMagic(){if(r(this,Z)!==void 0)return r(this,Z);for(let t of r(this,W))if(typeof t!="string"&&(t.type||t.hasMagic))return c(this,Z,true);return r(this,Z)}toString(){return r(this,fe)!==void 0?r(this,fe):this.type?c(this,fe,this.type+"("+r(this,W).map(t=>String(t)).join("|")+")"):c(this,fe,r(this,W).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof Y&&r(i,_)===this))throw new Error("invalid part: "+i);r(this,W).push(i);}}toJSON(){let t=this.type===null?r(this,W).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...r(this,W).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===r(this,$)||r(r(this,$),ee)&&r(this,_)?.type==="!")&&t.push({}),t}isStart(){if(r(this,$)===this)return true;if(!r(this,_)?.isStart())return false;if(r(this,te)===0)return true;let t=r(this,_);for(let i=0;i<r(this,te);i++){let s=r(t,W)[i];if(!(s instanceof Y&&s.type==="!"))return false}return true}isEnd(){if(r(this,$)===this||r(this,_)?.type==="!")return true;if(!r(this,_)?.isEnd())return false;if(!this.type)return r(this,_)?.isEnd();let t=r(this,_)?r(r(this,_),W).length:0;return r(this,te)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new Y(this.type,t);for(let s of r(this,W))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new Y(null,void 0,i);return g(h=Y,oe,Wi).call(h,t,s,0,i),s}toMMPattern(){if(this!==r(this,$))return r(this,$).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||r(this,Z)||r(this,Dt).nocase&&!r(this,Dt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(r(this,Dt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return r(this,Dt)}toRegExpSource(t){let i=t??!!r(this,Dt).dot;if(r(this,$)===this&&g(this,Ee,Or).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!r(this,W).some(w=>typeof w!="string"),u=r(this,W).map(w=>{var E;let[v,S,y,x]=typeof w=="string"?g(E=Y,oe,Ar).call(E,w,r(this,Z),l):w.toRegExpSource(t);return c(this,Z,r(this,Z)||y),c(this,$t,r(this,$t)||x),v}).join(""),d="";if(this.isStart()&&typeof r(this,W)[0]=="string"&&!(r(this,W).length===1&&Uh.has(r(this,W)[0]))){let w=$h,v=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),S=!i&&!t&&w.has(u.charAt(0));d=v?Bh:S?Ci:"";}let f="";return this.isEnd()&&r(r(this,$),ee)&&r(this,_)?.type==="!"&&(f="(?:$|\\/)"),[d+u+f,Oe(u),c(this,Z,!!r(this,Z)),r(this,$t)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=g(this,Ee,ns).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return c(this,W,[l]),this.type=null,c(this,Z,void 0),[l,Oe(this.toString()),false,false]}let o=!s||t||i||!Ci?"":g(this,Ee,ns).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&r(this,ti))a=(this.isStart()&&!i?Ci:"")+Ls;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?Ci:"")+Ms+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Oe(n),c(this,Z,!!r(this,Z)),r(this,$t)]}},$=new WeakMap,Z=new WeakMap,$t=new WeakMap,W=new WeakMap,_=new WeakMap,te=new WeakMap,pe=new WeakMap,ee=new WeakMap,Dt=new WeakMap,fe=new WeakMap,ti=new WeakMap,Ee=new WeakSet,Or=function(){if(this!==r(this,$))throw new Error("should only call on root");if(r(this,ee))return this;this.toString(),c(this,ee,true);let t;for(;t=r(this,pe).pop();){if(t.type!=="!")continue;let i=t,s=r(i,_);for(;s;){for(let h=r(i,te)+1;!s.type&&h<r(s,W).length;h++)for(let n of r(t,W)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(r(s,W)[h]);}i=s,s=r(i,_);}}return this},oe=new WeakSet,Wi=function(t,i,s,h){var v,S;let n=false,o=false,a=-1,l=false;if(i.type===null){let y=s,x="";for(;y<t.length;){let E=t.charAt(y++);if(n||E==="\\"){n=!n,x+=E;continue}if(o){y===a+1?(E==="^"||E==="!")&&(l=true):E==="]"&&!(y===a+2&&l)&&(o=false),x+=E;continue}else if(E==="["){o=true,a=y,l=false,x+=E;continue}if(!h.noext&&Fs(E)&&t.charAt(y)==="("){i.push(x),x="";let O=new Y(E,i);y=g(v=Y,oe,Wi).call(v,t,O,y,h),i.push(O);continue}x+=E;}return i.push(x),y}let u=s+1,d=new Y(null,i),f=[],w="";for(;u<t.length;){let y=t.charAt(u++);if(n||y==="\\"){n=!n,w+=y;continue}if(o){u===a+1?(y==="^"||y==="!")&&(l=true):y==="]"&&!(u===a+2&&l)&&(o=false),w+=y;continue}else if(y==="["){o=true,a=u,l=false,w+=y;continue}if(Fs(y)&&t.charAt(u)==="("){d.push(w),w="";let x=new Y(y,d);d.push(x),u=g(S=Y,oe,Wi).call(S,t,x,u,h);continue}if(y==="|"){d.push(w),w="",f.push(d),d=new Y(null,i);continue}if(y===")")return w===""&&r(i,W).length===0&&c(i,ti,true),d.push(w),w="",i.push(...f,d),u;w+=y;}return i.type=null,c(i,Z,void 0),c(i,W,[t.substring(s-1)]),u},ns=function(t){return r(this,W).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return c(this,$t,r(this,$t)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},Ar=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(Ih.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?Ls:Ms,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,v]=zh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||v;continue}}if(u==="?"){n+=vs,i=true;continue}n+=Gh(u);}return [n,Oe(t),!!i,o]},m(Y,oe),Y),Tr=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),ht=(e,t,i={})=>($i(t),!i.nocomment&&t.charAt(0)==="#"?false:new ae(t,i).match(e)),Hh=/^\*+([^+@!?\*\[\(]*)$/,Jh=e=>t=>!t.startsWith(".")&&t.endsWith(e),qh=e=>t=>t.endsWith(e),Zh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Vh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Kh=/^\*+\.\*+$/,Yh=e=>!e.startsWith(".")&&e.includes("."),Xh=e=>e!=="."&&e!==".."&&e.includes("."),Qh=/^\.\*+$/,tn=e=>e!=="."&&e!==".."&&e.startsWith("."),en=/^\*+$/,sn=e=>e.length!==0&&!e.startsWith("."),rn=e=>e.length!==0&&e!=="."&&e!=="..",hn=/^\?+([^+@!?\*\[\(]*)?$/,nn=([e,t=""])=>{let i=Fr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},on=([e,t=""])=>{let i=Mr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},an=([e,t=""])=>{let i=Mr([e]);return t?s=>i(s)&&s.endsWith(t):i},ln=([e,t=""])=>{let i=Fr([e]);return t?s=>i(s)&&s.endsWith(t):i},Fr=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Mr=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Lr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ws={win32:{sep:"\\"},posix:{sep:"/"}},cn=Lr==="win32"?Ws.win32.sep:Ws.posix.sep;ht.sep=cn;var rt=Symbol("globstar **");ht.GLOBSTAR=rt;var un="[^/]",pn=un+"*?",fn="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",dn="(?:(?!(?:\\/|^)\\.).)*?",gn=(e,t={})=>i=>ht(i,e,t);ht.filter=gn;var wt=(e,t={})=>Object.assign({},e,t),mn=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return ht;let t=ht;return Object.assign((i,s,h={})=>t(i,s,wt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,wt(e,s));}static defaults(i){return t.defaults(wt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,wt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,wt(e,s))}},unescape:(i,s={})=>t.unescape(i,wt(e,s)),escape:(i,s={})=>t.escape(i,wt(e,s)),filter:(i,s={})=>t.filter(i,wt(e,s)),defaults:i=>t.defaults(wt(e,i)),makeRe:(i,s={})=>t.makeRe(i,wt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,wt(e,s)),match:(i,s,h={})=>t.match(i,s,wt(e,h)),sep:t.sep,GLOBSTAR:rt})};ht.defaults=mn;var Wr=(e,t={})=>($i(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Mh(e,{max:t.braceExpandMax}));ht.braceExpand=Wr;var wn=(e,t={})=>new ae(e,t).makeRe();ht.makeRe=wn;var yn=(e,t,i={})=>{let s=new ae(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};ht.match=yn;var Ps=/[?*]|[+@!]\(.*?\)|\[|\]/,bn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ae=class{constructor(e,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");$i(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Lr,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ps.test(h[2]))&&!Ps.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let S=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!S&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),E=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),O=y?3:S?0:void 0,A=E?3:x?0:void 0;if(typeof O=="number"&&typeof A=="number"){let[F,M]=[e[O],t[A]];F.toLowerCase()===M.toLowerCase()&&(t[A]=F,A>O?t=t.slice(A):O>A&&(e=e.slice(O)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===rt){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var v=e[f];if(this.debug(`
2
- globstar while`,e,f,t,w,v),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,v),true;if(v==="."||v===".."||!s.dot&&v.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
3
- >>> no match, partial?`,e,f,t,w),f===a))}let S;if(typeof u=="string"?(S=d===u,this.debug("string match",u,d,S)):(S=u.test(d),this.debug("pattern match",u,d,S)),!S)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Wr(this.pattern,this.options)}parse(e){$i(e);let t=this.options;if(e==="**")return rt;if(e==="")return "";let i,s=null;(i=e.match(en))?s=t.dot?rn:sn:(i=e.match(Hh))?s=(t.nocase?t.dot?Vh:Zh:t.dot?qh:Jh)(i[1]):(i=e.match(hn))?s=(t.nocase?t.dot?on:nn:t.dot?an:ln)(i):(i=e.match(Kh))?s=t.dot?Xh:Yh:(i=e.match(Qh))&&(s=tn);let h=Rr.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?pn:t.dot?fn:dn,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?bn(d):d===rt?rt:d._src});l.forEach((d,f)=>{let w=l[f+1],v=l[f-1];d!==rt||v===rt||(v===void 0?w!==void 0&&w!==rt?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=v+"(?:\\/|\\/"+i+")?":w!==rt&&(l[f-1]=v+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=rt));});let u=l.filter(d=>d!==rt);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return ht.defaults(e).Minimatch}};ht.AST=Rr;ht.Minimatch=ae;ht.escape=Tr;ht.unescape=Oe;var vn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Pr=new Set,os=typeof process=="object"&&process?process:{},Dr=(e,t,i,s)=>{typeof os.emitWarning=="function"?os.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Ui=globalThis.AbortController,Ds=globalThis.AbortSignal;if(typeof Ui>"u"){Ds=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Ui=class{constructor(){p(this,"signal",new Ds);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e=os.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Dr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var En=e=>!Pr.has(e),Kt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),jr=e=>Kt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Pi:null:null,Pi=class extends Array{constructor(e){super(e),this.fill(0);}},zt,Ae,xn=(zt=class{constructor(t,i){p(this,"heap");p(this,"length");if(!r(zt,Ae))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=jr(t);if(!i)return [];c(zt,Ae,true);let s=new zt(t,i);return c(zt,Ae,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Ae=new WeakMap,m(zt,Ae,false),zt),Ks,Ys,bt,ut,kt,de,Ct,Te,Fe,Rt,U,Ot,B,P,R,et,pt,Q,V,At,K,Tt,Ft,ft,dt,Mt,ie,it,Me,b,as,ge,Ut,ei,gt,Nr,me,Le,ii,Yt,Xt,ls,Di,ji,L,cs,Ze,Qt,us,We,Hi=(We=class{constructor(t){m(this,b);m(this,bt);m(this,ut);m(this,kt);m(this,de);m(this,Ct);m(this,Te);m(this,Fe);m(this,Rt);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");m(this,U);m(this,Ot);m(this,B);m(this,P);m(this,R);m(this,et);m(this,pt);m(this,Q);m(this,V);m(this,At);m(this,K);m(this,Tt);m(this,Ft);m(this,ft);m(this,dt);m(this,Mt);m(this,ie);m(this,it);m(this,Me);m(this,ge,()=>{});m(this,Ut,()=>{});m(this,ei,()=>{});m(this,gt,()=>false);m(this,me,t=>{});m(this,Le,(t,i,s)=>{});m(this,ii,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Ks,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:u,onInsert:d,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:v,maxSize:S=0,maxEntrySize:y=0,sizeCalculation:x,fetchMethod:E,memoMethod:O,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:F,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:mt,ignoreFetchAbort:T,perf:D}=t;if(D!==void 0&&typeof D?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(c(this,Rt,D??vn),i!==0&&!Kt(i))throw new TypeError("max option must be a nonnegative integer");let N=i?jr(i):Array;if(!N)throw new Error("invalid max value: "+i);if(c(this,bt,i),c(this,ut,S),this.maxEntrySize=y||r(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!r(this,ut)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(O!==void 0&&typeof O!="function")throw new TypeError("memoMethod must be a function if defined");if(c(this,Fe,O),E!==void 0&&typeof E!="function")throw new TypeError("fetchMethod must be a function if specified");if(c(this,Te,E),c(this,ie,!!E),c(this,B,new Map),c(this,P,new Array(i).fill(void 0)),c(this,R,new Array(i).fill(void 0)),c(this,et,new N(i)),c(this,pt,new N(i)),c(this,Q,0),c(this,V,0),c(this,At,xn.create(i)),c(this,U,0),c(this,Ot,0),typeof u=="function"&&c(this,kt,u),typeof d=="function"&&c(this,de,d),typeof f=="function"?(c(this,Ct,f),c(this,K,[])):(c(this,Ct,void 0),c(this,K,void 0)),c(this,Mt,!!r(this,kt)),c(this,Me,!!r(this,de)),c(this,it,!!r(this,Ct)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!v,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!M,this.allowStaleOnFetchAbort=!!mt,this.ignoreFetchAbort=!!T,this.maxEntrySize!==0){if(r(this,ut)!==0&&!Kt(r(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Kt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");g(this,b,Nr).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!F,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Kt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Kt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");g(this,b,as).call(this);}if(r(this,bt)===0&&this.ttl===0&&r(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!r(this,bt)&&!r(this,ut)){let nt="LRU_CACHE_UNBOUNDED";En(nt)&&(Pr.add(nt),Dr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",nt,We));}}get perf(){return r(this,Rt)}static unsafeExposeInternals(t){return {starts:r(t,Ft),ttls:r(t,ft),autopurgeTimers:r(t,dt),sizes:r(t,Tt),keyMap:r(t,B),keyList:r(t,P),valList:r(t,R),next:r(t,et),prev:r(t,pt),get head(){return r(t,Q)},get tail(){return r(t,V)},free:r(t,At),isBackgroundFetch:i=>{var s;return g(s=t,b,L).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return g(o=t,b,ji).call(o,i,s,h,n)},moveToTail:i=>{var s;return g(s=t,b,Ze).call(s,i)},indexes:i=>{var s;return g(s=t,b,Yt).call(s,i)},rindexes:i=>{var s;return g(s=t,b,Xt).call(s,i)},isStale:i=>{var s;return r(s=t,gt).call(s,i)}}}get max(){return r(this,bt)}get maxSize(){return r(this,ut)}get calculatedSize(){return r(this,Ot)}get size(){return r(this,U)}get fetchMethod(){return r(this,Te)}get memoMethod(){return r(this,Fe)}get dispose(){return r(this,kt)}get onInsert(){return r(this,de)}get disposeAfter(){return r(this,Ct)}getRemainingTTL(t){return r(this,B).has(t)?1/0:0}*entries(){for(let t of g(this,b,Yt).call(this))r(this,R)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield [r(this,P)[t],r(this,R)[t]]);}*rentries(){for(let t of g(this,b,Xt).call(this))r(this,R)[t]!==void 0&&r(this,P)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield [r(this,P)[t],r(this,R)[t]]);}*keys(){for(let t of g(this,b,Yt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield i);}}*rkeys(){for(let t of g(this,b,Xt).call(this)){let i=r(this,P)[t];i!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield i);}}*values(){for(let t of g(this,b,Yt).call(this))r(this,R)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield r(this,R)[t]);}*rvalues(){for(let t of g(this,b,Xt).call(this))r(this,R)[t]!==void 0&&!g(this,b,L).call(this,r(this,R)[t])&&(yield r(this,R)[t]);}[(Ys=Symbol.iterator,Ks=Symbol.toStringTag,Ys)](){return this.entries()}find(t,i={}){for(let s of g(this,b,Yt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,r(this,P)[s],this))return this.get(r(this,P)[s],i)}}forEach(t,i=this){for(let s of g(this,b,Yt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}rforEach(t,i=this){for(let s of g(this,b,Xt).call(this)){let h=r(this,R)[s],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,P)[s],this);}}purgeStale(){let t=false;for(let i of g(this,b,Xt).call(this,{allowStale:true}))r(this,gt).call(this,i)&&(g(this,b,Qt).call(this,r(this,P)[i],"expire"),t=true);return t}info(t){let i=r(this,B).get(t);if(i===void 0)return;let s=r(this,R)[i],h=g(this,b,L).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(r(this,ft)&&r(this,Ft)){let o=r(this,ft)[i],a=r(this,Ft)[i];if(o&&a){let l=o-(r(this,Rt).now()-a);n.ttl=l,n.start=Date.now();}}return r(this,Tt)&&(n.size=r(this,Tt)[i]),n}dump(){let t=[];for(let i of g(this,b,Yt).call(this,{allowStale:true})){let s=r(this,P)[i],h=r(this,R)[i],n=g(this,b,L).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(r(this,ft)&&r(this,Ft)){o.ttl=r(this,ft)[i];let a=r(this,Rt).now()-r(this,Ft)[i];o.start=Math.floor(Date.now()-a);}r(this,Tt)&&(o.size=r(this,Tt)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=r(this,Rt).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,v,S,y;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d=r(this,ii).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),g(this,b,Qt).call(this,t,"set"),this;let f=r(this,U)===0?void 0:r(this,B).get(t);if(f===void 0)f=r(this,U)===0?r(this,V):r(this,At).length!==0?r(this,At).pop():r(this,U)===r(this,bt)?g(this,b,Di).call(this,false):r(this,U),r(this,P)[f]=t,r(this,R)[f]=i,r(this,B).set(t,f),r(this,et)[r(this,V)]=f,r(this,pt)[f]=r(this,V),c(this,V,f),ki(this,U)._++,r(this,Le).call(this,f,d,l),l&&(l.set="add"),u=false,r(this,Me)&&((w=r(this,de))==null||w.call(this,i,t,"add"));else {g(this,b,Ze).call(this,f);let x=r(this,R)[f];if(i!==x){if(r(this,ie)&&g(this,b,L).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:E}=x;E!==void 0&&!o&&(r(this,Mt)&&((v=r(this,kt))==null||v.call(this,E,t,"set")),r(this,it)&&r(this,K)?.push([E,t,"set"]));}else o||(r(this,Mt)&&((S=r(this,kt))==null||S.call(this,x,t,"set")),r(this,it)&&r(this,K)?.push([x,t,"set"]));if(r(this,me).call(this,f),r(this,Le).call(this,f,d,l),r(this,R)[f]=i,l){l.set="replace";let E=x&&g(this,b,L).call(this,x)?x.__staleWhileFetching:x;E!==void 0&&(l.oldValue=E);}}else l&&(l.set="update");r(this,Me)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!r(this,ft)&&g(this,b,as).call(this),r(this,ft)&&(u||r(this,ei).call(this,f,h,n),l&&r(this,Ut).call(this,l,f)),!o&&r(this,it)&&r(this,K)){let x=r(this,K),E;for(;E=x?.shift();)(y=r(this,Ct))==null||y.call(this,...E);}return this}pop(){var t;try{for(;r(this,U);){let i=r(this,R)[r(this,Q)];if(g(this,b,Di).call(this,!0),g(this,b,L).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(r(this,it)&&r(this,K)){let i=r(this,K),s;for(;s=i?.shift();)(t=r(this,Ct))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=r(this,B).get(t);if(n!==void 0){let o=r(this,R)[n];if(g(this,b,L).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(r(this,gt).call(this,n))h&&(h.has="stale",r(this,Ut).call(this,h,n));else return s&&r(this,ge).call(this,n),h&&(h.has="hit",r(this,Ut).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=r(this,B).get(t);if(h===void 0||!s&&r(this,gt).call(this,h))return;let n=r(this,R)[h];return g(this,b,L).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:v=this.ignoreFetchAbort,allowStaleOnFetchAbort:S=this.allowStaleOnFetchAbort,context:y,forceRefresh:x=false,status:E,signal:O}=i;if(!r(this,ie))return E&&(E.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:E});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:S,ignoreFetchAbort:v,status:E,signal:O},F=r(this,B).get(t);if(F===void 0){E&&(E.fetch="miss");let M=g(this,b,ji).call(this,t,F,A,y);return M.__returned=M}else {let M=r(this,R)[F];if(g(this,b,L).call(this,M)){let N=s&&M.__staleWhileFetching!==void 0;return E&&(E.fetch="inflight",N&&(E.returnedStale=true)),N?M.__staleWhileFetching:M.__returned=M}let mt=r(this,gt).call(this,F);if(!x&&!mt)return E&&(E.fetch="hit"),g(this,b,Ze).call(this,F),h&&r(this,ge).call(this,F),E&&r(this,Ut).call(this,E,F),M;let T=g(this,b,ji).call(this,t,F,A,y),D=T.__staleWhileFetching!==void 0&&s;return E&&(E.fetch=mt?"stale":"refresh",D&&mt&&(E.returnedStale=true)),D?T.__staleWhileFetching:T.__returned=T}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=r(this,Fe);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=r(this,B).get(t);if(a!==void 0){let l=r(this,R)[a],u=g(this,b,L).call(this,l);return o&&r(this,Ut).call(this,o,a),r(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||g(this,b,Qt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(g(this,b,Ze).call(this,a),h&&r(this,ge).call(this,a),l))}else o&&(o.get="miss");}delete(t){return g(this,b,Qt).call(this,t,"delete")}clear(){return g(this,b,us).call(this,"delete")}},bt=new WeakMap,ut=new WeakMap,kt=new WeakMap,de=new WeakMap,Ct=new WeakMap,Te=new WeakMap,Fe=new WeakMap,Rt=new WeakMap,U=new WeakMap,Ot=new WeakMap,B=new WeakMap,P=new WeakMap,R=new WeakMap,et=new WeakMap,pt=new WeakMap,Q=new WeakMap,V=new WeakMap,At=new WeakMap,K=new WeakMap,Tt=new WeakMap,Ft=new WeakMap,ft=new WeakMap,dt=new WeakMap,Mt=new WeakMap,ie=new WeakMap,it=new WeakMap,Me=new WeakMap,b=new WeakSet,as=function(){let t=new Pi(r(this,bt)),i=new Pi(r(this,bt));c(this,ft,t),c(this,Ft,i);let s=this.ttlAutopurge?new Array(r(this,bt)):void 0;c(this,dt,s),c(this,ei,(o,a,l=r(this,Rt).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{r(this,gt).call(this,o)&&g(this,b,Qt).call(this,r(this,P)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),c(this,ge,o=>{i[o]=t[o]!==0?r(this,Rt).now():0;}),c(this,Ut,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=r(this,Rt).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=r(this,B).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},c(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},ge=new WeakMap,Ut=new WeakMap,ei=new WeakMap,gt=new WeakMap,Nr=function(){let t=new Pi(r(this,bt));c(this,Ot,0),c(this,Tt,t),c(this,me,i=>{c(this,Ot,r(this,Ot)-t[i]),t[i]=0;}),c(this,ii,(i,s,h,n)=>{if(g(this,b,L).call(this,s))return 0;if(!Kt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Kt(h))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return h}),c(this,Le,(i,s,h)=>{if(t[i]=s,r(this,ut)){let n=r(this,ut)-t[i];for(;r(this,Ot)>n;)g(this,b,Di).call(this,true);}c(this,Ot,r(this,Ot)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=r(this,Ot));});},me=new WeakMap,Le=new WeakMap,ii=new WeakMap,Yt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,V);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,Q)));)i=r(this,pt)[i];},Xt=function*({allowStale:t=this.allowStale}={}){if(r(this,U))for(let i=r(this,Q);!(!g(this,b,ls).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,V)));)i=r(this,et)[i];},ls=function(t){return t!==void 0&&r(this,B).get(r(this,P)[t])===t},Di=function(t){var n;let i=r(this,Q),s=r(this,P)[i],h=r(this,R)[i];return r(this,ie)&&g(this,b,L).call(this,h)?h.__abortController.abort(new Error("evicted")):(r(this,Mt)||r(this,it))&&(r(this,Mt)&&((n=r(this,kt))==null||n.call(this,h,s,"evict")),r(this,it)&&r(this,K)?.push([h,s,"evict"])),r(this,me).call(this,i),r(this,dt)?.[i]&&(clearTimeout(r(this,dt)[i]),r(this,dt)[i]=void 0),t&&(r(this,P)[i]=void 0,r(this,R)[i]=void 0,r(this,At).push(i)),r(this,U)===1?(c(this,Q,c(this,V,0)),r(this,At).length=0):c(this,Q,r(this,et)[i]),r(this,B).delete(s),ki(this,U)._--,i},ji=function(t,i,s,h){let n=i===void 0?void 0:r(this,R)[i];if(g(this,b,L).call(this,n))return n;let o=new Ui,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(y,x=false)=>{let{aborted:E}=o.signal,O=s.ignoreFetchAbort&&y!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&y!==void 0);if(s.status&&(E&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,O&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),E&&!O&&!x)return f(o.signal.reason,A);let F=v,M=r(this,R)[i];return (M===v||O&&x&&M===void 0)&&(y===void 0?F.__staleWhileFetching!==void 0?r(this,R)[i]=F.__staleWhileFetching:g(this,b,Qt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,y,l.options))),y},d=y=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=y),f(y,false)),f=(y,x)=>{let{aborted:E}=o.signal,O=E&&s.allowStaleOnFetchAbort,A=O||s.allowStaleOnFetchRejection,F=A||s.noDeleteOnFetchRejection,M=v;if(r(this,R)[i]===v&&(!F||!x&&M.__staleWhileFetching===void 0?g(this,b,Qt).call(this,t,"fetch"):O||(r(this,R)[i]=M.__staleWhileFetching)),A)return s.status&&M.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),M.__staleWhileFetching;if(M.__returned===M)throw y},w=(y,x)=>{var O;let E=(O=r(this,Te))==null?void 0:O.call(this,t,n,l);E&&E instanceof Promise&&E.then(A=>y(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(y(void 0),s.allowStaleOnFetchAbort&&(y=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let v=new Promise(w).then(u,d),S=Object.assign(v,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,S,{...l.options,status:void 0}),i=r(this,B).get(t)):r(this,R)[i]=S,S},L=function(t){if(!r(this,ie))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Ui},cs=function(t,i){r(this,pt)[i]=t,r(this,et)[t]=i;},Ze=function(t){t!==r(this,V)&&(t===r(this,Q)?c(this,Q,r(this,et)[t]):g(this,b,cs).call(this,r(this,pt)[t],r(this,et)[t]),g(this,b,cs).call(this,r(this,V),t),c(this,V,t));},Qt=function(t,i){var h,n;let s=false;if(r(this,U)!==0){let o=r(this,B).get(t);if(o!==void 0)if(r(this,dt)?.[o]&&(clearTimeout(r(this,dt)?.[o]),r(this,dt)[o]=void 0),s=true,r(this,U)===1)g(this,b,us).call(this,i);else {r(this,me).call(this,o);let a=r(this,R)[o];if(g(this,b,L).call(this,a)?a.__abortController.abort(new Error("deleted")):(r(this,Mt)||r(this,it))&&(r(this,Mt)&&((h=r(this,kt))==null||h.call(this,a,t,i)),r(this,it)&&r(this,K)?.push([a,t,i])),r(this,B).delete(t),r(this,P)[o]=void 0,r(this,R)[o]=void 0,o===r(this,V))c(this,V,r(this,pt)[o]);else if(o===r(this,Q))c(this,Q,r(this,et)[o]);else {let l=r(this,pt)[o];r(this,et)[l]=r(this,et)[o];let u=r(this,et)[o];r(this,pt)[u]=r(this,pt)[o];}ki(this,U)._--,r(this,At).push(o);}}if(r(this,it)&&r(this,K)?.length){let o=r(this,K),a;for(;a=o?.shift();)(n=r(this,Ct))==null||n.call(this,...a);}return s},us=function(t){var i,s;for(let h of g(this,b,Xt).call(this,{allowStale:true})){let n=r(this,R)[h];if(g(this,b,L).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=r(this,P)[h];r(this,Mt)&&((i=r(this,kt))==null||i.call(this,n,o,t)),r(this,it)&&r(this,K)?.push([n,o,t]);}}if(r(this,B).clear(),r(this,R).fill(void 0),r(this,P).fill(void 0),r(this,ft)&&r(this,Ft)){r(this,ft).fill(0),r(this,Ft).fill(0);for(let h of r(this,dt)??[])h!==void 0&&clearTimeout(h);r(this,dt)?.fill(void 0);}if(r(this,Tt)&&r(this,Tt).fill(0),c(this,Q,0),c(this,V,0),r(this,At).length=0,c(this,Ot,0),c(this,U,0),r(this,it)&&r(this,K)){let h=r(this,K),n;for(;n=h?.shift();)(s=r(this,Ct))==null||s.call(this,...n);}},We),js=typeof process=="object"&&process?process:{stdout:null,stderr:null},Nn=e=>!!e&&typeof e=="object"&&(e instanceof Ii||e instanceof zr__default.default||zn(e)||_n(e)),zn=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==zr__default.default.Writable.prototype.pipe,_n=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",_t=Symbol("EOF"),Bt=Symbol("maybeEmitEnd"),Vt=Symbol("emittedEnd"),Ri=Symbol("emittingEnd"),Ue=Symbol("emittedError"),Oi=Symbol("closed"),Ns=Symbol("read"),Ai=Symbol("flush"),zs=Symbol("flushChunk"),Et=Symbol("encoding"),Ce=Symbol("decoder"),H=Symbol("flowing"),Ie=Symbol("paused"),Re=Symbol("resume"),J=Symbol("buffer"),tt=Symbol("pipes"),q=Symbol("bufferLength"),Qi=Symbol("bufferPush"),Ti=Symbol("bufferShift"),X=Symbol("objectMode"),z=Symbol("destroyed"),ts=Symbol("error"),es=Symbol("emitData"),_s=Symbol("emitEnd"),is=Symbol("emitEnd2"),Wt=Symbol("async"),ss=Symbol("abort"),Fi=Symbol("aborted"),Ge=Symbol("signal"),le=Symbol("dataListeners"),ct=Symbol("discarded"),He=e=>Promise.resolve().then(e),Bn=e=>e(),$n=e=>e==="end"||e==="finish"||e==="prefinish",Un=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,In=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),_r=class{constructor(e,t,i){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Re](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Gn=class extends _r{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},Hn=e=>!!e.objectMode,Jn=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,fr,dr,gr,mr,Ii=class extends events.EventEmitter{constructor(...t){let i=t[0]||{};super();p(this,mr,false);p(this,gr,false);p(this,dr,[]);p(this,fr,[]);p(this,pr);p(this,ur);p(this,cr);p(this,lr);p(this,ar,false);p(this,or,false);p(this,nr,false);p(this,hr,false);p(this,rr,null);p(this,sr,0);p(this,ir,false);p(this,er);p(this,tr,false);p(this,Qs,0);p(this,Xs,false);p(this,"writable",true);p(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Hn(i)?(this[X]=true,this[Et]=null):Jn(i)?(this[Et]=i.encoding,this[X]=false):(this[X]=false,this[Et]=null),this[Wt]=!!i.async,this[Ce]=this[Et]?new string_decoder.StringDecoder(this[Et]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[J]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[tt]});let{signal:s}=i;s&&(this[Ge]=s,s.aborted?this[ss]():s.addEventListener("abort",()=>this[ss]()));}get bufferLength(){return this[q]}get encoding(){return this[Et]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[X]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Wt]}set async(t){this[Wt]=this[Wt]||!!t;}[(mr=H,gr=Ie,dr=tt,fr=J,pr=X,ur=Et,cr=Wt,lr=Ce,ar=_t,or=Vt,nr=Ri,hr=Oi,rr=Ue,sr=q,ir=z,er=Ge,tr=Fi,Qs=le,Xs=ct,ss)](){this[Fi]=true,this.emit("abort",this[Ge]?.reason),this.destroy(this[Ge]?.reason);}get aborted(){return this[Fi]}set aborted(t){}write(t,i,s){if(this[Fi])return false;if(this[_t])throw new Error("write after end");if(this[z])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let h=this[Wt]?He:Bn;if(!this[X]&&!Buffer.isBuffer(t)){if(In(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Un(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[X]?(this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):t.length?(typeof t=="string"&&!(i===this[Et]&&!this[Ce]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[Et]&&(t=this[Ce].write(t)),this[H]&&this[q]!==0&&this[Ai](true),this[H]?this.emit("data",t):this[Qi](t),this[q]!==0&&this.emit("readable"),s&&h(s),this[H]):(this[q]!==0&&this.emit("readable"),s&&h(s),this[H])}read(t){if(this[z])return null;if(this[ct]=false,this[q]===0||t===0||t&&t>this[q])return this[Bt](),null;this[X]&&(t=null),this[J].length>1&&!this[X]&&(this[J]=[this[Et]?this[J].join(""):Buffer.concat(this[J],this[q])]);let i=this[Ns](t||null,this[J][0]);return this[Bt](),i}[Ns](t,i){if(this[X])this[Ti]();else {let s=i;t===s.length||t===null?this[Ti]():typeof s=="string"?(this[J][0]=s.slice(t),i=s.slice(0,t),this[q]-=t):(this[J][0]=s.subarray(t),i=s.subarray(0,t),this[q]-=t);}return this.emit("data",i),!this[J].length&&!this[_t]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[_t]=true,this.writable=false,(this[H]||!this[Ie])&&this[Bt](),this}[Re](){this[z]||(!this[le]&&!this[tt].length&&(this[ct]=true),this[Ie]=false,this[H]=true,this.emit("resume"),this[J].length?this[Ai]():this[_t]?this[Bt]():this.emit("drain"));}resume(){return this[Re]()}pause(){this[H]=false,this[Ie]=true,this[ct]=false;}get destroyed(){return this[z]}get flowing(){return this[H]}get paused(){return this[Ie]}[Qi](t){this[X]?this[q]+=1:this[q]+=t.length,this[J].push(t);}[Ti](){return this[X]?this[q]-=1:this[q]-=this[J][0].length,this[J].shift()}[Ai](t=false){do;while(this[zs](this[Ti]())&&this[J].length);!t&&!this[J].length&&!this[_t]&&this.emit("drain");}[zs](t){return this.emit("data",t),this[H]}pipe(t,i){if(this[z])return t;this[ct]=false;let s=this[Vt];return i=i||{},t===js.stdout||t===js.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[tt].push(i.proxyErrors?new Gn(this,t,i):new _r(this,t,i)),this[Wt]?He(()=>this[Re]()):this[Re]()),t}unpipe(t){let i=this[tt].find(s=>s.dest===t);i&&(this[tt].length===1?(this[H]&&this[le]===0&&(this[H]=false),this[tt]=[]):this[tt].splice(this[tt].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[le]++,!this[tt].length&&!this[H]&&this[Re]();else if(t==="readable"&&this[q]!==0)super.emit("readable");else if($n(t)&&this[Vt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ue]){let h=i;this[Wt]?He(()=>h.call(this,this[Ue])):h.call(this,this[Ue]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[le]=this.listeners("data").length,this[le]===0&&!this[ct]&&!this[tt].length&&(this[H]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[le]=0,!this[ct]&&!this[tt].length&&(this[H]=false)),i}get emittedEnd(){return this[Vt]}[Bt](){!this[Ri]&&!this[Vt]&&!this[z]&&this[J].length===0&&this[_t]&&(this[Ri]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Oi]&&this.emit("close"),this[Ri]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return false;if(t==="data")return !this[X]&&!s?false:this[Wt]?(He(()=>this[es](s)),true):this[es](s);if(t==="end")return this[_s]();if(t==="close"){if(this[Oi]=true,!this[Vt]&&!this[z])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Ue]=s,super.emit(ts,s);let n=!this[Ge]||this.listeners("error").length?super.emit("error",s):false;return this[Bt](),n}else if(t==="resume"){let n=super.emit("resume");return this[Bt](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[Bt](),h}[es](t){for(let s of this[tt])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[Bt](),i}[_s](){return this[Vt]?false:(this[Vt]=true,this.readable=false,this[Wt]?(He(()=>this[is]()),true):this[is]())}[is](){if(this[Ce]){let i=this[Ce].end();if(i){for(let s of this[tt])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[tt])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[X]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[X]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[X])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Et]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(z,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[_t])return i();let h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(z,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(z,u),this.pause(),h({value:d,done:!!this[_t]});},l=()=>{this.off("error",o),this.off("data",a),this.off(z,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(z,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(ts,i),this.off(z,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(ts,i),this.once(z,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=true,this[ct]=true,this[J].length=0,this[q]=0;let i=this;return typeof i.close=="function"&&!this[Oi]&&i.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return Nn}},qn=Mn.realpathSync.native,Ve={lstatSync:Mn.lstatSync,readdir:Mn.readdir,readdirSync:Mn.readdirSync,readlinkSync:Mn.readlinkSync,realpathSync:qn,promises:{lstat:uh.lstat,readdir:uh.readdir,readlink:uh.readlink,realpath:uh.realpath}},Br=e=>!e||e===Ve||e===Mn__namespace?Ve:{...Ve,...e,promises:{...Ve.promises,...e.promises||{}}},$r=/^\\\\\?\\([a-z]:)\\?$/i,Zn=e=>e.replace(/\//g,"\\").replace($r,"$1\\"),Vn=/[\\\/]/,St=0,Ur=1,Ir=2,Pt=4,Gr=6,Hr=8,ce=10,Jr=12,yt=15,Je=~yt,rs=16,Bs=32,Ke=64,xt=128,Mi=256,Ni=512,$s=Ke|xt|Ni,Kn=1023,hs=e=>e.isFile()?Hr:e.isDirectory()?Pt:e.isSymbolicLink()?ce:e.isCharacterDevice()?Ir:e.isBlockDevice()?Gr:e.isSocket()?Jr:e.isFIFO()?Ur:St,Us=new Hi({max:2**12}),Ye=e=>{let t=Us.get(e);if(t)return t;let i=e.normalize("NFKD");return Us.set(e,i),i},Is=new Hi({max:2**12}),Li=e=>{let t=Is.get(e);if(t)return t;let i=Ye(e.toLowerCase());return Is.set(e,i),i},Gs=class extends Hi{constructor(){super({max:256});}},Yn=class extends Hi{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},qr=Symbol("PathScurry setAsCwd"),st,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,Si,se,we,jt,It,Gt,Ht,C,ye,Jt,Nt,k,fs,zi,Xe,ds,gs,Qe,_i,ms,ws,Bi,Zr,Vr,Kr,ys,Pe,De,Yr,be,wr,at=(wr=class{constructor(e,t=St,i,s,h,n,o){m(this,k);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);m(this,st);m(this,si);m(this,ri);m(this,hi);m(this,ni);m(this,oi);m(this,ai);m(this,li);m(this,ci);m(this,ui);m(this,pi);m(this,fi);m(this,di);m(this,gi);m(this,mi);m(this,wi);m(this,yi);m(this,bi);m(this,Si);m(this,se);m(this,we);m(this,jt);m(this,It);m(this,Gt);m(this,Ht);m(this,C);m(this,ye);m(this,Jt);m(this,Nt);m(this,Pe,[]);m(this,De,false);m(this,be);this.name=e,c(this,se,h?Li(e):Ye(e)),c(this,C,t&Kn),this.nocase=h,this.roots=s,this.root=i||this,c(this,ye,n),c(this,jt,o.fullpath),c(this,Gt,o.relative),c(this,Ht,o.relativePosix),this.parent=o.parent,this.parent?c(this,st,r(this.parent,st)):c(this,st,Br(o.fs));}get dev(){return r(this,si)}get mode(){return r(this,ri)}get nlink(){return r(this,hi)}get uid(){return r(this,ni)}get gid(){return r(this,oi)}get rdev(){return r(this,ai)}get blksize(){return r(this,li)}get ino(){return r(this,ci)}get size(){return r(this,ui)}get blocks(){return r(this,pi)}get atimeMs(){return r(this,fi)}get mtimeMs(){return r(this,di)}get ctimeMs(){return r(this,gi)}get birthtimeMs(){return r(this,mi)}get atime(){return r(this,wi)}get mtime(){return r(this,yi)}get ctime(){return r(this,bi)}get birthtime(){return r(this,Si)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return r(this,we)!==void 0?r(this,we):this.parent?c(this,we,this.parent.depth()+1):c(this,we,0)}childrenCache(){return r(this,ye)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i=e.substring(t.length).split(this.splitSep);return t?g(s=this.getRoot(t),k,fs).call(s,i):g(this,k,fs).call(this,i)}children(){let e=r(this,ye).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return r(this,ye).set(this,t),c(this,C,r(this,C)&~rs),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Li(e):Ye(e);for(let a of i)if(r(a,se)===s)return a;let h=this.parent?this.sep:"",n=r(this,jt)?r(this,jt)+h+e:void 0,o=this.newChild(e,St,{...t,parent:this,fullpath:n});return this.canReaddir()||c(o,C,r(o,C)|xt),i.push(o),o}relative(){if(this.isCWD)return "";if(r(this,Gt)!==void 0)return r(this,Gt);let e=this.name,t=this.parent;if(!t)return c(this,Gt,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(r(this,Ht)!==void 0)return r(this,Ht);let e=this.name,t=this.parent;if(!t)return c(this,Ht,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(r(this,jt)!==void 0)return r(this,jt);let e=this.name,t=this.parent;if(!t)return c(this,jt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return c(this,jt,i)}fullpathPosix(){if(r(this,It)!==void 0)return r(this,It);if(this.sep==="/")return c(this,It,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?c(this,It,`//?/${s}`):c(this,It,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return c(this,It,i)}isUnknown(){return (r(this,C)&yt)===St}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (r(this,C)&yt)===Hr}isDirectory(){return (r(this,C)&yt)===Pt}isCharacterDevice(){return (r(this,C)&yt)===Ir}isBlockDevice(){return (r(this,C)&yt)===Gr}isFIFO(){return (r(this,C)&yt)===Ur}isSocket(){return (r(this,C)&yt)===Jr}isSymbolicLink(){return (r(this,C)&ce)===ce}lstatCached(){return r(this,C)&Bs?this:void 0}readlinkCached(){return r(this,Jt)}realpathCached(){return r(this,Nt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(r(this,Jt))return true;if(!this.parent)return false;let e=r(this,C)&yt;return !(e!==St&&e!==ce||r(this,C)&Mi||r(this,C)&xt)}calledReaddir(){return !!(r(this,C)&rs)}isENOENT(){return !!(r(this,C)&xt)}isNamed(e){return this.nocase?r(this,se)===Li(e):r(this,se)===Ye(e)}async readlink(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await r(this,st).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}readlinkSync(){let e=r(this,Jt);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=r(this,st).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return c(this,Jt,i)}catch(t){g(this,k,ws).call(this,t.code);return}}async lstat(){if((r(this,C)&xt)===0)try{return g(this,k,ys).call(this,await r(this,st).promises.lstat(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}lstatSync(){if((r(this,C)&xt)===0)try{return g(this,k,ys).call(this,r(this,st).lstatSync(this.fullpath())),this}catch(e){g(this,k,ms).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e(null,h):queueMicrotask(()=>e(null,h));return}if(r(this,Pe).push(e),r(this,De))return;c(this,De,true);let s=this.fullpath();r(this,st).readdir(s,{withFileTypes:true},(h,n)=>{if(h)g(this,k,_i).call(this,h.code),i.provisional=0;else {for(let o of n)g(this,k,Bi).call(this,o,i);g(this,k,zi).call(this,i);}g(this,k,Yr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(r(this,be))await r(this,be);else {let i=()=>{};c(this,be,new Promise(s=>i=s));try{for(let s of await r(this,st).promises.readdir(t,{withFileTypes:!0}))g(this,k,Bi).call(this,s,e);g(this,k,zi).call(this,e);}catch(s){g(this,k,_i).call(this,s.code),e.provisional=0;}c(this,be,void 0),i();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i of r(this,st).readdirSync(t,{withFileTypes:!0}))g(this,k,Bi).call(this,i,e);g(this,k,zi).call(this,e);}catch(i){g(this,k,_i).call(this,i.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(r(this,C)&$s)return false;let e=yt&r(this,C);return e===St||e===Pt||e===ce}shouldWalk(e,t){return (r(this,C)&Pt)===Pt&&!(r(this,C)&$s)&&!e.has(this)&&(!t||t(this))}async realpath(){if(r(this,Nt))return r(this,Nt);if(!((Ni|Mi|xt)&r(this,C)))try{let e=await r(this,st).promises.realpath(this.fullpath());return c(this,Nt,this.resolve(e))}catch{g(this,k,gs).call(this);}}realpathSync(){if(r(this,Nt))return r(this,Nt);if(!((Ni|Mi|xt)&r(this,C)))try{let e=r(this,st).realpathSync(this.fullpath());return c(this,Nt,this.resolve(e))}catch{g(this,k,gs).call(this);}}[qr](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),c(s,Gt,i.join(this.sep)),c(s,Ht,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)c(s,Gt,void 0),c(s,Ht,void 0),s=s.parent;}},st=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,Si=new WeakMap,se=new WeakMap,we=new WeakMap,jt=new WeakMap,It=new WeakMap,Gt=new WeakMap,Ht=new WeakMap,C=new WeakMap,ye=new WeakMap,Jt=new WeakMap,Nt=new WeakMap,k=new WeakSet,fs=function(e){let t=this;for(let i of e)t=t.child(i);return t},zi=function(e){var t;c(this,C,r(this,C)|rs);for(let i=e.provisional;i<e.length;i++){let s=e[i];s&&g(t=s,k,Xe).call(t);}},Xe=function(){r(this,C)&xt||(c(this,C,(r(this,C)|xt)&Je),g(this,k,ds).call(this));},ds=function(){var t;let e=this.children();e.provisional=0;for(let i of e)g(t=i,k,Xe).call(t);},gs=function(){c(this,C,r(this,C)|Ni),g(this,k,Qe).call(this);},Qe=function(){if(r(this,C)&Ke)return;let e=r(this,C);(e&yt)===Pt&&(e&=Je),c(this,C,e|Ke),g(this,k,ds).call(this);},_i=function(e=""){e==="ENOTDIR"||e==="EPERM"?g(this,k,Qe).call(this):e==="ENOENT"?g(this,k,Xe).call(this):this.children().provisional=0;},ms=function(e=""){var t;e==="ENOTDIR"?g(t=this.parent,k,Qe).call(t):e==="ENOENT"&&g(this,k,Xe).call(this);},ws=function(e=""){var i;let t=r(this,C);t|=Mi,e==="ENOENT"&&(t|=xt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Je),c(this,C,t),e==="ENOTDIR"&&this.parent&&g(i=this.parent,k,Qe).call(i);},Bi=function(e,t){return g(this,k,Vr).call(this,e,t)||g(this,k,Zr).call(this,e,t)},Zr=function(e,t){let i=hs(e),s=this.newChild(e.name,i,{parent:this}),h=r(s,C)&yt;return h!==Pt&&h!==ce&&h!==St&&c(s,C,r(s,C)|Ke),t.unshift(s),t.provisional++,s},Vr=function(e,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Li(e.name):Ye(e.name))===r(s,se))return g(this,k,Kr).call(this,e,s,i,t)}},Kr=function(e,t,i,s){let h=t.name;return c(t,C,r(t,C)&Je|hs(e)),h!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},ys=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d,ino:f,mode:w,mtime:v,mtimeMs:S,nlink:y,rdev:x,size:E,uid:O}=e;c(this,wi,t),c(this,fi,i),c(this,Si,s),c(this,mi,h),c(this,li,n),c(this,pi,o),c(this,bi,a),c(this,gi,l),c(this,si,u),c(this,oi,d),c(this,ci,f),c(this,ri,w),c(this,yi,v),c(this,di,S),c(this,hi,y),c(this,ai,x),c(this,ui,E),c(this,ni,O);let A=hs(e);c(this,C,r(this,C)&Je|A|Bs),A!==St&&A!==Pt&&A!==ce&&c(this,C,r(this,C)|Ke);},Pe=new WeakMap,De=new WeakMap,Yr=function(e){c(this,De,false);let t=r(this,Pe).slice();r(this,Pe).length=0,t.forEach(i=>i(null,e));},be=new WeakMap,wr),Xr=class Qr extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"sep","\\");p(this,"splitSep",Vn);}newChild(i,s=St,h={}){return new Qr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return Zi.win32.parse(i).root}getRoot(i){if(i=Zn(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new xs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace($r,"$1\\"),i===s}},th=class eh extends at{constructor(i,s=St,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"splitSep","/");p(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=St,h={}){return new eh(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},je,Ne,vi,Ei,yr,ih=(yr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ve}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");m(this,je);m(this,Ne);m(this,vi);p(this,"nocase");m(this,Ei);c(this,Ei,Br(n)),(e instanceof URL||e.startsWith("file://"))&&(e=url.fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),c(this,je,new Gs),c(this,Ne,new Gs),c(this,vi,new Yn(h));let a=o.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(r(this,Ei)),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,d=t.sep,f=this.rootPath,w=false;for(let v of a){let S=u--;l=l.child(v,{relative:new Array(S).fill("..").join(d),relativePosix:new Array(S).fill("..").join("/"),fullpath:f+=(w?"":d)+v}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return r(this,vi)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return r(this,je).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,Ne).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return r(this,Ne).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,v)=>{if(w)return f(w);let S=v.length;if(!S)return f();let y=()=>{--S===0&&f();};for(let x of v)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(E=>E?.isUnknown()?E.lstat():E).then(E=>E?.shouldWalk(a,n)?l(E,y):y()):x.shouldWalk(a,n)?l(x,y):y();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ii({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=(y,x,E=false)=>{if(y)return o.emit("error",y);if(s&&!E){let O=[];for(let A of x)A.isSymbolicLink()&&O.push(A.realpath().then(F=>F?.isUnknown()?F.lstat():F));if(O.length){Promise.all(O).then(()=>v(null,x,true));return}}for(let O of x)O&&(!h||h(O))&&(o.write(i?O:O.fullpath())||(f=true));u--;for(let O of x){let A=O.realpathCached()||O;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):S||d();},S=true;w.readdirCB(v,true),S=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ii({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let v=w.readdirSync();for(let S of v)(!h||h(S))&&(o.write(i?S:S.fullpath())||(f=true));u--;for(let S of v){let y=S;if(S.isSymbolicLink()){if(!(s&&(y=S.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(a,n)&&l.push(y);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[qr](t);}},je=new WeakMap,Ne=new WeakMap,vi=new WeakMap,Ei=new WeakMap,yr),xs=class extends ih{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,Zi.win32,"\\",{...i,nocase:s});p(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return Zi.win32.parse(t).root.toUpperCase()}newRoot(t){return new Xr(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},ks=class extends ih{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,Zi.posix,"/",{...i,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new th(this.rootPath,Pt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},sh=class extends ks{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Xr:th;var Xn=process.platform==="win32"?xs:process.platform==="darwin"?sh:ks,Qn=e=>e.length>=1,to=e=>e.length>=1,eo=Symbol.for("nodejs.util.inspect.custom"),I,lt,G,Se,Lt,xi,re,he,ne,ze,_e,rh=(_e=class{constructor(t,i,s,h){m(this,I);m(this,lt);m(this,G);p(this,"length");m(this,Se);m(this,Lt);m(this,xi);m(this,re);m(this,he);m(this,ne);m(this,ze,true);if(!Qn(t))throw new TypeError("empty pattern list");if(!to(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(c(this,I,t),c(this,lt,i),c(this,G,s),c(this,Se,h),r(this,G)===0){if(this.isUNC()){let[n,o,a,l,...u]=r(this,I),[d,f,w,v,...S]=r(this,lt);u[0]===""&&(u.shift(),S.shift());let y=[n,o,a,l,""].join("/"),x=[d,f,w,v,""].join("/");c(this,I,[y,...u]),c(this,lt,[x,...S]),this.length=r(this,I).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=r(this,I),[a,...l]=r(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d=a+"/";c(this,I,[u,...o]),c(this,lt,[d,...l]),this.length=r(this,I).length;}}}[eo](){return "Pattern <"+r(this,lt).slice(r(this,G)).join("/")+">"}pattern(){return r(this,I)[r(this,G)]}isString(){return typeof r(this,I)[r(this,G)]=="string"}isGlobstar(){return r(this,I)[r(this,G)]===rt}isRegExp(){return r(this,I)[r(this,G)]instanceof RegExp}globString(){return c(this,xi,r(this,xi)||(r(this,G)===0?this.isAbsolute()?r(this,lt)[0]+r(this,lt).slice(1).join("/"):r(this,lt).join("/"):r(this,lt).slice(r(this,G)).join("/")))}hasMore(){return this.length>r(this,G)+1}rest(){return r(this,Lt)!==void 0?r(this,Lt):this.hasMore()?(c(this,Lt,new _e(r(this,I),r(this,lt),r(this,G)+1,r(this,Se))),c(r(this,Lt),ne,r(this,ne)),c(r(this,Lt),he,r(this,he)),c(r(this,Lt),re,r(this,re)),r(this,Lt)):c(this,Lt,null)}isUNC(){let t=r(this,I);return r(this,he)!==void 0?r(this,he):c(this,he,r(this,Se)==="win32"&&r(this,G)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=r(this,I);return r(this,re)!==void 0?r(this,re):c(this,re,r(this,Se)==="win32"&&r(this,G)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=r(this,I);return r(this,ne)!==void 0?r(this,ne):c(this,ne,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=r(this,I)[0];return typeof t=="string"&&this.isAbsolute()&&r(this,G)===0?t:""}checkFollowGlobstar(){return !(r(this,G)===0||!this.isGlobstar()||!r(this,ze))}markFollowGlobstar(){return r(this,G)===0||!this.isGlobstar()||!r(this,ze)?false:(c(this,ze,false),true)}},I=new WeakMap,lt=new WeakMap,G=new WeakMap,Se=new WeakMap,Lt=new WeakMap,xi=new WeakMap,re=new WeakMap,he=new WeakMap,ne=new WeakMap,ze=new WeakMap,_e),io=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Hs=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=io}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new ae(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new rh(s,h,0,this.platform),o=new ae(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},so=class hh{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new hh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},ro=class{constructor(){p(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ho=class{constructor(){p(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Js=class nh{constructor(t,i){p(this,"hasWalkedCache");p(this,"matches",new ro);p(this,"subwalks",new ho);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new so;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===rt){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let v=h.parent||h;w?this.hasWalkedCache.hasWalked(v,w)||this.subwalks.add(v,w):this.matches.add(v,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new nh(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===rt?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},no=(e,t)=>typeof e=="string"?new Hs([e],t):Array.isArray(e)?new Hs(e,t):e,Be,qt,ve,vt,ue,bs,br,oh=(br=class{constructor(e,t,i){m(this,vt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);m(this,Be,[]);m(this,qt);m(this,ve);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,c(this,ve,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(c(this,qt,no(i.ignore??[],i)),!this.includeChildMatches&&typeof r(this,qt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{r(this,Be).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=r(this,Be).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?r(this,Be).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!g(this,vt,ue).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(g(this,vt,ue).call(this,e))return;if(!this.includeChildMatches&&r(this,qt)?.add){let h=`${e.relativePosix()}/**`;r(this,qt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?r(this,ve):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i){let h=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+r(this,ve))?"."+r(this,ve):"";this.matchEmit(h?n+h+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new Js(this.opts),i);}walkCB2(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Js(this.opts),i);}walkCB2Sync(e,t,i,s){if(g(this,vt,bs).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,vt,ue).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},Be=new WeakMap,qt=new WeakMap,ve=new WeakMap,vt=new WeakSet,ue=function(e){return this.seen.has(e)||!!r(this,qt)?.ignored?.(e)},bs=function(e){return !!r(this,qt)?.childrenIgnored?.(e)},br),qs=class extends oh{constructor(t,i,s){super(t,i,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Zs=class extends oh{constructor(t,i,s){super(t,i,s);p(this,"results");this.results=new Ii({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},oo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",xe=class{constructor(e,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=url.fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||oo,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=t.platform==="win32"?xs:t.platform==="darwin"?sh:t.platform?ks:Xn;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},h=this.pattern.map(a=>new ae(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new rh(a,u,0,this.platform)});}async walk(){return [...await new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new qs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Zs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Zs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},ao=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new ae(i,t).hasMagic())return true;return false};function Ji(e,t={}){return new xe(e,t).streamSync()}function ah(e,t={}){return new xe(e,t).stream()}function lh(e,t={}){return new xe(e,t).walkSync()}async function Vs(e,t={}){return new xe(e,t).walk()}function qi(e,t={}){return new xe(e,t).iterateSync()}function ch(e,t={}){return new xe(e,t).iterate()}var lo=Ji,co=Object.assign(ah,{sync:Ji}),uo=qi,po=Object.assign(ch,{sync:qi}),fo=Object.assign(lh,{stream:Ji,iterate:qi}),Gi=Object.assign(Vs,{glob:Vs,globSync:lh,sync:fo,globStream:ah,stream:co,globStreamSync:Ji,streamSync:lo,globIterate:ch,iterate:po,globIterateSync:qi,iterateSync:uo,Glob:xe,hasMagic:ao,escape:Tr,unescape:Oe});Gi.glob=Gi;exports.c=void 0;(mt=>{mt.Level=mo__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(T){return t[T]>=t[i]}function h(){return i}mt.getLevel=h;let n=new Map;mt.Default=M({service:"default"});let a="";function l(){return a}mt.file=l;let u,d,f=false,w=false,v=T=>{try{w&&process.stderr.write(T);}catch{}},S=false,y=false;async function x(T){if(f)return;if(T.level&&(i=T.level),T.print&&(w=T.print??false),T.print){f=true;return}let D=T.logDir||Zi__default.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");T.logFile?a=Zi__default.default.join(D,T.logFile??"codebase.log"):a=Zi__default.default.join(D,"codebase.log");try{await uh__default.default.mkdir(D,{recursive:!0}),u=await uh__default.default.open(a,"a"),d=Mn.createWriteStream("",{fd:u.fd,autoClose:!1}),v=N=>{if(!(S||y||!d||d.destroyed))try{if(!d.writable)return;d.write(N,nt=>{if(nt&&!S){let j=nt;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(nt){let j=nt;if(j.code==="EPIPE"||j.code==="EIO"){y=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch{v=N=>{try{process.stderr.write(N);}catch{}},f=true;}}mt.init=x;async function E(){f&&(d&&!d.destroyed&&(await new Promise((T,D)=>{d.end(N=>{N?D(N):T();});}).catch(()=>{}),d=void 0),u&&(await u.close().catch(()=>{}),u=void 0),v=T=>{try{process.stderr.write(T);}catch{}},f=false);}mt.close=E;function A(T,D=0){let N=T.message;return T.cause instanceof Error&&D<10?N+" Caused by: "+A(T.cause,D+1):N}let F=Date.now();function M(T){T=T||{};let D=T.service;if(D&&typeof D=="string"){let j=n.get(D);if(j)return j}function N(j,ot){let Vi=Object.entries({...T,...ot}).filter(([Cs,Zt])=>Zt!=null).map(([Cs,Zt])=>{let Ki=`${Cs}=`;return Zt instanceof Error?Ki+A(Zt):typeof Zt=="object"?Ki+JSON.stringify(Zt):Ki+Zt}).join(" "),ke=new Date,fh=ke.getTime()-F;return F=ke.getTime(),[utils.formatLogTime(ke),"+"+fh+"ms",Vi,j].filter(Boolean).join(" ")+`
4
- `}let nt={debug(j,ot){s("DEBUG")&&v("DEBUG "+N(j,ot));},info(j,ot){s("INFO")&&v("INFO "+N(j,ot));},error(j,ot){s("ERROR")&&v("ERROR "+N(j,ot));},warn(j,ot){s("WARN")&&v("WARN "+N(j,ot));},tag(j,ot){return T&&(T[j]=ot),nt},clone(){return mt.create({...T})},time(j,ot){let Vi=Date.now();nt.info(j,{status:"started",...ot});function ke(){nt.info(j,{status:"completed",duration:Date.now()-Vi,...ot});}return {stop:ke,[Symbol.dispose](){ke();}}}};return D&&typeof D=="string"&&n.set(D,nt),nt}mt.create=M;})(exports.c||(exports.c={}));exports.a=p;exports.b=Os;
@@ -1 +0,0 @@
1
- 'use strict';var chunkWNWTOLMW_cjs=require('./chunk-WNWTOLMW.cjs');Object.defineProperty(exports,"Log",{enumerable:true,get:function(){return chunkWNWTOLMW_cjs.c}});
@@ -1 +0,0 @@
1
- export{c as Log}from'./chunk-KWEU4PKH.mjs';