@wispbit/local 1.0.82 → 1.0.84
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/cli-bundle.js +8 -8
- package/package.json +1 -1
package/cli-bundle.js
CHANGED
|
@@ -160,7 +160,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
160
160
|
`);return e?n.pop():n.push(n.pop().slice(0,-1)),n}import*as bi from"fs/promises";import*as d8 from"os";import*as zl from"path";var c8=ue(fO(),1);import Sit from"path";var L6={libraryPath:"graphql",extensions:["graphql","gql"],languageSymbol:"tree_sitter_graphql",expandoChar:"$"};import{existsSync as Eit}from"fs";import Gc from"path";import{fileURLToPath as dit}from"url";var fit=dit(import.meta.url),cd=Gc.dirname(fit);function Tit(){return globalThis.__POWERLINT_IS_BUN_EXECUTABLE__===!0}function y6(t){if(Tit()){let a=globalThis.__POWERLINT_ASSETS__;if(!a)throw new Error("Bun executable assets not initialized");let c=a.parsers[t];if(!c)throw new Error(`Language parser not found in embedded assets: ${t}`);return c}let e=process.platform,n=process.arch,i=`${t}-${e}-${n}-parser.so`,o=[Gc.join(cd,"../../dist/vendor/languages"),Gc.join(cd,"../dist/vendor/languages"),Gc.join(cd,"powerlint/dist/vendor/languages"),Gc.join(cd,"./vendor/languages"),Gc.join(cd,"../vendor/languages"),Gc.join(cd,"../../vendor/languages")],s=[];for(let a of o){let c=Gc.join(a,i);if(Eit(c))return c;s.push(c)}throw new Error(`Prebuild not found for ${t} on ${e} ${n}. Expected file: ${i}. Tried paths: ${s.join(", ")}`)}var b6={libraryPath:"angular",extensions:["html"],languageSymbol:"tree_sitter_angular",expandoChar:"z"};var v6={libraryPath:"bash",extensions:["bash","bats","cgi","command","env","fcgi","ksh","sh","tmux","tool","zsh"],languageSymbol:"tree_sitter_bash",expandoChar:"$"};var U6={libraryPath:"c",extensions:["c","h"],languageSymbol:"tree_sitter_c",expandoChar:"_"};var w6={libraryPath:"cpp",extensions:["cc","hpp","cpp","hh","cxx","cu","ino"],languageSymbol:"tree_sitter_cpp",expandoChar:"_"};var x6={libraryPath:"csharp",extensions:["cs"],languageSymbol:"tree_sitter_c_sharp",expandoChar:"\xB5"};var V6={libraryPath:"css",extensions:["css","scss","vue"],languageSymbol:"tree_sitter_css",expandoChar:"$"};var G6={libraryPath:"dart",extensions:["dart"],languageSymbol:"tree_sitter_dart",expandoChar:"$"};var B6={libraryPath:"elixir",extensions:["ex","exs"],languageSymbol:"tree_sitter_elixir",expandoChar:"\xB5"};var F6={libraryPath:"go",extensions:["go"],languageSymbol:"tree_sitter_go",expandoChar:"\xB5"};var k6={libraryPath:"haskell",extensions:["hs"],languageSymbol:"tree_sitter_haskell",expandoChar:"\xB5"};var H6={libraryPath:"html",extensions:["html","htm","xhtml","vue"],languageSymbol:"tree_sitter_html",expandoChar:"z"};var Y6={libraryPath:"java",extensions:["java"],languageSymbol:"tree_sitter_java",expandoChar:"$"};var $6={libraryPath:"javascript",extensions:["cjs","js","mjs","jsx"],languageSymbol:"tree_sitter_javascript",expandoChar:"$"};var j6={libraryPath:"json",extensions:["json"],languageSymbol:"tree_sitter_json",expandoChar:"$"};var W6={libraryPath:"kotlin",extensions:["kt","ktm","kts"],languageSymbol:"tree_sitter_kotlin",expandoChar:"\xB5"};var K6={libraryPath:"lua",extensions:["lua"],languageSymbol:"tree_sitter_lua",expandoChar:"$"};var z6={libraryPath:"markdown",extensions:["md"],languageSymbol:"tree_sitter_markdown",expandoChar:"$"};var Z6={libraryPath:"php",extensions:["php"],languageSymbol:"tree_sitter_php",expandoChar:"$"};var X6={libraryPath:"python",extensions:["py"],languageSymbol:"tree_sitter_python",expandoChar:"\xB5"};var q6={libraryPath:"ruby",extensions:["rb","rbw","gemspec"],languageSymbol:"tree_sitter_ruby",expandoChar:"\xB5"};var J6={libraryPath:"rust",extensions:["rs"],languageSymbol:"tree_sitter_rust",expandoChar:"\xB5"};var Q6={libraryPath:"scala",extensions:["scala","sc","sbt"],languageSymbol:"tree_sitter_scala",expandoChar:"$"};var e8={libraryPath:"sql",extensions:["sql"],languageSymbol:"tree_sitter_sql",expandoChar:"_"};var t8={libraryPath:"swift",extensions:["swift"],languageSymbol:"tree_sitter_swift",expandoChar:"\xB5"};var n8={libraryPath:"toml",extensions:["toml"],languageSymbol:"tree_sitter_toml",expandoChar:"_"};var r8={libraryPath:"tsx",extensions:["tsx"],languageSymbol:"tree_sitter_tsx",expandoChar:"$"};var i8={libraryPath:"typescript",extensions:["ts","cts","mts","vue"],languageSymbol:"tree_sitter_typescript",expandoChar:"$"};var o8={libraryPath:"yaml",extensions:["yaml","yml"],languageSymbol:"tree_sitter_yaml",expandoChar:"$"};console.debug=()=>{};var yi=(te=>(te.Angular="Angular",te.Bash="Bash",te.C="C",te.Cpp="Cpp",te.Csharp="Csharp",te.Css="Css",te.Dart="Dart",te.Elixir="Elixir",te.Go="Go",te.Haskell="Haskell",te.Html="Html",te.Java="Java",te.JavaScript="JavaScript",te.Json="Json",te.Kotlin="Kotlin",te.Lua="Lua",te.Markdown="Markdown",te.Php="Php",te.Python="Python",te.Ruby="Ruby",te.Rust="Rust",te.Scala="Scala",te.Sql="Sql",te.Swift="Swift",te.Toml="Toml",te.Tsx="Tsx",te.TypeScript="TypeScript",te.Yaml="Yaml",te.GraphQL="GraphQL",te.Unknown="Unknown",te))(yi||{}),dV=[{extension:"vue",hostLanguage:"Html",language:"Html",rule:{pattern:"<template>$$$</template>"},contentNodeKinds:["element","text"]},{extension:"vue",hostLanguage:"Html",language:"TypeScript",rule:{kind:"script_element",regex:'lang="ts"'},contentNodeKinds:["raw_text"]},{extension:"vue",hostLanguage:"Html",language:"JavaScript",rule:{kind:"script_element",not:{regex:"lang="}},contentNodeKinds:["raw_text"]},{extension:"vue",hostLanguage:"Html",language:"Css",rule:{kind:"style_element"},contentNodeKinds:["raw_text"]},{extension:"md",hostLanguage:"Markdown",language:"TypeScript",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(typescript|ts)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"JavaScript",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(javascript|js)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Python",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(python|py)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Go",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(go|golang)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Rust",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(rust|rs)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Java",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^java$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"C",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^c$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Cpp",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(cpp|c\\+\\+|cxx)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Csharp",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(csharp|cs|c#)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Ruby",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(ruby|rb)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Php",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^php$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Swift",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^swift$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Kotlin",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(kotlin|kt)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Scala",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^scala$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Dart",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^dart$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Elixir",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(elixir|ex)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Haskell",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(haskell|hs)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Lua",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^lua$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Bash",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(bash|sh|shell)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Sql",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^sql$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Html",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^html$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Css",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(css|scss)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Json",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^json$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Yaml",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^(yaml|yml)$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Toml",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^toml$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Tsx",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^tsx$"}},contentNodeKinds:["code_fence_content"]},{extension:"md",hostLanguage:"Markdown",language:"Angular",rule:{kind:"fenced_code_block",has:{kind:"info_string",regex:"^angular$"}},contentNodeKinds:["code_fence_content"]}],pit=new Set(["vue","md"]),TO={Angular:b6,Bash:v6,C:U6,Cpp:w6,Csharp:x6,Css:V6,Dart:G6,Elixir:B6,Go:F6,Haskell:k6,Html:H6,Java:Y6,JavaScript:$6,Json:j6,Kotlin:W6,Lua:K6,Markdown:z6,Php:Z6,Python:X6,Ruby:q6,Rust:J6,Scala:Q6,Sql:e8,Swift:t8,Toml:n8,Tsx:r8,TypeScript:i8,Yaml:o8,GraphQL:L6},s8=!1;function hit(){if(!s8){for(let[t,e]of Object.entries(TO))TO[t]={...e,libraryPath:y6(e.libraryPath)};(0,c8.registerDynamicLanguage)(TO),s8=!0}}globalThis.__POWERLINT_IS_BUN_EXECUTABLE__||hit();var a8=Object.entries(TO).reduce((t,[e,n])=>(t[e]=n.extensions??[],t),{});function Bc(t){let e=Sit.extname(t).slice(1),n=mit(e);return n.length>0?n:["Unknown"]}function mit(t){return Object.keys(a8).filter(e=>a8[e].includes(t))}function fV(t){return pit.has(t)}function SO(t,e){if(fV(e))return dV.find(n=>n.extension===e&&n.language===t)}var u8=M.object({path:M.string().describe("File path"),sha:M.string().describe("SHA hash of the file content")}),w0t=M.object({sha:M.string().describe("Commit SHA"),branch:M.string().describe("Branch name"),message:M.string().describe("Commit message"),timestamp:M.string().describe("Commit timestamp")}),pO=M.object({start:M.object({line:M.number().describe("1-based line number"),column:M.number().describe("1-based column number"),index:M.number().describe("0-based byte offset in the file")}),end:M.object({line:M.number().describe("1-based line number"),column:M.number().describe("1-based column number"),index:M.number().describe("0-based byte offset in the file")})}),TV=M.lazy(()=>M.object({file:M.object({path:M.string().describe("File path"),sha:M.string().describe("SHA hash of the file content")}).describe("File information for this evidence match"),text:M.string().optional().describe("The matched text at this evidence step"),range:pO.describe("Position range of this evidence match"),language:M.nativeEnum(yi).describe("The language this evidence match was found in (e.g., Language.TypeScript, Language.Python)"),description:M.string().optional().describe("Description of why this evidence supports the violation, formatted in markdown with proper formatting for code snippets where needed.")})),th=M.object({file:M.object({path:M.string().describe("File path"),sha:M.string().describe("SHA hash of the file content")}).describe("File information for this match"),text:M.string().optional().describe("The matched text/code snippet"),range:pO.describe("Position range of the match"),language:M.nativeEnum(yi).describe("The language this match was found in (e.g., Language.TypeScript, Language.Python)"),description:M.string().optional().describe("Description of the match"),evidence:M.array(TV).optional().describe("Chain of evidence that led to this match. First entry is the original evidence, last entry is the immediate parent."),fingerprint:M.string().optional().describe("AST fingerprint for deduplication. Format: symbol:{symbolPath}|shape:{normalizedAstHash}|index:{nodeIndex}. Index is included for indexed nodes like parameters."),edits:M.array(M.object({filePath:M.string().describe("Workspace-relative path to the file to edit"),oldString:M.string().optional().describe("Text to find and replace. For existing files: provide text to replace. For new files or appending: leave empty/undefined"),newString:M.string().describe("Replacement text"),replaceAll:M.boolean().optional().describe("Replace all occurrences (default: false)")})).optional().describe("Array of string replacement edits for fixing this match")}),l8=M.object({id:M.string(),function:M.object({name:M.enum(["read","grep","glob","report_fix"]),arguments:M.string()})}),Ait=M.object({type:M.literal("tool_request"),tool_calls:M.array(l8)}),git=M.object({tool_call_id:M.string(),content:M.string()}),Rit=M.object({type:M.literal("tool_response"),tool_results:M.array(git)}),Nit=M.object({type:M.literal("assistant"),content:M.string().nullable()}),Oit=M.object({type:M.literal("user"),content:M.string()}),x0t=M.object({match:th,description:M.string(),reason:M.string()}),V0t=M.object({match:th,reason:M.string()}),nh=M.object({cost:M.string().describe("Total cost in USD as a string").optional(),inputTokens:M.string().describe("Total input tokens used").optional(),outputTokens:M.string().describe("Total output tokens used").optional(),cacheReadTokens:M.string().describe("Tokens read from cache").optional(),cacheWriteTokens:M.string().describe("Tokens written to cache").optional()}),Cit=M.object({type:M.literal("tool_request"),tool_calls:M.array(l8),usage:nh.optional()}),Iit=M.object({type:M.literal("assistant"),content:M.string(),usage:nh.optional()}),_8=M.object({type:M.literal("matches"),matches:M.array(th),usage:nh.optional(),files:M.array(u8).optional().describe("Files involved in these matches")}),Mit=M.object({type:M.literal("request_files"),files:M.array(u8).describe("Files that need to be provided with their current SHAs"),usage:nh.optional()}),E8=M.object({type:M.literal("partial_matches"),matches:M.array(th).describe("Cached matches that are already resolved"),unresolved:M.array(th).describe("Uncached matches that need LLM processing"),usage:nh.optional()}),Pit=M.discriminatedUnion("type",[Cit,Iit,_8,Mit,E8]),Dit=M.discriminatedUnion("type",[_8,E8]),G0t=M.discriminatedUnion("type",[Ait,Rit,Nit,Oit]),B0t=M.object({search:M.record(M.string(),Pit),validate:M.record(M.string(),Dit)});var Lit=Ye.object({filePath:Ye.string(),oldString:Ye.string(),newString:Ye.string(),lastUpdated:Ye.string()}),yit=Ye.object({ruleId:Ye.string(),file:Ye.object({path:Ye.string(),sha:Ye.string()}),range:pO,language:Ye.nativeEnum(yi),description:Ye.string().optional(),evidence:Ye.array(TV).optional(),fingerprint:Ye.string().optional()}),bit=Ye.object({timestamp:Ye.string(),matches:Ye.array(yit)}),SV=Ye.object({wispbitSessionId:Ye.string(),workspaceRoot:Ye.string(),startTime:Ye.string(),lastUpdated:Ye.string(),checkpoints:Ye.array(bit),files:Ye.record(Ye.string(),Lit)}),pV=Ye.record(Ye.string(),Ye.string());function hV(t){let e=t==="claude"?"cc":"crsr",n="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let i=0;i<4;i++)r+=n.charAt(Math.floor(Math.random()*n.length));return`${e}_${r}`}var hO=class{getSessionsDir(){return zl.join(d8.homedir(),".wispbit","sessions")}getSessionPath(e){return zl.join(this.getSessionsDir(),`${e}.json`)}getClaudeMappingPath(){return zl.join(this.getSessionsDir(),"claude-sessions.json")}async loadSession(e){let n=this.getSessionPath(e),r=await bi.readFile(n,"utf-8").catch(()=>null);return r?SV.parse(JSON.parse(r)):null}async saveSession(e){let n=this.getSessionPath(e.wispbitSessionId);await bi.mkdir(zl.dirname(n),{recursive:!0}),SV.parse(e),await bi.writeFile(n,JSON.stringify(e,null,2))}async deleteSession(e){let n=this.getSessionPath(e);await bi.unlink(n).catch(()=>{})}async loadClaudeMapping(){let e=this.getClaudeMappingPath(),n=await bi.readFile(e,"utf-8").catch(()=>null);return n?pV.parse(JSON.parse(n)):{}}async saveClaudeMapping(e){let n=this.getClaudeMappingPath();await bi.mkdir(zl.dirname(n),{recursive:!0}),pV.parse(e),await bi.writeFile(n,JSON.stringify(e,null,2))}async getClaudeSession(e){return(await this.loadClaudeMapping())[e]||null}async getOrCreateClaudeSession(e,n){let r=await this.loadClaudeMapping();if(r[e])return r[e];let i=n();return r[e]=i,await this.saveClaudeMapping(r),i}async listSessions(){let e=this.getSessionsDir();return(await bi.readdir(e).catch(()=>[])).filter(r=>r.endsWith(".json")&&r!=="claude-sessions.json").map(r=>r.replace(".json",""))}};var Na=class{storage;sessionData=null;constructor(e){this.storage=e||new hO}async initializeSession(e,n,r){let i;r&&n==="claude"?i=await this.storage.getOrCreateClaudeSession(r,()=>hV(n)):i=hV(n);let o=await this.storage.loadSession(i);if(o)this.sessionData=o,this.sessionData.lastUpdated=new Date().toISOString(),await this.storage.saveSession(this.sessionData);else{let s=new Date().toISOString();this.sessionData={wispbitSessionId:i,workspaceRoot:e,startTime:s,lastUpdated:s,checkpoints:[],files:{}},await this.storage.saveSession(this.sessionData)}return i}async loadSession(e){let n=await this.storage.loadSession(e);if(!n)throw new Error(`Session not found: ${e}`);this.sessionData=n}getSessionData(){if(!this.sessionData)throw new Error("Session not initialized. Call initializeSession() or loadSession() first.");return this.sessionData}async getSession(e,n){if(e==="claude"){let r=await this.storage.getClaudeSession(n);if(!r)return null;let i=await this.storage.loadSession(r);return i&&(this.sessionData=i),i}return null}async addFileChange(e,n,r){if(!this.sessionData)throw new Error("Session not initialized");let i=new Date().toISOString();this.sessionData.files[e]?this.sessionData.files[e]={...this.sessionData.files[e],newString:r,lastUpdated:i}:this.sessionData.files[e]={filePath:e,oldString:n,newString:r,lastUpdated:i},this.sessionData.lastUpdated=i,await this.storage.saveSession(this.sessionData)}async createCheckpoint(e){if(!this.sessionData)throw new Error("Session not initialized");let n=new Date().toISOString(),r=e.map(i=>{let{edits:o,text:s,evidence:a,...c}=i;return{...c,ruleId:i.ruleId}});return this.sessionData.checkpoints.push({timestamp:n,matches:r}),this.sessionData.lastUpdated=n,await this.storage.saveSession(this.sessionData),n}getFileChanges(e){if(!this.sessionData)throw new Error("Session not initialized");let n=[];for(let[r,i]of Object.entries(this.sessionData.files)){if(e&&i.lastUpdated<=e)continue;let o=EV(r,i.oldString,i.newString,"",""),s=o.split(`
|
|
161
161
|
`),a=0,c=0;for(let l of s)l.startsWith("+")&&!l.startsWith("+++")?a++:l.startsWith("-")&&!l.startsWith("---")&&c++;let u="modified";i.oldString===""&&i.newString!==""?u="added":i.oldString!==""&&i.newString===""&&(u="removed"),n.push({filename:r,status:u,additions:a,deletions:c,patch:o,sha:"",baseContent:i.oldString})}return n}getLastCheckpointMatches(){if(!this.sessionData)throw new Error("Session not initialized");if(this.sessionData.checkpoints.length===0)return[];let e=[];for(let r of this.sessionData.checkpoints)e.push(...r.matches);let n=new Map;for(let r of e){let i=`${r.ruleId}:${r.file.path}:${r.range.start.line}:${r.range.start.column}:${r.range.end.line}:${r.range.end.column}:${r.fingerprint||""}`;n.set(i,r)}return Array.from(n.values())}getLastCheckpointTimestamp(){if(!this.sessionData)throw new Error("Session not initialized");if(this.sessionData.checkpoints.length!==0)return this.sessionData.checkpoints[this.sessionData.checkpoints.length-1].timestamp}async endSession(){this.sessionData&&(this.sessionData.lastUpdated=new Date().toISOString(),await this.storage.saveSession(this.sessionData),this.sessionData=null)}};import{EventEmitter as vit}from"events";var zr=class extends vit{rulesStartTime=0;indexingStartTimes=new Map;fileDiscoveryStartTime=0;constructor(){super(),this.setMaxListeners(20)}emit(e,n){return super.emit(e,n)}on(e,n){return super.on(e,n)}once(e,n){return super.once(e,n)}off(e,n){return super.off(e,n)}setExecutionMode(e,n){this.emit("execution:mode",{mode:e,...n})}startRules(e){this.rulesStartTime=Date.now(),this.emit("rules:start",{totalRules:e})}progressRule(e,n,r,i){let o=Math.round(e/n*100);this.emit("rules:progress",{currentRule:e,totalRules:n,ruleId:r,percentage:o,isLlm:i})}errorRule(e,n,r,i){this.emit("rules:rule-error",{ruleId:e,error:n,message:r,severity:i})}completeRules(e,n){let r=Date.now()-this.rulesStartTime;this.emit("rules:complete",{totalRules:e,totalMatches:n,executionTime:r})}startFileDiscovery(e){this.fileDiscoveryStartTime=Date.now(),this.emit("files:discovery:start",{mode:e})}fileDiscoveryProgress(e,n){this.emit("files:discovery:progress",{message:e,currentCount:n})}completeFileDiscovery(e,n,r,i,o){let s=Date.now()-this.fileDiscoveryStartTime,a;(n==="diff"||n==="session")&&r&&(a={totalAdditions:0,totalDeletions:0,files:e.map(c=>{let u=r.get(c),l=u?.additions||0,E=u?.deletions||0;return{path:c,additions:l,deletions:E}})},a.totalAdditions=a.files.reduce((c,u)=>c+u.additions,0),a.totalDeletions=a.files.reduce((c,u)=>c+u.deletions,0)),this.emit("files:discovery:complete",{totalFiles:e.length,mode:n,executionTime:s,stats:a,ignoredFiles:i,deletedFiles:o})}fileFilter(e,n,r){this.emit("files:filter",{originalCount:e,filteredCount:n,filterType:r})}startScipMatchLookup(e,n){this.emit("scip:match-lookup:start",{language:e,match:n})}scipMatchLookupProgress(e,n){this.emit("scip:match-lookup:progress",{language:e,document:n})}scipMatchLookupComplete(e,n){this.emit("scip:match-lookup:complete",{language:e,document:n})}startIndexing(e){this.indexingStartTimes.set(e,Date.now()),this.emit("indexing:start",{language:e})}indexingProgress(e,n,r,i){this.emit("indexing:progress",{language:e,message:n,packageName:r,timeMs:i})}completeIndexing(e){let n=this.indexingStartTimes.get(e)||Date.now(),r=Date.now()-n;this.indexingStartTimes.delete(e),this.emit("indexing:complete",{language:e,executionTime:r})}startStep(e,n,r,i,o){this.emit("step:start",{ruleId:e,stepName:n,stepType:r,inputs:i,parentStepName:o})}completeStep(e,n,r,i,o=0,s){this.emit("step:complete",{ruleId:e,stepName:n,stepType:r,outputs:i,executionTime:o,parentStepName:s})}startTest(e,n){this.emit("test:start",{ruleId:e,testName:n})}testMatches(e,n,r){this.emit("test:matches",{ruleId:e,testName:n,matches:r})}completeTest(e,n,r,i){this.emit("test:complete",{ruleId:e,testName:n,matches:r,stepExecutions:i})}startLLMValidation(e,n,r){this.emit("llm:validation:start",{ruleId:e,matchCount:n,estimatedCost:r})}llmValidationProgress(e,n,r,i){this.emit("llm:validation:progress",{ruleId:e,tokenCount:n,elapsedTime:r,streamedText:i})}completeLLMValidation(e,n,r,i,o,s,a,c){this.emit("llm:validation:complete",{ruleId:e,tokenCount:n,inputTokens:r,outputTokens:i,cost:o,executionTime:s,violationCount:a,fromCache:c})}llmToolExecution(e,n,r){this.emit("llm:tool-execution",{ruleId:e,toolName:n,...r})}startLLMSearchPhase(e,n){this.emit("llm:search-phase:start",{ruleId:e,matchCount:n})}startLLMValidationPhase(e,n){this.emit("llm:validation-phase:start",{ruleId:e,matchCount:n})}llmValidationPhaseBatch(e,n,r,i,o,s){this.emit("llm:validation-phase:batch",{ruleId:e,currentBatch:n,totalBatches:r,batchSize:i,remainingMatches:o,totalMatches:s})}llmMaxIterationsReached(e,n,r,i){this.emit("llm:max-iterations-reached",{ruleId:e,maxIterations:n,messages:r,results:i})}};import*as to from"fs";import*as Ht from"path";var U8=ue(I8(),1);var ih=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var kit={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},oh=t=>t.replace(/[[\]\\-]/g,"\\$&"),Hit=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),M8=t=>t.join(""),P8=(t,e)=>{let n=e;if(t.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],i=[],o=n+1,s=!1,a=!1,c=!1,u=!1,l=n,E="";e:for(;o<t.length;){let p=t.charAt(o);if((p==="!"||p==="^")&&o===n+1){u=!0,o++;continue}if(p==="]"&&s&&!c){l=o+1;break}if(s=!0,p==="\\"&&!c){c=!0,o++;continue}if(p==="["&&!c){for(let[S,[m,O,h]]of Object.entries(kit))if(t.startsWith(S,o)){if(E)return["$.",!1,t.length-n,!0];o+=S.length,h?i.push(m):r.push(m),a=a||O;continue e}}if(c=!1,E){p>E?r.push(oh(E)+"-"+oh(p)):p===E&&r.push(oh(p)),E="",o++;continue}if(t.startsWith("-]",o+1)){r.push(oh(p+"-")),o+=2;continue}if(t.startsWith("-",o+1)){E=p,o+=2;continue}r.push(oh(p)),o++}if(l<o)return["",!1,0,!1];if(!r.length&&!i.length)return["$.",!1,t.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!u){let p=r[0].length===2?r[0].slice(-1):r[0];return[Hit(p),!1,l-n,!1]}let d="["+(u?"^":"")+M8(r)+"]",f="["+(u?"":"^")+M8(i)+"]";return[r.length&&i.length?"("+d+"|"+f+")":r.length?d:f,a,l-n,!0]};var jo=(t,{windowsPathsNoEscape:e=!1}={})=>e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Yit=new Set(["!","?","+","*","@"]),D8=t=>Yit.has(t),$it="(?!(?:^|/)\\.\\.?(?:$|/))",mO="(?!\\.)",jit=new Set(["[","."]),Wit=new Set(["..","."]),Kit=new Set("().*{}+?[]^$\\!"),zit=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),gV="[^/]",L8=gV+"*?",y8=gV+"+?",ud=class t{type;#e;#n;#t=!1;#a=[];#d;#p;#c;#l=!1;#r;#i;#o=!1;constructor(e,n,r={}){this.type=e,e&&(this.#n=!0),this.#d=n,this.#e=this.#d?this.#d.#e:this,this.#r=this.#e===this?r:this.#e.#r,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#l&&this.#c.push(this),this.#p=this.#d?this.#d.#a.length:0}get hasMagic(){if(this.#n!==void 0)return this.#n;for(let e of this.#a)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#n=!0;return this.#n}toString(){return this.#i!==void 0?this.#i:this.type?this.#i=this.type+"("+this.#a.map(e=>String(e)).join("|")+")":this.#i=this.#a.map(e=>String(e)).join("")}#_(){if(this!==this.#e)throw new Error("should only call on root");if(this.#l)return this;this.toString(),this.#l=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let n=e,r=n.#d;for(;r;){for(let i=n.#p+1;!r.type&&i<r.#a.length;i++)for(let o of e.#a){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(r.#a[i])}n=r,r=n.#d}}return this}push(...e){for(let n of e)if(n!==""){if(typeof n!="string"&&!(n instanceof t&&n.#d===this))throw new Error("invalid part: "+n);this.#a.push(n)}}toJSON(){let e=this.type===null?this.#a.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#a.map(n=>n.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#l&&this.#d?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#d?.isStart())return!1;if(this.#p===0)return!0;let e=this.#d;for(let n=0;n<this.#p;n++){let r=e.#a[n];if(!(r instanceof t&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#d?.type==="!")return!0;if(!this.#d?.isEnd())return!1;if(!this.type)return this.#d?.isEnd();let e=this.#d?this.#d.#a.length:0;return this.#p===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let n=new t(this.type,e);for(let r of this.#a)n.copyIn(r);return n}static#s(e,n,r,i){let o=!1,s=!1,a=-1,c=!1;if(n.type===null){let f=r,T="";for(;f<e.length;){let p=e.charAt(f++);if(o||p==="\\"){o=!o,T+=p;continue}if(s){f===a+1?(p==="^"||p==="!")&&(c=!0):p==="]"&&!(f===a+2&&c)&&(s=!1),T+=p;continue}else if(p==="["){s=!0,a=f,c=!1,T+=p;continue}if(!i.noext&&D8(p)&&e.charAt(f)==="("){n.push(T),T="";let S=new t(p,n);f=t.#s(e,S,f,i),n.push(S);continue}T+=p}return n.push(T),f}let u=r+1,l=new t(null,n),E=[],d="";for(;u<e.length;){let f=e.charAt(u++);if(o||f==="\\"){o=!o,d+=f;continue}if(s){u===a+1?(f==="^"||f==="!")&&(c=!0):f==="]"&&!(u===a+2&&c)&&(s=!1),d+=f;continue}else if(f==="["){s=!0,a=u,c=!1,d+=f;continue}if(D8(f)&&e.charAt(u)==="("){l.push(d),d="";let T=new t(f,l);l.push(T),u=t.#s(e,T,u,i);continue}if(f==="|"){l.push(d),d="",E.push(l),l=new t(null,n);continue}if(f===")")return d===""&&n.#a.length===0&&(n.#o=!0),l.push(d),d="",n.push(...E,l),u;d+=f}return n.type=null,n.#n=void 0,n.#a=[e.substring(r-1)],u}static fromGlob(e,n={}){let r=new t(null,void 0,n);return t.#s(e,r,0,n),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[n,r,i,o]=this.toRegExpSource();if(!(i||this.#n||this.#r.nocase&&!this.#r.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let a=(this.#r.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${n}$`,a),{_src:n,_glob:e})}get options(){return this.#r}toRegExpSource(e){let n=e??!!this.#r.dot;if(this.#e===this&&this.#_(),!this.type){let c=this.isStart()&&this.isEnd(),u=this.#a.map(f=>{let[T,p,S,m]=typeof f=="string"?t.#S(f,this.#n,c):f.toRegExpSource(e);return this.#n=this.#n||S,this.#t=this.#t||m,T}).join(""),l="";if(this.isStart()&&typeof this.#a[0]=="string"&&!(this.#a.length===1&&Wit.has(this.#a[0]))){let T=jit,p=n&&T.has(u.charAt(0))||u.startsWith("\\.")&&T.has(u.charAt(2))||u.startsWith("\\.\\.")&&T.has(u.charAt(4)),S=!n&&!e&&T.has(u.charAt(0));l=p?$it:S?mO:""}let E="";return this.isEnd()&&this.#e.#l&&this.#d?.type==="!"&&(E="(?:$|\\/)"),[l+u+E,jo(u),this.#n=!!this.#n,this.#t]}let r=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#E(n);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let c=this.toString();return this.#a=[c],this.type=null,this.#n=void 0,[c,jo(this.toString()),!1,!1]}let s=!r||e||n||!mO?"":this.#E(!0);s===o&&(s=""),s&&(o=`(?:${o})(?:${s})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!n?mO:"")+y8;else{let c=this.type==="!"?"))"+(this.isStart()&&!n&&!e?mO:"")+L8+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&s?")":this.type==="*"&&s?")?":`)${this.type}`;a=i+o+c}return[a,jo(o),this.#n=!!this.#n,this.#t]}#E(e){return this.#a.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,i,o,s]=n.toRegExpSource(e);return this.#t=this.#t||s,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#S(e,n,r=!1){let i=!1,o="",s=!1;for(let a=0;a<e.length;a++){let c=e.charAt(a);if(i){i=!1,o+=(Kit.has(c)?"\\":"")+c;continue}if(c==="\\"){a===e.length-1?o+="\\\\":i=!0;continue}if(c==="["){let[u,l,E,d]=P8(e,a);if(E){o+=u,s=s||l,a+=E-1,n=n||d;continue}}if(c==="*"){r&&e==="*"?o+=y8:o+=L8,n=!0;continue}if(c==="?"){o+=gV,n=!0;continue}o+=zit(c)}return[o,jo(e),!!n,s]}};var ld=(t,{windowsPathsNoEscape:e=!1}={})=>e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var Zr=(t,e,n={})=>(ih(e),!n.nocomment&&e.charAt(0)==="#"?!1:new vi(e,n).match(t)),Zit=/^\*+([^+@!?\*\[\(]*)$/,Xit=t=>e=>!e.startsWith(".")&&e.endsWith(t),qit=t=>e=>e.endsWith(t),Jit=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),Qit=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),eot=/^\*+\.\*+$/,tot=t=>!t.startsWith(".")&&t.includes("."),not=t=>t!=="."&&t!==".."&&t.includes("."),rot=/^\.\*+$/,iot=t=>t!=="."&&t!==".."&&t.startsWith("."),oot=/^\*+$/,sot=t=>t.length!==0&&!t.startsWith("."),aot=t=>t.length!==0&&t!=="."&&t!=="..",cot=/^\?+([^+@!?\*\[\(]*)?$/,uot=([t,e=""])=>{let n=w8([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},lot=([t,e=""])=>{let n=x8([t]);return e?(e=e.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(e)):n},_ot=([t,e=""])=>{let n=x8([t]);return e?r=>n(r)&&r.endsWith(e):n},Eot=([t,e=""])=>{let n=w8([t]);return e?r=>n(r)&&r.endsWith(e):n},w8=([t])=>{let e=t.length;return n=>n.length===e&&!n.startsWith(".")},x8=([t])=>{let e=t.length;return n=>n.length===e&&n!=="."&&n!==".."},V8=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",b8={win32:{sep:"\\"},posix:{sep:"/"}},dot=V8==="win32"?b8.win32.sep:b8.posix.sep;Zr.sep=dot;var cr=Symbol("globstar **");Zr.GLOBSTAR=cr;var fot="[^/]",Tot=fot+"*?",Sot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",pot="(?:(?!(?:\\/|^)\\.).)*?",hot=(t,e={})=>n=>Zr(n,t,e);Zr.filter=hot;var Ji=(t,e={})=>Object.assign({},t,e),mot=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Zr;let e=Zr;return Object.assign((r,i,o={})=>e(r,i,Ji(t,o)),{Minimatch:class extends e.Minimatch{constructor(i,o={}){super(i,Ji(t,o))}static defaults(i){return e.defaults(Ji(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,o,s={}){super(i,o,Ji(t,s))}static fromGlob(i,o={}){return e.AST.fromGlob(i,Ji(t,o))}},unescape:(r,i={})=>e.unescape(r,Ji(t,i)),escape:(r,i={})=>e.escape(r,Ji(t,i)),filter:(r,i={})=>e.filter(r,Ji(t,i)),defaults:r=>e.defaults(Ji(t,r)),makeRe:(r,i={})=>e.makeRe(r,Ji(t,i)),braceExpand:(r,i={})=>e.braceExpand(r,Ji(t,i)),match:(r,i,o={})=>e.match(r,i,Ji(t,o)),sep:e.sep,GLOBSTAR:cr})};Zr.defaults=mot;var G8=(t,e={})=>(ih(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:(0,U8.default)(t));Zr.braceExpand=G8;var Aot=(t,e={})=>new vi(t,e).makeRe();Zr.makeRe=Aot;var got=(t,e,n={})=>{let r=new vi(e,n);return t=t.filter(i=>r.match(i)),r.options.nonull&&!t.length&&t.push(e),t};Zr.match=got;var v8=/[?*]|[+@!]\(.*?\)|\[|\]/,Rot=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vi=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,n={}){ih(e),n=n||{},this.options=n,this.pattern=e,this.platform=n.platform||V8,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let n of e)if(typeof n!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,n=this.options;if(!n.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let i=this.globParts.map((o,s,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=o[0]===""&&o[1]===""&&(o[2]==="?"||!v8.test(o[2]))&&!v8.test(o[3]),u=/^[a-z]:/i.test(o[0]);if(c)return[...o.slice(0,4),...o.slice(4).map(l=>this.parse(l))];if(u)return[o[0],...o.slice(1).map(l=>this.parse(l))]}return o.map(c=>this.parse(c))});if(this.debug(this.pattern,i),this.set=i.filter(o=>o.indexOf(!1)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let s=this.set[o];s[0]===""&&s[1]===""&&this.globParts[o][2]==="?"&&typeof s[3]=="string"&&/^[a-z]:$/i.test(s[3])&&(s[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let i=0;i<e[r].length;i++)e[r][i]==="**"&&(e[r][i]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):n>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let i=r;for(;n[i+1]==="**";)i++;i!==r&&n.splice(r,i-r)}return n})}levelOneOptimize(e){return e.map(n=>(n=n.reduce((r,i)=>{let o=r[r.length-1];return i==="**"&&o==="**"?r:i===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(r.pop(),r):(r.push(i),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){let o=e[i];i===1&&o===""&&e[0]===""||(o==="."||o==="")&&(n=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(n=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let i=e[r-1];i&&i!=="."&&i!==".."&&i!=="**"&&(n=!0,e.splice(r-1,2),r-=2)}}while(n);return e.length===0?[""]:e}firstPhasePreProcess(e){let n=!1;do{n=!1;for(let r of e){let i=-1;for(;(i=r.indexOf("**",i+1))!==-1;){let s=i;for(;r[s+1]==="**";)s++;s>i&&r.splice(i+1,s-i);let a=r[i+1],c=r[i+2],u=r[i+3];if(a!==".."||!c||c==="."||c===".."||!u||u==="."||u==="..")continue;n=!0,r.splice(i,1);let l=r.slice(0);l[i]="**",e.push(l),i--}if(!this.preserveMultipleSlashes){for(let s=1;s<r.length-1;s++){let a=r[s];s===1&&a===""&&r[0]===""||(a==="."||a==="")&&(n=!0,r.splice(s,1),s--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let o=0;for(;(o=r.indexOf("..",o+1))!==-1;){let s=r[o-1];if(s&&s!=="."&&s!==".."&&s!=="**"){n=!0;let c=o===1&&r[o+1]==="**"?["."]:[];r.splice(o-1,2,...c),r.length===0&&r.push(""),o-=2}}}}while(n);return e}secondPhasePreProcess(e){for(let n=0;n<e.length-1;n++)for(let r=n+1;r<e.length;r++){let i=this.partsMatch(e[n],e[r],!this.preserveMultipleSlashes);if(i){e[n]=[],e[r]=i;break}}return e.filter(n=>n.length)}partsMatch(e,n,r=!1){let i=0,o=0,s=[],a="";for(;i<e.length&&o<n.length;)if(e[i]===n[o])s.push(a==="b"?n[o]:e[i]),i++,o++;else if(r&&e[i]==="**"&&n[o]===e[i+1])s.push(e[i]),i++;else if(r&&n[o]==="**"&&e[i]===n[o+1])s.push(n[o]),o++;else if(e[i]==="*"&&n[o]&&(this.options.dot||!n[o].startsWith("."))&&n[o]!=="**"){if(a==="b")return!1;a="a",s.push(e[i]),i++,o++}else if(n[o]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(a==="a")return!1;a="b",s.push(n[o]),i++,o++}else return!1;return e.length===n.length&&s}parseNegate(){if(this.nonegate)return;let e=this.pattern,n=!1,r=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)n=!n,r++;r&&(this.pattern=e.slice(r)),this.negate=n}matchOne(e,n,r=!1){let i=this.options;if(this.isWindows){let p=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!p&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),m=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),O=!m&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),h=S?3:p?0:void 0,C=O?3:m?0:void 0;if(typeof h=="number"&&typeof C=="number"){let[P,G]=[e[h],n[C]];P.toLowerCase()===G.toLowerCase()&&(n[C]=P,C>h?n=n.slice(C):h>C&&(e=e.slice(h)))}}let{optimizationLevel:o=1}=this.options;o>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:n}),this.debug("matchOne",e.length,n.length);for(var s=0,a=0,c=e.length,u=n.length;s<c&&a<u;s++,a++){this.debug("matchOne loop");var l=n[a],E=e[s];if(this.debug(n,l,E),l===!1)return!1;if(l===cr){this.debug("GLOBSTAR",[n,l,E]);var d=s,f=a+1;if(f===u){for(this.debug("** at the end");s<c;s++)if(e[s]==="."||e[s]===".."||!i.dot&&e[s].charAt(0)===".")return!1;return!0}for(;d<c;){var T=e[d];if(this.debug(`
|
|
162
162
|
globstar while`,e,d,n,f,T),this.matchOne(e.slice(d),n.slice(f),r))return this.debug("globstar found match!",d,c,T),!0;if(T==="."||T===".."||!i.dot&&T.charAt(0)==="."){this.debug("dot detected!",e,d,n,f);break}this.debug("globstar swallow a segment, and continue"),d++}return!!(r&&(this.debug(`
|
|
163
|
-
>>> no match, partial?`,e,d,n,f),d===c))}let p;if(typeof l=="string"?(p=E===l,this.debug("string match",l,E,p)):(p=l.test(E),this.debug("pattern match",l,E,p)),!p)return!1}if(s===c&&a===u)return!0;if(s===c)return r;if(a===u)return s===c-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return G8(this.pattern,this.options)}parse(e){ih(e);let n=this.options;if(e==="**")return cr;if(e==="")return"";let r,i=null;(r=e.match(oot))?i=n.dot?aot:sot:(r=e.match(Zit))?i=(n.nocase?n.dot?Qit:Jit:n.dot?qit:Xit)(r[1]):(r=e.match(cot))?i=(n.nocase?n.dot?lot:uot:n.dot?_ot:Eot)(r):(r=e.match(eot))?i=n.dot?not:tot:(r=e.match(rot))&&(i=iot);let o=ud.fromGlob(e,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?Tot:n.dot?Sot:pot,i=new Set(n.nocase?["i"]:[]),o=e.map(c=>{let u=c.map(l=>{if(l instanceof RegExp)for(let E of l.flags.split(""))i.add(E);return typeof l=="string"?Rot(l):l===cr?cr:l._src});return u.forEach((l,E)=>{let d=u[E+1],f=u[E-1];l!==cr||f===cr||(f===void 0?d!==void 0&&d!==cr?u[E+1]="(?:\\/|"+r+"\\/)?"+d:u[E]=r:d===void 0?u[E-1]=f+"(?:\\/|"+r+")?":d!==cr&&(u[E-1]=f+"(?:\\/|\\/"+r+"\\/)"+d,u[E+1]=cr))}),u.filter(l=>l!==cr).join("/")}).join("|"),[s,a]=e.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a=0;a<o.length;a++){let c=o[a],u=i;if(r.matchBase&&c.length===1&&(u=[s]),this.matchOne(u,c,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return Zr.defaults(e).Minimatch}};Zr.AST=ud;Zr.Minimatch=vi;Zr.escape=ld;Zr.unescape=jo;import{fileURLToPath as est}from"node:url";var _d=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,F8=new Set,RV=typeof process=="object"&&process?process:{},k8=(t,e,n,r)=>{typeof RV.emitWarning=="function"?RV.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},AO=globalThis.AbortController,B8=globalThis.AbortSignal;if(typeof AO>"u"){B8=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,i){this._onabort.push(i)}},AO=class{constructor(){e()}signal=new B8;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let i of this.signal._onabort)i(r);this.signal.onabort?.(r)}}};let t=RV.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,k8("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",e))}}var Not=t=>!F8.has(t),Cwt=Symbol("type"),Fc=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),H8=t=>Fc(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ed:null:null,Ed=class extends Array{constructor(e){super(e),this.fill(0)}},NV=class t{heap;length;static#e=!1;static create(e){let n=H8(e);if(!n)return[];t.#e=!0;let r=new t(e,n);return t.#e=!1,r}constructor(e,n){if(!t.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},sh=class t{#e;#n;#t;#a;#d;#p;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#l;#r;#i;#o;#_;#s;#E;#S;#f;#T;#C;#m;#A;#O;#h;#N;static unsafeExposeInternals(e){return{starts:e.#m,ttls:e.#A,sizes:e.#C,keyMap:e.#r,keyList:e.#i,valList:e.#o,next:e.#_,prev:e.#s,get head(){return e.#E},get tail(){return e.#S},free:e.#f,isBackgroundFetch:n=>e.#R(n),backgroundFetch:(n,r,i,o)=>e.#g(n,r,i,o),moveToTail:n=>e.#H(n),indexes:n=>e.#b(n),rindexes:n=>e.#w(n),isStale:n=>e.#y(n)}}get max(){return this.#e}get maxSize(){return this.#n}get calculatedSize(){return this.#l}get size(){return this.#c}get fetchMethod(){return this.#d}get memoMethod(){return this.#p}get dispose(){return this.#t}get disposeAfter(){return this.#a}constructor(e){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:l,noDisposeOnSet:E,noUpdateTTL:d,maxSize:f=0,maxEntrySize:T=0,sizeCalculation:p,fetchMethod:S,memoMethod:m,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:h,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:P,ignoreFetchAbort:G}=e;if(n!==0&&!Fc(n))throw new TypeError("max option must be a nonnegative integer");let Y=n?H8(n):Array;if(!Y)throw new Error("invalid max value: "+n);if(this.#e=n,this.#n=f,this.maxEntrySize=T||this.#n,this.sizeCalculation=p,this.sizeCalculation){if(!this.#n&&!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(m!==void 0&&typeof m!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#p=m,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#d=S,this.#h=!!S,this.#r=new Map,this.#i=new Array(n).fill(void 0),this.#o=new Array(n).fill(void 0),this.#_=new Y(n),this.#s=new Y(n),this.#E=0,this.#S=0,this.#f=NV.create(n),this.#c=0,this.#l=0,typeof u=="function"&&(this.#t=u),typeof l=="function"?(this.#a=l,this.#T=[]):(this.#a=void 0,this.#T=void 0),this.#O=!!this.#t,this.#N=!!this.#a,this.noDisposeOnSet=!!E,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!C,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!G,this.maxEntrySize!==0){if(this.#n!==0&&!Fc(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!Fc(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#v()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!h,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Fc(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!Fc(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#n){let re="LRU_CACHE_UNBOUNDED";Not(re)&&(F8.add(re),k8("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",re,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#D(){let e=new Ed(this.#e),n=new Ed(this.#e);this.#A=e,this.#m=n,this.#L=(o,s,a=_d.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#y(o)&&this.#F(this.#i[o],"expire")},s+1);c.unref&&c.unref()}},this.#P=o=>{n[o]=e[o]!==0?_d.now():0},this.#u=(o,s)=>{if(e[s]){let a=e[s],c=n[s];if(!a||!c)return;o.ttl=a,o.start=c,o.now=r||i();let u=o.now-c;o.remainingTTL=a-u}};let r=0,i=()=>{let o=_d.now();if(this.ttlResolution>0){r=o;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],c=n[s];if(!a||!c)return 1/0;let u=(r||i())-c;return a-u},this.#y=o=>{let s=n[o],a=e[o];return!!a&&!!s&&(r||i())-s>a}}#P=()=>{};#u=()=>{};#L=()=>{};#y=()=>!1;#v(){let e=new Ed(this.#e);this.#l=0,this.#C=e,this.#U=n=>{this.#l-=e[n],e[n]=0},this.#M=(n,r,i,o)=>{if(this.#R(r))return 0;if(!Fc(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(r,n),!Fc(i))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 i},this.#B=(n,r,i)=>{if(e[n]=r,this.#n){let o=this.#n-e[n];for(;this.#l>o;)this.#V(!0)}this.#l+=e[n],i&&(i.entrySize=r,i.totalCalculatedSize=this.#l)}}#U=e=>{};#B=(e,n,r)=>{};#M=(e,n,r,i)=>{if(r||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#c)for(let n=this.#S;!(!this.#x(n)||((e||!this.#y(n))&&(yield n),n===this.#E));)n=this.#s[n]}*#w({allowStale:e=this.allowStale}={}){if(this.#c)for(let n=this.#E;!(!this.#x(n)||((e||!this.#y(n))&&(yield n),n===this.#S));)n=this.#_[n]}#x(e){return e!==void 0&&this.#r.get(this.#i[e])===e}*entries(){for(let e of this.#b())this.#o[e]!==void 0&&this.#i[e]!==void 0&&!this.#R(this.#o[e])&&(yield[this.#i[e],this.#o[e]])}*rentries(){for(let e of this.#w())this.#o[e]!==void 0&&this.#i[e]!==void 0&&!this.#R(this.#o[e])&&(yield[this.#i[e],this.#o[e]])}*keys(){for(let e of this.#b()){let n=this.#i[e];n!==void 0&&!this.#R(this.#o[e])&&(yield n)}}*rkeys(){for(let e of this.#w()){let n=this.#i[e];n!==void 0&&!this.#R(this.#o[e])&&(yield n)}}*values(){for(let e of this.#b())this.#o[e]!==void 0&&!this.#R(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#w())this.#o[e]!==void 0&&!this.#R(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#b()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#i[r],this))return this.get(this.#i[r],n)}}forEach(e,n=this){for(let r of this.#b()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#i[r],this)}}rforEach(e,n=this){for(let r of this.#w()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#i[r],this)}}purgeStale(){let e=!1;for(let n of this.#w({allowStale:!0}))this.#y(n)&&(this.#F(this.#i[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#o[n],i=this.#R(r)?r.__staleWhileFetching:r;if(i===void 0)return;let o={value:i};if(this.#A&&this.#m){let s=this.#A[n],a=this.#m[n];if(s&&a){let c=s-(_d.now()-a);o.ttl=c,o.start=Date.now()}}return this.#C&&(o.size=this.#C[n]),o}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let r=this.#i[n],i=this.#o[n],o=this.#R(i)?i.__staleWhileFetching:i;if(o===void 0||r===void 0)continue;let s={value:o};if(this.#A&&this.#m){s.ttl=this.#A[n];let a=_d.now()-this.#m[n];s.start=Math.floor(Date.now()-a)}this.#C&&(s.size=this.#C[n]),e.unshift([r,s])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let i=Date.now()-r.start;r.start=_d.now()-i}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,l=this.#M(e,n,r.size||0,a);if(this.maxEntrySize&&l>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#F(e,"set"),this;let E=this.#c===0?void 0:this.#r.get(e);if(E===void 0)E=this.#c===0?this.#S:this.#f.length!==0?this.#f.pop():this.#c===this.#e?this.#V(!1):this.#c,this.#i[E]=e,this.#o[E]=n,this.#r.set(e,E),this.#_[this.#S]=E,this.#s[E]=this.#S,this.#S=E,this.#c++,this.#B(E,l,c),c&&(c.set="add"),u=!1;else{this.#H(E);let d=this.#o[E];if(n!==d){if(this.#h&&this.#R(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!s&&(this.#O&&this.#t?.(f,e,"set"),this.#N&&this.#T?.push([f,e,"set"]))}else s||(this.#O&&this.#t?.(d,e,"set"),this.#N&&this.#T?.push([d,e,"set"]));if(this.#U(E),this.#B(E,l,c),this.#o[E]=n,c){c.set="replace";let f=d&&this.#R(d)?d.__staleWhileFetching:d;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(i!==0&&!this.#A&&this.#D(),this.#A&&(u||this.#L(E,i,o),c&&this.#u(c,E)),!s&&this.#N&&this.#T){let d=this.#T,f;for(;f=d?.shift();)this.#a?.(...f)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#E];if(this.#V(!0),this.#R(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#N&&this.#T){let e=this.#T,n;for(;n=e?.shift();)this.#a?.(...n)}}}#V(e){let n=this.#E,r=this.#i[n],i=this.#o[n];return this.#h&&this.#R(i)?i.__abortController.abort(new Error("evicted")):(this.#O||this.#N)&&(this.#O&&this.#t?.(i,r,"evict"),this.#N&&this.#T?.push([i,r,"evict"])),this.#U(n),e&&(this.#i[n]=void 0,this.#o[n]=void 0,this.#f.push(n)),this.#c===1?(this.#E=this.#S=0,this.#f.length=0):this.#E=this.#_[n],this.#r.delete(r),this.#c--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:i}=n,o=this.#r.get(e);if(o!==void 0){let s=this.#o[o];if(this.#R(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#y(o))i&&(i.has="stale",this.#u(i,o));else return r&&this.#P(o),i&&(i.has="hit",this.#u(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,i=this.#r.get(e);if(i===void 0||!r&&this.#y(i))return;let o=this.#o[i];return this.#R(o)?o.__staleWhileFetching:o}#g(e,n,r,i){let o=n===void 0?void 0:this.#o[n];if(this.#R(o))return o;let s=new AO,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:r,context:i},u=(p,S=!1)=>{let{aborted:m}=s.signal,O=r.ignoreFetchAbort&&p!==void 0;if(r.status&&(m&&!S?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,O&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),m&&!O&&!S)return E(s.signal.reason);let h=f;return this.#o[n]===f&&(p===void 0?h.__staleWhileFetching?this.#o[n]=h.__staleWhileFetching:this.#F(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,p,c.options))),p},l=p=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=p),E(p)),E=p=>{let{aborted:S}=s.signal,m=S&&r.allowStaleOnFetchAbort,O=m||r.allowStaleOnFetchRejection,h=O||r.noDeleteOnFetchRejection,C=f;if(this.#o[n]===f&&(!h||C.__staleWhileFetching===void 0?this.#F(e,"fetch"):m||(this.#o[n]=C.__staleWhileFetching)),O)return r.status&&C.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),C.__staleWhileFetching;if(C.__returned===C)throw p},d=(p,S)=>{let m=this.#d?.(e,o,c);m&&m instanceof Promise&&m.then(O=>p(O===void 0?void 0:O),S),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(p(void 0),r.allowStaleOnFetchAbort&&(p=O=>u(O,!0)))})};r.status&&(r.status.fetchDispatched=!0);let f=new Promise(d).then(u,l),T=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,T,{...c.options,status:void 0}),n=this.#r.get(e)):this.#o[n]=T,T}#R(e){if(!this.#h)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof AO}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:E=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:T=this.allowStaleOnFetchAbort,context:p,forceRefresh:S=!1,status:m,signal:O}=n;if(!this.#h)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:m});let h={allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:E,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:T,ignoreFetchAbort:f,status:m,signal:O},C=this.#r.get(e);if(C===void 0){m&&(m.fetch="miss");let P=this.#g(e,C,h,p);return P.__returned=P}else{let P=this.#o[C];if(this.#R(P)){let q=r&&P.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",q&&(m.returnedStale=!0)),q?P.__staleWhileFetching:P.__returned=P}let G=this.#y(C);if(!S&&!G)return m&&(m.fetch="hit"),this.#H(C),i&&this.#P(C),m&&this.#u(m,C),P;let Y=this.#g(e,C,h,p),W=Y.__staleWhileFetching!==void 0&&r;return m&&(m.fetch=G?"stale":"refresh",W&&G&&(m.returnedStale=!0)),W?Y.__staleWhileFetching:Y.__returned=Y}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#p;if(!r)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:o,...s}=n,a=this.get(e,s);if(!o&&a!==void 0)return a;let c=r(e,a,{options:s,context:i});return this.set(e,c,s),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#o[a],u=this.#R(c);return s&&this.#u(s,a),this.#y(a)?(s&&(s.get="stale"),u?(s&&r&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?c.__staleWhileFetching:void 0):(o||this.#F(e,"expire"),s&&r&&(s.returnedStale=!0),r?c:void 0)):(s&&(s.get="hit"),u?c.__staleWhileFetching:(this.#H(a),i&&this.#P(a),c))}else s&&(s.get="miss")}#G(e,n){this.#s[n]=e,this.#_[e]=n}#H(e){e!==this.#S&&(e===this.#E?this.#E=this.#_[e]:this.#G(this.#s[e],this.#_[e]),this.#G(this.#S,e),this.#S=e)}delete(e){return this.#F(e,"delete")}#F(e,n){let r=!1;if(this.#c!==0){let i=this.#r.get(e);if(i!==void 0)if(r=!0,this.#c===1)this.#I(n);else{this.#U(i);let o=this.#o[i];if(this.#R(o)?o.__abortController.abort(new Error("deleted")):(this.#O||this.#N)&&(this.#O&&this.#t?.(o,e,n),this.#N&&this.#T?.push([o,e,n])),this.#r.delete(e),this.#i[i]=void 0,this.#o[i]=void 0,i===this.#S)this.#S=this.#s[i];else if(i===this.#E)this.#E=this.#_[i];else{let s=this.#s[i];this.#_[s]=this.#_[i];let a=this.#_[i];this.#s[a]=this.#s[i]}this.#c--,this.#f.push(i)}}if(this.#N&&this.#T?.length){let i=this.#T,o;for(;o=i?.shift();)this.#a?.(...o)}return r}clear(){return this.#I("delete")}#I(e){for(let n of this.#w({allowStale:!0})){let r=this.#o[n];if(this.#R(r))r.__abortController.abort(new Error("deleted"));else{let i=this.#i[n];this.#O&&this.#t?.(r,i,e),this.#N&&this.#T?.push([r,i,e])}}if(this.#r.clear(),this.#o.fill(void 0),this.#i.fill(void 0),this.#A&&this.#m&&(this.#A.fill(0),this.#m.fill(0)),this.#C&&this.#C.fill(0),this.#E=0,this.#S=0,this.#f.length=0,this.#l=0,this.#c=0,this.#N&&this.#T){let n=this.#T,r;for(;r=n?.shift();)this.#a?.(...r)}}};import{posix as Uot,win32 as vV}from"node:path";import{fileURLToPath as wot}from"node:url";import{lstatSync as xot,readdir as Vot,readdirSync as Got,readlinkSync as Bot,realpathSync as Fot}from"fs";import*as kot from"node:fs";import{lstat as Yot,readdir as $ot,readlink as jot,realpath as Wot}from"node:fs/promises";import{EventEmitter as LV}from"node:events";import K8 from"node:stream";import{StringDecoder as Oot}from"node:string_decoder";var Y8=typeof process=="object"&&process?process:{stdout:null,stderr:null},Cot=t=>!!t&&typeof t=="object"&&(t instanceof Hc||t instanceof K8||Iot(t)||Mot(t)),Iot=t=>!!t&&typeof t=="object"&&t instanceof LV&&typeof t.pipe=="function"&&t.pipe!==K8.Writable.prototype.pipe,Mot=t=>!!t&&typeof t=="object"&&t instanceof LV&&typeof t.write=="function"&&typeof t.end=="function",Oa=Symbol("EOF"),Ca=Symbol("maybeEmitEnd"),kc=Symbol("emittedEnd"),gO=Symbol("emittingEnd"),ah=Symbol("emittedError"),RO=Symbol("closed"),$8=Symbol("read"),NO=Symbol("flush"),j8=Symbol("flushChunk"),Wo=Symbol("encoding"),dd=Symbol("decoder"),Xn=Symbol("flowing"),ch=Symbol("paused"),fd=Symbol("resume"),qn=Symbol("buffer"),Xr=Symbol("pipes"),Jn=Symbol("bufferLength"),OV=Symbol("bufferPush"),OO=Symbol("bufferShift"),Ir=Symbol("objectMode"),Mn=Symbol("destroyed"),CV=Symbol("error"),IV=Symbol("emitData"),W8=Symbol("emitEnd"),MV=Symbol("emitEnd2"),Cs=Symbol("async"),PV=Symbol("abort"),CO=Symbol("aborted"),uh=Symbol("signal"),Zl=Symbol("dataListeners"),Ui=Symbol("discarded"),lh=t=>Promise.resolve().then(t),Pot=t=>t(),Dot=t=>t==="end"||t==="finish"||t==="prefinish",Lot=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,yot=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),IO=class{src;dest;opts;ondrain;constructor(e,n,r){this.src=e,this.dest=n,this.opts=r,this.ondrain=()=>e[fd](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},DV=class extends IO{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,n,r){super(e,n,r),this.proxyErrors=i=>n.emit("error",i),e.on("error",this.proxyErrors)}},bot=t=>!!t.objectMode,vot=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Hc=class extends LV{[Xn]=!1;[ch]=!1;[Xr]=[];[qn]=[];[Ir];[Wo];[Cs];[dd];[Oa]=!1;[kc]=!1;[gO]=!1;[RO]=!1;[ah]=null;[Jn]=0;[Mn]=!1;[uh];[CO]=!1;[Zl]=0;[Ui]=!1;writable=!0;readable=!0;constructor(...e){let n=e[0]||{};if(super(),n.objectMode&&typeof n.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");bot(n)?(this[Ir]=!0,this[Wo]=null):vot(n)?(this[Wo]=n.encoding,this[Ir]=!1):(this[Ir]=!1,this[Wo]=null),this[Cs]=!!n.async,this[dd]=this[Wo]?new Oot(this[Wo]):null,n&&n.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qn]}),n&&n.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Xr]});let{signal:r}=n;r&&(this[uh]=r,r.aborted?this[PV]():r.addEventListener("abort",()=>this[PV]()))}get bufferLength(){return this[Jn]}get encoding(){return this[Wo]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ir]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Cs]}set async(e){this[Cs]=this[Cs]||!!e}[PV](){this[CO]=!0,this.emit("abort",this[uh]?.reason),this.destroy(this[uh]?.reason)}get aborted(){return this[CO]}set aborted(e){}write(e,n,r){if(this[CO])return!1;if(this[Oa])throw new Error("write after end");if(this[Mn])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof n=="function"&&(r=n,n="utf8"),n||(n="utf8");let i=this[Cs]?lh:Pot;if(!this[Ir]&&!Buffer.isBuffer(e)){if(yot(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Lot(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ir]?(this[Xn]&&this[Jn]!==0&&this[NO](!0),this[Xn]?this.emit("data",e):this[OV](e),this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn]):e.length?(typeof e=="string"&&!(n===this[Wo]&&!this[dd]?.lastNeed)&&(e=Buffer.from(e,n)),Buffer.isBuffer(e)&&this[Wo]&&(e=this[dd].write(e)),this[Xn]&&this[Jn]!==0&&this[NO](!0),this[Xn]?this.emit("data",e):this[OV](e),this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn]):(this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn])}read(e){if(this[Mn])return null;if(this[Ui]=!1,this[Jn]===0||e===0||e&&e>this[Jn])return this[Ca](),null;this[Ir]&&(e=null),this[qn].length>1&&!this[Ir]&&(this[qn]=[this[Wo]?this[qn].join(""):Buffer.concat(this[qn],this[Jn])]);let n=this[$8](e||null,this[qn][0]);return this[Ca](),n}[$8](e,n){if(this[Ir])this[OO]();else{let r=n;e===r.length||e===null?this[OO]():typeof r=="string"?(this[qn][0]=r.slice(e),n=r.slice(0,e),this[Jn]-=e):(this[qn][0]=r.subarray(e),n=r.subarray(0,e),this[Jn]-=e)}return this.emit("data",n),!this[qn].length&&!this[Oa]&&this.emit("drain"),n}end(e,n,r){return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n="utf8"),e!==void 0&&this.write(e,n),r&&this.once("end",r),this[Oa]=!0,this.writable=!1,(this[Xn]||!this[ch])&&this[Ca](),this}[fd](){this[Mn]||(!this[Zl]&&!this[Xr].length&&(this[Ui]=!0),this[ch]=!1,this[Xn]=!0,this.emit("resume"),this[qn].length?this[NO]():this[Oa]?this[Ca]():this.emit("drain"))}resume(){return this[fd]()}pause(){this[Xn]=!1,this[ch]=!0,this[Ui]=!1}get destroyed(){return this[Mn]}get flowing(){return this[Xn]}get paused(){return this[ch]}[OV](e){this[Ir]?this[Jn]+=1:this[Jn]+=e.length,this[qn].push(e)}[OO](){return this[Ir]?this[Jn]-=1:this[Jn]-=this[qn][0].length,this[qn].shift()}[NO](e=!1){do;while(this[j8](this[OO]())&&this[qn].length);!e&&!this[qn].length&&!this[Oa]&&this.emit("drain")}[j8](e){return this.emit("data",e),this[Xn]}pipe(e,n){if(this[Mn])return e;this[Ui]=!1;let r=this[kc];return n=n||{},e===Y8.stdout||e===Y8.stderr?n.end=!1:n.end=n.end!==!1,n.proxyErrors=!!n.proxyErrors,r?n.end&&e.end():(this[Xr].push(n.proxyErrors?new DV(this,e,n):new IO(this,e,n)),this[Cs]?lh(()=>this[fd]()):this[fd]()),e}unpipe(e){let n=this[Xr].find(r=>r.dest===e);n&&(this[Xr].length===1?(this[Xn]&&this[Zl]===0&&(this[Xn]=!1),this[Xr]=[]):this[Xr].splice(this[Xr].indexOf(n),1),n.unpipe())}addListener(e,n){return this.on(e,n)}on(e,n){let r=super.on(e,n);if(e==="data")this[Ui]=!1,this[Zl]++,!this[Xr].length&&!this[Xn]&&this[fd]();else if(e==="readable"&&this[Jn]!==0)super.emit("readable");else if(Dot(e)&&this[kc])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[ah]){let i=n;this[Cs]?lh(()=>i.call(this,this[ah])):i.call(this,this[ah])}return r}removeListener(e,n){return this.off(e,n)}off(e,n){let r=super.off(e,n);return e==="data"&&(this[Zl]=this.listeners("data").length,this[Zl]===0&&!this[Ui]&&!this[Xr].length&&(this[Xn]=!1)),r}removeAllListeners(e){let n=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Zl]=0,!this[Ui]&&!this[Xr].length&&(this[Xn]=!1)),n}get emittedEnd(){return this[kc]}[Ca](){!this[gO]&&!this[kc]&&!this[Mn]&&this[qn].length===0&&this[Oa]&&(this[gO]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[RO]&&this.emit("close"),this[gO]=!1)}emit(e,...n){let r=n[0];if(e!=="error"&&e!=="close"&&e!==Mn&&this[Mn])return!1;if(e==="data")return!this[Ir]&&!r?!1:this[Cs]?(lh(()=>this[IV](r)),!0):this[IV](r);if(e==="end")return this[W8]();if(e==="close"){if(this[RO]=!0,!this[kc]&&!this[Mn])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[ah]=r,super.emit(CV,r);let o=!this[uh]||this.listeners("error").length?super.emit("error",r):!1;return this[Ca](),o}else if(e==="resume"){let o=super.emit("resume");return this[Ca](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let i=super.emit(e,...n);return this[Ca](),i}[IV](e){for(let r of this[Xr])r.dest.write(e)===!1&&this.pause();let n=this[Ui]?!1:super.emit("data",e);return this[Ca](),n}[W8](){return this[kc]?!1:(this[kc]=!0,this.readable=!1,this[Cs]?(lh(()=>this[MV]()),!0):this[MV]())}[MV](){if(this[dd]){let n=this[dd].end();if(n){for(let r of this[Xr])r.dest.write(n);this[Ui]||super.emit("data",n)}}for(let n of this[Xr])n.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Ir]||(e.dataLength=0);let n=this.promise();return this.on("data",r=>{e.push(r),this[Ir]||(e.dataLength+=r.length)}),await n,e}async concat(){if(this[Ir])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[Wo]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,n)=>{this.on(Mn,()=>n(new Error("stream destroyed"))),this.on("error",r=>n(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Ui]=!1;let e=!1,n=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return n();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[Oa])return n();let o,s,a=E=>{this.off("data",c),this.off("end",u),this.off(Mn,l),n(),s(E)},c=E=>{this.off("error",a),this.off("end",u),this.off(Mn,l),this.pause(),o({value:E,done:!!this[Oa]})},u=()=>{this.off("error",a),this.off("data",c),this.off(Mn,l),n(),o({done:!0,value:void 0})},l=()=>a(new Error("stream destroyed"));return new Promise((E,d)=>{s=d,o=E,this.once(Mn,l),this.once("error",a),this.once("end",u),this.once("data",c)})},throw:n,return:n,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ui]=!1;let e=!1,n=()=>(this.pause(),this.off(CV,n),this.off(Mn,n),this.off("end",n),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return n();let i=this.read();return i===null?n():{done:!1,value:i}};return this.once("end",n),this.once(CV,n),this.once(Mn,n),{next:r,throw:n,return:n,[Symbol.iterator](){return this}}}destroy(e){if(this[Mn])return e?this.emit("error",e):this.emit(Mn),this;this[Mn]=!0,this[Ui]=!0,this[qn].length=0,this[Jn]=0;let n=this;return typeof n.close=="function"&&!this[RO]&&n.close(),e?this.emit("error",e):this.emit(Mn),this}static get isStream(){return Cot}};var Hot=Fot.native,Eh={lstatSync:xot,readdir:Vot,readdirSync:Got,readlinkSync:Bot,realpathSync:Hot,promises:{lstat:Yot,readdir:$ot,readlink:jot,realpath:Wot}},J8=t=>!t||t===Eh||t===kot?Eh:{...Eh,...t,promises:{...Eh.promises,...t.promises||{}}},Q8=/^\\\\\?\\([a-z]:)\\?$/i,Kot=t=>t.replace(/\//g,"\\").replace(Q8,"$1\\"),zot=/[\\\/]/,eo=0,eJ=1,tJ=2,Is=4,nJ=6,rJ=8,Xl=10,iJ=12,Qi=15,_h=~Qi,yV=16,z8=32,dh=64,Ko=128,MO=256,DO=512,Z8=dh|Ko|DO,Zot=1023,bV=t=>t.isFile()?rJ:t.isDirectory()?Is:t.isSymbolicLink()?Xl:t.isCharacterDevice()?tJ:t.isBlockDevice()?nJ:t.isSocket()?iJ:t.isFIFO()?eJ:eo,X8=new Map,fh=t=>{let e=X8.get(t);if(e)return e;let n=t.normalize("NFKD");return X8.set(t,n),n},q8=new Map,PO=t=>{let e=q8.get(t);if(e)return e;let n=fh(t.toLowerCase());return q8.set(t,n),n},LO=class extends sh{constructor(){super({max:256})}},UV=class extends sh{constructor(e=16*1024){super({maxSize:e,sizeCalculation:n=>n.length+1})}},oJ=Symbol("PathScurry setAsCwd"),Mr=class{name;root;roots;parent;nocase;isCWD=!1;#e;#n;get dev(){return this.#n}#t;get mode(){return this.#t}#a;get nlink(){return this.#a}#d;get uid(){return this.#d}#p;get gid(){return this.#p}#c;get rdev(){return this.#c}#l;get blksize(){return this.#l}#r;get ino(){return this.#r}#i;get size(){return this.#i}#o;get blocks(){return this.#o}#_;get atimeMs(){return this.#_}#s;get mtimeMs(){return this.#s}#E;get ctimeMs(){return this.#E}#S;get birthtimeMs(){return this.#S}#f;get atime(){return this.#f}#T;get mtime(){return this.#T}#C;get ctime(){return this.#C}#m;get birthtime(){return this.#m}#A;#O;#h;#N;#D;#P;#u;#L;#y;#v;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,n=eo,r,i,o,s,a){this.name=e,this.#A=o?PO(e):fh(e),this.#u=n&Zot,this.nocase=o,this.roots=i,this.root=r||this,this.#L=s,this.#h=a.fullpath,this.#D=a.relative,this.#P=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=J8(a.fs)}depth(){return this.#O!==void 0?this.#O:this.parent?this.#O=this.parent.depth()+1:this.#O=0}childrenCache(){return this.#L}resolve(e){if(!e)return this;let n=this.getRootString(e),i=e.substring(n.length).split(this.splitSep);return n?this.getRoot(n).#U(i):this.#U(i)}#U(e){let n=this;for(let r of e)n=n.child(r);return n}children(){let e=this.#L.get(this);if(e)return e;let n=Object.assign([],{provisional:0});return this.#L.set(this,n),this.#u&=~yV,n}child(e,n){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),i=this.nocase?PO(e):fh(e);for(let c of r)if(c.#A===i)return c;let o=this.parent?this.sep:"",s=this.#h?this.#h+o+e:void 0,a=this.newChild(e,eo,{...n,parent:this,fullpath:s});return this.canReaddir()||(a.#u|=Ko),r.push(a),a}relative(){if(this.isCWD)return"";if(this.#D!==void 0)return this.#D;let e=this.name,n=this.parent;if(!n)return this.#D=this.name;let r=n.relative();return r+(!r||!n.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,n=this.parent;if(!n)return this.#P=this.fullpathPosix();let r=n.relativePosix();return r+(!r||!n.parent?"":"/")+e}fullpath(){if(this.#h!==void 0)return this.#h;let e=this.name,n=this.parent;if(!n)return this.#h=this.name;let i=n.fullpath()+(n.parent?this.sep:"")+e;return this.#h=i}fullpathPosix(){if(this.#N!==void 0)return this.#N;if(this.sep==="/")return this.#N=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#N=`//?/${i}`:this.#N=i}let e=this.parent,n=e.fullpathPosix(),r=n+(!n||!e.parent?"":"/")+this.name;return this.#N=r}isUnknown(){return(this.#u&Qi)===eo}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(this.#u&Qi)===rJ}isDirectory(){return(this.#u&Qi)===Is}isCharacterDevice(){return(this.#u&Qi)===tJ}isBlockDevice(){return(this.#u&Qi)===nJ}isFIFO(){return(this.#u&Qi)===eJ}isSocket(){return(this.#u&Qi)===iJ}isSymbolicLink(){return(this.#u&Xl)===Xl}lstatCached(){return this.#u&z8?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#v}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#u&Qi;return!(e!==eo&&e!==Xl||this.#u&MO||this.#u&Ko)}calledReaddir(){return!!(this.#u&yV)}isENOENT(){return!!(this.#u&Ko)}isNamed(e){return this.nocase?this.#A===PO(e):this.#A===fh(e)}async readlink(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let n=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(n);if(r)return this.#y=r}catch(n){this.#R(n.code);return}}readlinkSync(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let n=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(n);if(r)return this.#y=r}catch(n){this.#R(n.code);return}}#B(e){this.#u|=yV;for(let n=e.provisional;n<e.length;n++){let r=e[n];r&&r.#M()}}#M(){this.#u&Ko||(this.#u=(this.#u|Ko)&_h,this.#b())}#b(){let e=this.children();e.provisional=0;for(let n of e)n.#M()}#w(){this.#u|=DO,this.#x()}#x(){if(this.#u&dh)return;let e=this.#u;(e&Qi)===Is&&(e&=_h),this.#u=e|dh,this.#b()}#V(e=""){e==="ENOTDIR"||e==="EPERM"?this.#x():e==="ENOENT"?this.#M():this.children().provisional=0}#g(e=""){e==="ENOTDIR"?this.parent.#x():e==="ENOENT"&&this.#M()}#R(e=""){let n=this.#u;n|=MO,e==="ENOENT"&&(n|=Ko),(e==="EINVAL"||e==="UNKNOWN")&&(n&=_h),this.#u=n,e==="ENOTDIR"&&this.parent&&this.parent.#x()}#G(e,n){return this.#F(e,n)||this.#H(e,n)}#H(e,n){let r=bV(e),i=this.newChild(e.name,r,{parent:this}),o=i.#u&Qi;return o!==Is&&o!==Xl&&o!==eo&&(i.#u|=dh),n.unshift(i),n.provisional++,i}#F(e,n){for(let r=n.provisional;r<n.length;r++){let i=n[r];if((this.nocase?PO(e.name):fh(e.name))===i.#A)return this.#I(e,i,r,n)}}#I(e,n,r,i){let o=n.name;return n.#u=n.#u&_h|bV(e),o!==e.name&&(n.name=e.name),r!==i.provisional&&(r===i.length-1?i.pop():i.splice(r,1),i.unshift(n)),i.provisional++,n}async lstat(){if((this.#u&Ko)===0)try{return this.#$(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#g(e.code)}}lstatSync(){if((this.#u&Ko)===0)try{return this.#$(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#g(e.code)}}#$(e){let{atime:n,atimeMs:r,birthtime:i,birthtimeMs:o,blksize:s,blocks:a,ctime:c,ctimeMs:u,dev:l,gid:E,ino:d,mode:f,mtime:T,mtimeMs:p,nlink:S,rdev:m,size:O,uid:h}=e;this.#f=n,this.#_=r,this.#m=i,this.#S=o,this.#l=s,this.#o=a,this.#C=c,this.#E=u,this.#n=l,this.#p=E,this.#r=d,this.#t=f,this.#T=T,this.#s=p,this.#a=S,this.#c=m,this.#i=O,this.#d=h;let C=bV(e);this.#u=this.#u&_h|C|z8,C!==eo&&C!==Is&&C!==Xl&&(this.#u|=dh)}#Y=[];#k=!1;#j(e){this.#k=!1;let n=this.#Y.slice();this.#Y.length=0,n.forEach(r=>r(null,e))}readdirCB(e,n=!1){if(!this.canReaddir()){n?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let o=r.slice(0,r.provisional);n?e(null,o):queueMicrotask(()=>e(null,o));return}if(this.#Y.push(e),this.#k)return;this.#k=!0;let i=this.fullpath();this.#e.readdir(i,{withFileTypes:!0},(o,s)=>{if(o)this.#V(o.code),r.provisional=0;else{for(let a of s)this.#G(a,r);this.#B(r)}this.#j(r.slice(0,r.provisional))})}#W;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let n=this.fullpath();if(this.#W)await this.#W;else{let r=()=>{};this.#W=new Promise(i=>r=i);try{for(let i of await this.#e.promises.readdir(n,{withFileTypes:!0}))this.#G(i,e);this.#B(e)}catch(i){this.#V(i.code),e.provisional=0}this.#W=void 0,r()}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 n=this.fullpath();try{for(let r of this.#e.readdirSync(n,{withFileTypes:!0}))this.#G(r,e);this.#B(e)}catch(r){this.#V(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#u&Z8)return!1;let e=Qi&this.#u;return e===eo||e===Is||e===Xl}shouldWalk(e,n){return(this.#u&Is)===Is&&!(this.#u&Z8)&&!e.has(this)&&(!n||n(this))}async realpath(){if(this.#v)return this.#v;if(!((DO|MO|Ko)&this.#u))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#v=this.resolve(e)}catch{this.#w()}}realpathSync(){if(this.#v)return this.#v;if(!((DO|MO|Ko)&this.#u))try{let e=this.#e.realpathSync(this.fullpath());return this.#v=this.resolve(e)}catch{this.#w()}}[oJ](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let n=new Set([]),r=[],i=this;for(;i&&i.parent;)n.add(i),i.#D=r.join(this.sep),i.#P=r.join("/"),i=i.parent,r.push("..");for(i=e;i&&i.parent&&!n.has(i);)i.#D=void 0,i.#P=void 0,i=i.parent}},yO=class t extends Mr{sep="\\";splitSep=zot;constructor(e,n=eo,r,i,o,s,a){super(e,n,r,i,o,s,a)}newChild(e,n=eo,r={}){return new t(e,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return vV.parse(e).root}getRoot(e){if(e=Kot(e.toUpperCase()),e===this.root.name)return this.root;for(let[n,r]of Object.entries(this.roots))if(this.sameRoot(e,n))return this.roots[e]=r;return this.roots[e]=new Td(e,this).root}sameRoot(e,n=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Q8,"$1\\"),e===n}},bO=class t extends Mr{splitSep="/";sep="/";constructor(e,n=eo,r,i,o,s,a){super(e,n,r,i,o,s,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,n=eo,r={}){return new t(e,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}},vO=class{root;rootPath;roots;cwd;#e;#n;#t;nocase;#a;constructor(e=process.cwd(),n,r,{nocase:i,childrenCacheSize:o=16*1024,fs:s=Eh}={}){this.#a=J8(s),(e instanceof URL||e.startsWith("file://"))&&(e=wot(e));let a=n.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new LO,this.#n=new LO,this.#t=new UV(o);let c=a.substring(this.rootPath.length).split(r);if(c.length===1&&!c[0]&&c.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#a),this.roots[this.rootPath]=this.root;let u=this.root,l=c.length-1,E=n.sep,d=this.rootPath,f=!1;for(let T of c){let p=l--;u=u.child(T,{relative:new Array(p).fill("..").join(E),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(f?"":E)+T}),f=!0}this.cwd=u}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#t}resolve(...e){let n="";for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(!s||s===".")&&(n=n?`${s}/${n}`:s,this.isAbsolute(s)))break}let r=this.#e.get(n);if(r!==void 0)return r;let i=this.cwd.resolve(n).fullpath();return this.#e.set(n,i),i}resolvePosix(...e){let n="";for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(!s||s===".")&&(n=n?`${s}/${n}`:s,this.isAbsolute(s)))break}let r=this.#n.get(n);if(r!==void 0)return r;let i=this.cwd.resolve(n).fullpathPosix();return this.#n.set(n,i),i}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,n={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r}=n;if(e.canReaddir()){let i=await e.readdir();return r?i:i.map(o=>o.name)}else return[]}readdirSync(e=this.cwd,n={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0}=n;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(i=>i.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:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=await e.readlink();return n?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return n?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=await e.realpath();return n?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return n?r:r?.fullpath()}async walk(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=[];(!o||o(e))&&a.push(r?e:e.fullpath());let c=new Set,u=(E,d)=>{c.add(E),E.readdirCB((f,T)=>{if(f)return d(f);let p=T.length;if(!p)return d();let S=()=>{--p===0&&d()};for(let m of T)(!o||o(m))&&a.push(r?m:m.fullpath()),i&&m.isSymbolicLink()?m.realpath().then(O=>O?.isUnknown()?O.lstat():O).then(O=>O?.shouldWalk(c,s)?u(O,S):S()):m.shouldWalk(c,s)?u(m,S):S()},!0)},l=e;return new Promise((E,d)=>{u(l,f=>{if(f)return d(f);E(a)})})}walkSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=[];(!o||o(e))&&a.push(r?e:e.fullpath());let c=new Set([e]);for(let u of c){let l=u.readdirSync();for(let E of l){(!o||o(E))&&a.push(r?E:E.fullpath());let d=E;if(E.isSymbolicLink()){if(!(i&&(d=E.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(c,s)&&c.add(d)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,n={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd),this.stream(e,n)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n;(!o||o(e))&&(yield r?e:e.fullpath());let a=new Set([e]);for(let c of a){let u=c.readdirSync();for(let l of u){(!o||o(l))&&(yield r?l:l.fullpath());let E=l;if(l.isSymbolicLink()){if(!(i&&(E=l.realpathSync())))continue;E.isUnknown()&&E.lstatSync()}E.shouldWalk(a,s)&&a.add(E)}}}stream(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=new Hc({objectMode:!0});(!o||o(e))&&a.write(r?e:e.fullpath());let c=new Set,u=[e],l=0,E=()=>{let d=!1;for(;!d;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let T=(S,m,O=!1)=>{if(S)return a.emit("error",S);if(i&&!O){let h=[];for(let C of m)C.isSymbolicLink()&&h.push(C.realpath().then(P=>P?.isUnknown()?P.lstat():P));if(h.length){Promise.all(h).then(()=>T(null,m,!0));return}}for(let h of m)h&&(!o||o(h))&&(a.write(r?h:h.fullpath())||(d=!0));l--;for(let h of m){let C=h.realpathCached()||h;C.shouldWalk(c,s)&&u.push(C)}d&&!a.flowing?a.once("drain",E):p||E()},p=!0;f.readdirCB(T,!0),p=!1}};return E(),a}streamSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=new Hc({objectMode:!0}),c=new Set;(!o||o(e))&&a.write(r?e:e.fullpath());let u=[e],l=0,E=()=>{let d=!1;for(;!d;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let T=f.readdirSync();for(let p of T)(!o||o(p))&&(a.write(r?p:p.fullpath())||(d=!0));l--;for(let p of T){let S=p;if(p.isSymbolicLink()){if(!(i&&(S=p.realpathSync())))continue;S.isUnknown()&&S.lstatSync()}S.shouldWalk(c,s)&&u.push(S)}}d&&!a.flowing&&a.once("drain",E)};return E(),a}chdir(e=this.cwd){let n=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[oJ](n)}},Td=class extends vO{sep="\\";constructor(e=process.cwd(),n={}){let{nocase:r=!0}=n;super(e,vV,"\\",{...n,nocase:r}),this.nocase=r;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(e){return vV.parse(e).root.toUpperCase()}newRoot(e){return new yO(this.rootPath,Is,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Sd=class extends vO{sep="/";constructor(e=process.cwd(),n={}){let{nocase:r=!1}=n;super(e,Uot,"/",{...n,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new bO(this.rootPath,Is,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Th=class extends Sd{constructor(e=process.cwd(),n={}){let{nocase:r=!0}=n;super(e,{...n,nocase:r})}},Vwt=process.platform==="win32"?yO:bO,sJ=process.platform==="win32"?Td:process.platform==="darwin"?Th:Sd;var Xot=t=>t.length>=1,qot=t=>t.length>=1,pd=class t{#e;#n;#t;length;#a;#d;#p;#c;#l;#r;#i=!0;constructor(e,n,r,i){if(!Xot(e))throw new TypeError("empty pattern list");if(!qot(n))throw new TypeError("empty glob list");if(n.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#n=n,this.#t=r,this.#a=i,this.#t===0){if(this.isUNC()){let[o,s,a,c,...u]=this.#e,[l,E,d,f,...T]=this.#n;u[0]===""&&(u.shift(),T.shift());let p=[o,s,a,c,""].join("/"),S=[l,E,d,f,""].join("/");this.#e=[p,...u],this.#n=[S,...T],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[o,...s]=this.#e,[a,...c]=this.#n;s[0]===""&&(s.shift(),c.shift());let u=o+"/",l=a+"/";this.#e=[u,...s],this.#n=[l,...c],this.length=this.#e.length}}}pattern(){return this.#e[this.#t]}isString(){return typeof this.#e[this.#t]=="string"}isGlobstar(){return this.#e[this.#t]===cr}isRegExp(){return this.#e[this.#t]instanceof RegExp}globString(){return this.#p=this.#p||(this.#t===0?this.isAbsolute()?this.#n[0]+this.#n.slice(1).join("/"):this.#n.join("/"):this.#n.slice(this.#t).join("/"))}hasMore(){return this.length>this.#t+1}rest(){return this.#d!==void 0?this.#d:this.hasMore()?(this.#d=new t(this.#e,this.#n,this.#t+1,this.#a),this.#d.#r=this.#r,this.#d.#l=this.#l,this.#d.#c=this.#c,this.#d):this.#d=null}isUNC(){let e=this.#e;return this.#l!==void 0?this.#l:this.#l=this.#a==="win32"&&this.#t===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#a==="win32"&&this.#t===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#r!==void 0?this.#r:this.#r=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#t===0?e:""}checkFollowGlobstar(){return!(this.#t===0||!this.isGlobstar()||!this.#i)}markFollowGlobstar(){return this.#t===0||!this.isGlobstar()||!this.#i?!1:(this.#i=!1,!0)}};var Jot=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",hd=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:n,nocase:r,noext:i,noglobstar:o,platform:s=Jot}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=s,this.mmopts={dot:!0,nobrace:n,nocase:r,noext:i,noglobstar:o,optimizationLevel:2,platform:s,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let n=new vi(e,this.mmopts);for(let r=0;r<n.set.length;r++){let i=n.set[r],o=n.globParts[r];if(!i||!o)throw new Error("invalid pattern object");for(;i[0]==="."&&o[0]===".";)i.shift(),o.shift();let s=new pd(i,o,0,this.platform),a=new vi(s.globString(),this.mmopts),c=o[o.length-1]==="**",u=s.isAbsolute();u?this.absolute.push(a):this.relative.push(a),c&&(u?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let n=e.fullpath(),r=`${n}/`,i=e.relative()||".",o=`${i}/`;for(let s of this.relative)if(s.match(i)||s.match(o))return!0;for(let s of this.absolute)if(s.match(n)||s.match(r))return!0;return!1}childrenIgnored(e){let n=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(r))return!0;for(let i of this.absoluteChildren)if(i.match(n))return!0;return!1}};var wV=class t{store;constructor(e=new Map){this.store=e}copy(){return new t(new Map(this.store))}hasWalked(e,n){return this.store.get(e.fullpath())?.has(n.globString())}storeWalked(e,n){let r=e.fullpath(),i=this.store.get(r);i?i.add(n.globString()):this.store.set(r,new Set([n.globString()]))}},xV=class{store=new Map;add(e,n,r){let i=(n?2:0)|(r?1:0),o=this.store.get(e);this.store.set(e,o===void 0?i:i&o)}entries(){return[...this.store.entries()].map(([e,n])=>[e,!!(n&2),!!(n&1)])}},VV=class{store=new Map;add(e,n){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(i=>i.globString()===n.globString())||r.push(n):this.store.set(e,[n])}get(e){let n=this.store.get(e);if(!n)throw new Error("attempting to walk unknown path");return n}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},Sh=class t{hasWalkedCache;matches=new xV;subwalks=new VV;patterns;follow;dot;opts;constructor(e,n){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=n?n.copy():new wV}processPatterns(e,n){this.patterns=n;let r=n.map(i=>[e,i]);for(let[i,o]of r){this.hasWalkedCache.storeWalked(i,o);let s=o.root(),a=o.isAbsolute()&&this.opts.absolute!==!1;if(s){i=i.resolve(s==="/"&&this.opts.root!==void 0?this.opts.root:s);let E=o.rest();if(E)o=E;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let c,u,l=!1;for(;typeof(c=o.pattern())=="string"&&(u=o.rest());)i=i.resolve(c),o=u,l=!0;if(c=o.pattern(),u=o.rest(),l){if(this.hasWalkedCache.hasWalked(i,o))continue;this.hasWalkedCache.storeWalked(i,o)}if(typeof c=="string"){let E=c===".."||c===""||c===".";this.matches.add(i.resolve(c),a,E);continue}else if(c===cr){(!i.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(i,o);let E=u?.pattern(),d=u?.rest();if(!u||(E===""||E===".")&&!d)this.matches.add(i,a,E===""||E===".");else if(E===".."){let f=i.parent||i;d?this.hasWalkedCache.hasWalked(f,d)||this.subwalks.add(f,d):this.matches.add(f,a,!0)}}else c instanceof RegExp&&this.subwalks.add(i,o)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new t(this.opts,this.hasWalkedCache)}filterEntries(e,n){let r=this.subwalks.get(e),i=this.child();for(let o of n)for(let s of r){let a=s.isAbsolute(),c=s.pattern(),u=s.rest();c===cr?i.testGlobstar(o,s,u,a):c instanceof RegExp?i.testRegExp(o,c,u,a):i.testString(o,c,u,a)}return i}testGlobstar(e,n,r,i){if((this.dot||!e.name.startsWith("."))&&(n.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,n):e.isSymbolicLink()&&(r&&n.checkFollowGlobstar()?this.subwalks.add(e,r):n.markFollowGlobstar()&&this.subwalks.add(e,n)))),r){let o=r.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(e,o,r.rest(),i);else if(o===".."){let s=e.parent||e;this.subwalks.add(s,r)}else o instanceof RegExp&&this.testRegExp(e,o,r.rest(),i)}}testRegExp(e,n,r,i){n.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,i,!1))}testString(e,n,r,i){e.isNamed(n)&&(r?this.subwalks.add(e,r):this.matches.add(e,i,!1))}};var Qot=(t,e)=>typeof t=="string"?new hd([t],e):Array.isArray(t)?new hd(t,e):t,UO=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#n;#t;signal;maxDepth;includeChildMatches;constructor(e,n,r){if(this.patterns=e,this.path=n,this.opts=r,this.#t=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#n=Qot(r.ignore??[],r),!this.includeChildMatches&&typeof this.#n.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#a(e){return this.seen.has(e)||!!this.#n?.ignored?.(e)}#d(e){return!!this.#n?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,n){if(n&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let o=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let s=await o.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(o,n)}matchCheckTest(e,n){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!n||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#a(e)?e:void 0}matchCheckSync(e,n){if(n&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let o=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let s=o.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(o,n)}matchFinish(e,n){if(this.#a(e))return;if(!this.includeChildMatches&&this.#n?.add){let o=`${e.relativePosix()}/**`;this.#n.add(o)}let r=this.opts.absolute===void 0?n:this.opts.absolute;this.seen.add(e);let i=this.opts.mark&&e.isDirectory()?this.#t:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let o=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(o+i)}else{let o=this.opts.posix?e.relativePosix():e.relative(),s=this.opts.dotRelative&&!o.startsWith(".."+this.#t)?"."+this.#t:"";this.matchEmit(o?s+o+i:"."+i)}}async match(e,n,r){let i=await this.matchCheck(e,r);i&&this.matchFinish(i,n)}matchSync(e,n,r){let i=this.matchCheckSync(e,r);i&&this.matchFinish(i,n)}walkCB(e,n,r){this.signal?.aborted&&r(),this.walkCB2(e,n,new Sh(this.opts),r)}walkCB2(e,n,r,i){if(this.#d(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(e,n,r,i));return}r.processPatterns(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||(o++,this.match(a,c,u).then(()=>s()));for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let c=a.readdirCached();a.calledReaddir()?this.walkCB3(a,c,r,s):a.readdirCB((u,l)=>this.walkCB3(a,l,r,s),!0)}s()}walkCB3(e,n,r,i){r=r.filterEntries(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||(o++,this.match(a,c,u).then(()=>s()));for(let[a,c]of r.subwalks.entries())o++,this.walkCB2(a,c,r.child(),s);s()}walkCBSync(e,n,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,n,new Sh(this.opts),r)}walkCB2Sync(e,n,r,i){if(this.#d(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(e,n,r,i));return}r.processPatterns(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||this.matchSync(a,c,u);for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let c=a.readdirSync();this.walkCB3Sync(a,c,r,s)}s()}walkCB3Sync(e,n,r,i){r=r.filterEntries(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||this.matchSync(a,c,u);for(let[a,c]of r.subwalks.entries())o++,this.walkCB2Sync(a,c,r.child(),s);s()}},ph=class extends UO{matches=new Set;constructor(e,n,r){super(e,n,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,n)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?n(this.signal.reason):e(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}},hh=class extends UO{results;constructor(e,n,r){super(e,n,r),this.results=new Hc({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,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}};var tst=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",zo=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,n){if(!n)throw new TypeError("glob options required");if(this.withFileTypes=!!n.withFileTypes,this.signal=n.signal,this.follow=!!n.follow,this.dot=!!n.dot,this.dotRelative=!!n.dotRelative,this.nodir=!!n.nodir,this.mark=!!n.mark,n.cwd?(n.cwd instanceof URL||n.cwd.startsWith("file://"))&&(n.cwd=est(n.cwd)):this.cwd="",this.cwd=n.cwd||"",this.root=n.root,this.magicalBraces=!!n.magicalBraces,this.nobrace=!!n.nobrace,this.noext=!!n.noext,this.realpath=!!n.realpath,this.absolute=n.absolute,this.includeChildMatches=n.includeChildMatches!==!1,this.noglobstar=!!n.noglobstar,this.matchBase=!!n.matchBase,this.maxDepth=typeof n.maxDepth=="number"?n.maxDepth:1/0,this.stat=!!n.stat,this.ignore=n.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(c=>c.replace(/\\/g,"/"))),this.matchBase){if(n.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(c=>c.includes("/")?c:`./**/${c}`)}if(this.pattern=e,this.platform=n.platform||tst,this.opts={...n,platform:this.platform},n.scurry){if(this.scurry=n.scurry,n.nocase!==void 0&&n.nocase!==n.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let c=n.platform==="win32"?Td:n.platform==="darwin"?Th:n.platform?Sd:sJ;this.scurry=new c(this.cwd,{nocase:n.nocase,fs:n.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",i={...n,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},o=this.pattern.map(c=>new vi(c,i)),[s,a]=o.reduce((c,u)=>(c[0].push(...u.set),c[1].push(...u.globParts),c),[[],[]]);this.patterns=s.map((c,u)=>{let l=a[u];if(!l)throw new Error("invalid pattern object");return new pd(c,l,0,this.platform)})}async walk(){return[...await new ph(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 ph(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 hh(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 hh(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()}};var GV=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let n of t)if(new vi(n,e).hasMagic())return!0;return!1};function wO(t,e={}){return new zo(t,e).streamSync()}function cJ(t,e={}){return new zo(t,e).stream()}function uJ(t,e={}){return new zo(t,e).walkSync()}async function aJ(t,e={}){return new zo(t,e).walk()}function xO(t,e={}){return new zo(t,e).iterateSync()}function lJ(t,e={}){return new zo(t,e).iterate()}var nst=wO,rst=Object.assign(cJ,{sync:wO}),ist=xO,ost=Object.assign(lJ,{sync:xO}),sst=Object.assign(uJ,{stream:wO,iterate:xO}),md=Object.assign(aJ,{glob:aJ,globSync:uJ,sync:sst,globStream:cJ,stream:rst,globStreamSync:wO,streamSync:nst,globIterate:lJ,iterate:ost,globIterateSync:xO,iterateSync:ist,Glob:zo,hasMagic:GV,escape:ld,unescape:jo});md.glob=md;function VO(t,e){let{changedFiles:n}=e;return n.some(r=>t===r||t.endsWith(r)||r.endsWith(t))}function ast(t,e,n,r){let{fileChangeMap:i}=r,o=i.get(t);return o?o.status==="added"?!0:o.status==="removed"?!1:cst(o.patch,e,n):!1}function mh(t,e){return VO(t.file.path,e)&&ast(t.file.path,t.range.start.line,t.range.end.line,e)}function cst(t,e,n){let r=t.split(`
|
|
163
|
+
>>> no match, partial?`,e,d,n,f),d===c))}let p;if(typeof l=="string"?(p=E===l,this.debug("string match",l,E,p)):(p=l.test(E),this.debug("pattern match",l,E,p)),!p)return!1}if(s===c&&a===u)return!0;if(s===c)return r;if(a===u)return s===c-1&&e[s]==="";throw new Error("wtf?")}braceExpand(){return G8(this.pattern,this.options)}parse(e){ih(e);let n=this.options;if(e==="**")return cr;if(e==="")return"";let r,i=null;(r=e.match(oot))?i=n.dot?aot:sot:(r=e.match(Zit))?i=(n.nocase?n.dot?Qit:Jit:n.dot?qit:Xit)(r[1]):(r=e.match(cot))?i=(n.nocase?n.dot?lot:uot:n.dot?_ot:Eot)(r):(r=e.match(eot))?i=n.dot?not:tot:(r=e.match(rot))&&(i=iot);let o=ud.fromGlob(e,this.options).toMMPattern();return i&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:i}),o}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?Tot:n.dot?Sot:pot,i=new Set(n.nocase?["i"]:[]),o=e.map(c=>{let u=c.map(l=>{if(l instanceof RegExp)for(let E of l.flags.split(""))i.add(E);return typeof l=="string"?Rot(l):l===cr?cr:l._src});return u.forEach((l,E)=>{let d=u[E+1],f=u[E-1];l!==cr||f===cr||(f===void 0?d!==void 0&&d!==cr?u[E+1]="(?:\\/|"+r+"\\/)?"+d:u[E]=r:d===void 0?u[E-1]=f+"(?:\\/|"+r+")?":d!==cr&&(u[E-1]=f+"(?:\\/|\\/"+r+"\\/)"+d,u[E+1]=cr))}),u.filter(l=>l!==cr).join("/")}).join("|"),[s,a]=e.length>1?["(?:",")"]:["",""];o="^"+s+o+a+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,n=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&n)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let o=this.set;this.debug(this.pattern,"set",o);let s=i[i.length-1];if(!s)for(let a=i.length-2;!s&&a>=0;a--)s=i[a];for(let a=0;a<o.length;a++){let c=o[a],u=i;if(r.matchBase&&c.length===1&&(u=[s]),this.matchOne(u,c,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return Zr.defaults(e).Minimatch}};Zr.AST=ud;Zr.Minimatch=vi;Zr.escape=ld;Zr.unescape=jo;import{fileURLToPath as est}from"node:url";var _d=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,F8=new Set,RV=typeof process=="object"&&process?process:{},k8=(t,e,n,r)=>{typeof RV.emitWarning=="function"?RV.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},AO=globalThis.AbortController,B8=globalThis.AbortSignal;if(typeof AO>"u"){B8=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,i){this._onabort.push(i)}},AO=class{constructor(){e()}signal=new B8;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let i of this.signal._onabort)i(r);this.signal.onabort?.(r)}}};let t=RV.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,k8("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",e))}}var Not=t=>!F8.has(t),Cwt=Symbol("type"),Fc=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),H8=t=>Fc(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Ed:null:null,Ed=class extends Array{constructor(e){super(e),this.fill(0)}},NV=class t{heap;length;static#e=!1;static create(e){let n=H8(e);if(!n)return[];t.#e=!0;let r=new t(e,n);return t.#e=!1,r}constructor(e,n){if(!t.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},sh=class t{#e;#n;#t;#a;#d;#p;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#l;#r;#i;#o;#_;#s;#E;#S;#f;#T;#C;#m;#A;#O;#h;#N;static unsafeExposeInternals(e){return{starts:e.#m,ttls:e.#A,sizes:e.#C,keyMap:e.#r,keyList:e.#i,valList:e.#o,next:e.#_,prev:e.#s,get head(){return e.#E},get tail(){return e.#S},free:e.#f,isBackgroundFetch:n=>e.#R(n),backgroundFetch:(n,r,i,o)=>e.#g(n,r,i,o),moveToTail:n=>e.#H(n),indexes:n=>e.#b(n),rindexes:n=>e.#w(n),isStale:n=>e.#y(n)}}get max(){return this.#e}get maxSize(){return this.#n}get calculatedSize(){return this.#l}get size(){return this.#c}get fetchMethod(){return this.#d}get memoMethod(){return this.#p}get dispose(){return this.#t}get disposeAfter(){return this.#a}constructor(e){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:u,disposeAfter:l,noDisposeOnSet:E,noUpdateTTL:d,maxSize:f=0,maxEntrySize:T=0,sizeCalculation:p,fetchMethod:S,memoMethod:m,noDeleteOnFetchRejection:O,noDeleteOnStaleGet:h,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:P,ignoreFetchAbort:G}=e;if(n!==0&&!Fc(n))throw new TypeError("max option must be a nonnegative integer");let Y=n?H8(n):Array;if(!Y)throw new Error("invalid max value: "+n);if(this.#e=n,this.#n=f,this.maxEntrySize=T||this.#n,this.sizeCalculation=p,this.sizeCalculation){if(!this.#n&&!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(m!==void 0&&typeof m!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#p=m,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#d=S,this.#h=!!S,this.#r=new Map,this.#i=new Array(n).fill(void 0),this.#o=new Array(n).fill(void 0),this.#_=new Y(n),this.#s=new Y(n),this.#E=0,this.#S=0,this.#f=NV.create(n),this.#c=0,this.#l=0,typeof u=="function"&&(this.#t=u),typeof l=="function"?(this.#a=l,this.#T=[]):(this.#a=void 0,this.#T=void 0),this.#O=!!this.#t,this.#N=!!this.#a,this.noDisposeOnSet=!!E,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!O,this.allowStaleOnFetchRejection=!!C,this.allowStaleOnFetchAbort=!!P,this.ignoreFetchAbort=!!G,this.maxEntrySize!==0){if(this.#n!==0&&!Fc(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!Fc(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#v()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!h,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Fc(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!Fc(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#n){let re="LRU_CACHE_UNBOUNDED";Not(re)&&(F8.add(re),k8("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",re,t))}}getRemainingTTL(e){return this.#r.has(e)?1/0:0}#D(){let e=new Ed(this.#e),n=new Ed(this.#e);this.#A=e,this.#m=n,this.#L=(o,s,a=_d.now())=>{if(n[o]=s!==0?a:0,e[o]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#y(o)&&this.#F(this.#i[o],"expire")},s+1);c.unref&&c.unref()}},this.#P=o=>{n[o]=e[o]!==0?_d.now():0},this.#u=(o,s)=>{if(e[s]){let a=e[s],c=n[s];if(!a||!c)return;o.ttl=a,o.start=c,o.now=r||i();let u=o.now-c;o.remainingTTL=a-u}};let r=0,i=()=>{let o=_d.now();if(this.ttlResolution>0){r=o;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return o};this.getRemainingTTL=o=>{let s=this.#r.get(o);if(s===void 0)return 0;let a=e[s],c=n[s];if(!a||!c)return 1/0;let u=(r||i())-c;return a-u},this.#y=o=>{let s=n[o],a=e[o];return!!a&&!!s&&(r||i())-s>a}}#P=()=>{};#u=()=>{};#L=()=>{};#y=()=>!1;#v(){let e=new Ed(this.#e);this.#l=0,this.#C=e,this.#U=n=>{this.#l-=e[n],e[n]=0},this.#M=(n,r,i,o)=>{if(this.#R(r))return 0;if(!Fc(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(r,n),!Fc(i))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 i},this.#B=(n,r,i)=>{if(e[n]=r,this.#n){let o=this.#n-e[n];for(;this.#l>o;)this.#V(!0)}this.#l+=e[n],i&&(i.entrySize=r,i.totalCalculatedSize=this.#l)}}#U=e=>{};#B=(e,n,r)=>{};#M=(e,n,r,i)=>{if(r||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#b({allowStale:e=this.allowStale}={}){if(this.#c)for(let n=this.#S;!(!this.#x(n)||((e||!this.#y(n))&&(yield n),n===this.#E));)n=this.#s[n]}*#w({allowStale:e=this.allowStale}={}){if(this.#c)for(let n=this.#E;!(!this.#x(n)||((e||!this.#y(n))&&(yield n),n===this.#S));)n=this.#_[n]}#x(e){return e!==void 0&&this.#r.get(this.#i[e])===e}*entries(){for(let e of this.#b())this.#o[e]!==void 0&&this.#i[e]!==void 0&&!this.#R(this.#o[e])&&(yield[this.#i[e],this.#o[e]])}*rentries(){for(let e of this.#w())this.#o[e]!==void 0&&this.#i[e]!==void 0&&!this.#R(this.#o[e])&&(yield[this.#i[e],this.#o[e]])}*keys(){for(let e of this.#b()){let n=this.#i[e];n!==void 0&&!this.#R(this.#o[e])&&(yield n)}}*rkeys(){for(let e of this.#w()){let n=this.#i[e];n!==void 0&&!this.#R(this.#o[e])&&(yield n)}}*values(){for(let e of this.#b())this.#o[e]!==void 0&&!this.#R(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#w())this.#o[e]!==void 0&&!this.#R(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#b()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#i[r],this))return this.get(this.#i[r],n)}}forEach(e,n=this){for(let r of this.#b()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#i[r],this)}}rforEach(e,n=this){for(let r of this.#w()){let i=this.#o[r],o=this.#R(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#i[r],this)}}purgeStale(){let e=!1;for(let n of this.#w({allowStale:!0}))this.#y(n)&&(this.#F(this.#i[n],"expire"),e=!0);return e}info(e){let n=this.#r.get(e);if(n===void 0)return;let r=this.#o[n],i=this.#R(r)?r.__staleWhileFetching:r;if(i===void 0)return;let o={value:i};if(this.#A&&this.#m){let s=this.#A[n],a=this.#m[n];if(s&&a){let c=s-(_d.now()-a);o.ttl=c,o.start=Date.now()}}return this.#C&&(o.size=this.#C[n]),o}dump(){let e=[];for(let n of this.#b({allowStale:!0})){let r=this.#i[n],i=this.#o[n],o=this.#R(i)?i.__staleWhileFetching:i;if(o===void 0||r===void 0)continue;let s={value:o};if(this.#A&&this.#m){s.ttl=this.#A[n];let a=_d.now()-this.#m[n];s.start=Math.floor(Date.now()-a)}this.#C&&(s.size=this.#C[n]),e.unshift([r,s])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let i=Date.now()-r.start;r.start=_d.now()-i}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,l=this.#M(e,n,r.size||0,a);if(this.maxEntrySize&&l>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#F(e,"set"),this;let E=this.#c===0?void 0:this.#r.get(e);if(E===void 0)E=this.#c===0?this.#S:this.#f.length!==0?this.#f.pop():this.#c===this.#e?this.#V(!1):this.#c,this.#i[E]=e,this.#o[E]=n,this.#r.set(e,E),this.#_[this.#S]=E,this.#s[E]=this.#S,this.#S=E,this.#c++,this.#B(E,l,c),c&&(c.set="add"),u=!1;else{this.#H(E);let d=this.#o[E];if(n!==d){if(this.#h&&this.#R(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!s&&(this.#O&&this.#t?.(f,e,"set"),this.#N&&this.#T?.push([f,e,"set"]))}else s||(this.#O&&this.#t?.(d,e,"set"),this.#N&&this.#T?.push([d,e,"set"]));if(this.#U(E),this.#B(E,l,c),this.#o[E]=n,c){c.set="replace";let f=d&&this.#R(d)?d.__staleWhileFetching:d;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update")}if(i!==0&&!this.#A&&this.#D(),this.#A&&(u||this.#L(E,i,o),c&&this.#u(c,E)),!s&&this.#N&&this.#T){let d=this.#T,f;for(;f=d?.shift();)this.#a?.(...f)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#E];if(this.#V(!0),this.#R(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#N&&this.#T){let e=this.#T,n;for(;n=e?.shift();)this.#a?.(...n)}}}#V(e){let n=this.#E,r=this.#i[n],i=this.#o[n];return this.#h&&this.#R(i)?i.__abortController.abort(new Error("evicted")):(this.#O||this.#N)&&(this.#O&&this.#t?.(i,r,"evict"),this.#N&&this.#T?.push([i,r,"evict"])),this.#U(n),e&&(this.#i[n]=void 0,this.#o[n]=void 0,this.#f.push(n)),this.#c===1?(this.#E=this.#S=0,this.#f.length=0):this.#E=this.#_[n],this.#r.delete(r),this.#c--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:i}=n,o=this.#r.get(e);if(o!==void 0){let s=this.#o[o];if(this.#R(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#y(o))i&&(i.has="stale",this.#u(i,o));else return r&&this.#P(o),i&&(i.has="hit",this.#u(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,i=this.#r.get(e);if(i===void 0||!r&&this.#y(i))return;let o=this.#o[i];return this.#R(o)?o.__staleWhileFetching:o}#g(e,n,r,i){let o=n===void 0?void 0:this.#o[n];if(this.#R(o))return o;let s=new AO,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:r,context:i},u=(p,S=!1)=>{let{aborted:m}=s.signal,O=r.ignoreFetchAbort&&p!==void 0;if(r.status&&(m&&!S?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,O&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),m&&!O&&!S)return E(s.signal.reason);let h=f;return this.#o[n]===f&&(p===void 0?h.__staleWhileFetching?this.#o[n]=h.__staleWhileFetching:this.#F(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,p,c.options))),p},l=p=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=p),E(p)),E=p=>{let{aborted:S}=s.signal,m=S&&r.allowStaleOnFetchAbort,O=m||r.allowStaleOnFetchRejection,h=O||r.noDeleteOnFetchRejection,C=f;if(this.#o[n]===f&&(!h||C.__staleWhileFetching===void 0?this.#F(e,"fetch"):m||(this.#o[n]=C.__staleWhileFetching)),O)return r.status&&C.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),C.__staleWhileFetching;if(C.__returned===C)throw p},d=(p,S)=>{let m=this.#d?.(e,o,c);m&&m instanceof Promise&&m.then(O=>p(O===void 0?void 0:O),S),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(p(void 0),r.allowStaleOnFetchAbort&&(p=O=>u(O,!0)))})};r.status&&(r.status.fetchDispatched=!0);let f=new Promise(d).then(u,l),T=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,T,{...c.options,status:void 0}),n=this.#r.get(e)):this.#o[n]=T,T}#R(e){if(!this.#h)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof AO}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:E=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:T=this.allowStaleOnFetchAbort,context:p,forceRefresh:S=!1,status:m,signal:O}=n;if(!this.#h)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:m});let h={allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:E,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:T,ignoreFetchAbort:f,status:m,signal:O},C=this.#r.get(e);if(C===void 0){m&&(m.fetch="miss");let P=this.#g(e,C,h,p);return P.__returned=P}else{let P=this.#o[C];if(this.#R(P)){let q=r&&P.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",q&&(m.returnedStale=!0)),q?P.__staleWhileFetching:P.__returned=P}let G=this.#y(C);if(!S&&!G)return m&&(m.fetch="hit"),this.#H(C),i&&this.#P(C),m&&this.#u(m,C),P;let Y=this.#g(e,C,h,p),W=Y.__staleWhileFetching!==void 0&&r;return m&&(m.fetch=G?"stale":"refresh",W&&G&&(m.returnedStale=!0)),W?Y.__staleWhileFetching:Y.__returned=Y}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#p;if(!r)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:o,...s}=n,a=this.get(e,s);if(!o&&a!==void 0)return a;let c=r(e,a,{options:s,context:i});return this.set(e,c,s),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#r.get(e);if(a!==void 0){let c=this.#o[a],u=this.#R(c);return s&&this.#u(s,a),this.#y(a)?(s&&(s.get="stale"),u?(s&&r&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?c.__staleWhileFetching:void 0):(o||this.#F(e,"expire"),s&&r&&(s.returnedStale=!0),r?c:void 0)):(s&&(s.get="hit"),u?c.__staleWhileFetching:(this.#H(a),i&&this.#P(a),c))}else s&&(s.get="miss")}#G(e,n){this.#s[n]=e,this.#_[e]=n}#H(e){e!==this.#S&&(e===this.#E?this.#E=this.#_[e]:this.#G(this.#s[e],this.#_[e]),this.#G(this.#S,e),this.#S=e)}delete(e){return this.#F(e,"delete")}#F(e,n){let r=!1;if(this.#c!==0){let i=this.#r.get(e);if(i!==void 0)if(r=!0,this.#c===1)this.#I(n);else{this.#U(i);let o=this.#o[i];if(this.#R(o)?o.__abortController.abort(new Error("deleted")):(this.#O||this.#N)&&(this.#O&&this.#t?.(o,e,n),this.#N&&this.#T?.push([o,e,n])),this.#r.delete(e),this.#i[i]=void 0,this.#o[i]=void 0,i===this.#S)this.#S=this.#s[i];else if(i===this.#E)this.#E=this.#_[i];else{let s=this.#s[i];this.#_[s]=this.#_[i];let a=this.#_[i];this.#s[a]=this.#s[i]}this.#c--,this.#f.push(i)}}if(this.#N&&this.#T?.length){let i=this.#T,o;for(;o=i?.shift();)this.#a?.(...o)}return r}clear(){return this.#I("delete")}#I(e){for(let n of this.#w({allowStale:!0})){let r=this.#o[n];if(this.#R(r))r.__abortController.abort(new Error("deleted"));else{let i=this.#i[n];this.#O&&this.#t?.(r,i,e),this.#N&&this.#T?.push([r,i,e])}}if(this.#r.clear(),this.#o.fill(void 0),this.#i.fill(void 0),this.#A&&this.#m&&(this.#A.fill(0),this.#m.fill(0)),this.#C&&this.#C.fill(0),this.#E=0,this.#S=0,this.#f.length=0,this.#l=0,this.#c=0,this.#N&&this.#T){let n=this.#T,r;for(;r=n?.shift();)this.#a?.(...r)}}};import{posix as Uot,win32 as vV}from"node:path";import{fileURLToPath as wot}from"node:url";import{lstatSync as xot,readdir as Vot,readdirSync as Got,readlinkSync as Bot,realpathSync as Fot}from"fs";import*as kot from"node:fs";import{lstat as Yot,readdir as $ot,readlink as jot,realpath as Wot}from"node:fs/promises";import{EventEmitter as LV}from"node:events";import K8 from"node:stream";import{StringDecoder as Oot}from"node:string_decoder";var Y8=typeof process=="object"&&process?process:{stdout:null,stderr:null},Cot=t=>!!t&&typeof t=="object"&&(t instanceof Hc||t instanceof K8||Iot(t)||Mot(t)),Iot=t=>!!t&&typeof t=="object"&&t instanceof LV&&typeof t.pipe=="function"&&t.pipe!==K8.Writable.prototype.pipe,Mot=t=>!!t&&typeof t=="object"&&t instanceof LV&&typeof t.write=="function"&&typeof t.end=="function",Oa=Symbol("EOF"),Ca=Symbol("maybeEmitEnd"),kc=Symbol("emittedEnd"),gO=Symbol("emittingEnd"),ah=Symbol("emittedError"),RO=Symbol("closed"),$8=Symbol("read"),NO=Symbol("flush"),j8=Symbol("flushChunk"),Wo=Symbol("encoding"),dd=Symbol("decoder"),Xn=Symbol("flowing"),ch=Symbol("paused"),fd=Symbol("resume"),qn=Symbol("buffer"),Xr=Symbol("pipes"),Jn=Symbol("bufferLength"),OV=Symbol("bufferPush"),OO=Symbol("bufferShift"),Ir=Symbol("objectMode"),Mn=Symbol("destroyed"),CV=Symbol("error"),IV=Symbol("emitData"),W8=Symbol("emitEnd"),MV=Symbol("emitEnd2"),Cs=Symbol("async"),PV=Symbol("abort"),CO=Symbol("aborted"),uh=Symbol("signal"),Zl=Symbol("dataListeners"),Ui=Symbol("discarded"),lh=t=>Promise.resolve().then(t),Pot=t=>t(),Dot=t=>t==="end"||t==="finish"||t==="prefinish",Lot=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,yot=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),IO=class{src;dest;opts;ondrain;constructor(e,n,r){this.src=e,this.dest=n,this.opts=r,this.ondrain=()=>e[fd](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},DV=class extends IO{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,n,r){super(e,n,r),this.proxyErrors=i=>n.emit("error",i),e.on("error",this.proxyErrors)}},bot=t=>!!t.objectMode,vot=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Hc=class extends LV{[Xn]=!1;[ch]=!1;[Xr]=[];[qn]=[];[Ir];[Wo];[Cs];[dd];[Oa]=!1;[kc]=!1;[gO]=!1;[RO]=!1;[ah]=null;[Jn]=0;[Mn]=!1;[uh];[CO]=!1;[Zl]=0;[Ui]=!1;writable=!0;readable=!0;constructor(...e){let n=e[0]||{};if(super(),n.objectMode&&typeof n.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");bot(n)?(this[Ir]=!0,this[Wo]=null):vot(n)?(this[Wo]=n.encoding,this[Ir]=!1):(this[Ir]=!1,this[Wo]=null),this[Cs]=!!n.async,this[dd]=this[Wo]?new Oot(this[Wo]):null,n&&n.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[qn]}),n&&n.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Xr]});let{signal:r}=n;r&&(this[uh]=r,r.aborted?this[PV]():r.addEventListener("abort",()=>this[PV]()))}get bufferLength(){return this[Jn]}get encoding(){return this[Wo]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ir]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Cs]}set async(e){this[Cs]=this[Cs]||!!e}[PV](){this[CO]=!0,this.emit("abort",this[uh]?.reason),this.destroy(this[uh]?.reason)}get aborted(){return this[CO]}set aborted(e){}write(e,n,r){if(this[CO])return!1;if(this[Oa])throw new Error("write after end");if(this[Mn])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof n=="function"&&(r=n,n="utf8"),n||(n="utf8");let i=this[Cs]?lh:Pot;if(!this[Ir]&&!Buffer.isBuffer(e)){if(yot(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Lot(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ir]?(this[Xn]&&this[Jn]!==0&&this[NO](!0),this[Xn]?this.emit("data",e):this[OV](e),this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn]):e.length?(typeof e=="string"&&!(n===this[Wo]&&!this[dd]?.lastNeed)&&(e=Buffer.from(e,n)),Buffer.isBuffer(e)&&this[Wo]&&(e=this[dd].write(e)),this[Xn]&&this[Jn]!==0&&this[NO](!0),this[Xn]?this.emit("data",e):this[OV](e),this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn]):(this[Jn]!==0&&this.emit("readable"),r&&i(r),this[Xn])}read(e){if(this[Mn])return null;if(this[Ui]=!1,this[Jn]===0||e===0||e&&e>this[Jn])return this[Ca](),null;this[Ir]&&(e=null),this[qn].length>1&&!this[Ir]&&(this[qn]=[this[Wo]?this[qn].join(""):Buffer.concat(this[qn],this[Jn])]);let n=this[$8](e||null,this[qn][0]);return this[Ca](),n}[$8](e,n){if(this[Ir])this[OO]();else{let r=n;e===r.length||e===null?this[OO]():typeof r=="string"?(this[qn][0]=r.slice(e),n=r.slice(0,e),this[Jn]-=e):(this[qn][0]=r.subarray(e),n=r.subarray(0,e),this[Jn]-=e)}return this.emit("data",n),!this[qn].length&&!this[Oa]&&this.emit("drain"),n}end(e,n,r){return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n="utf8"),e!==void 0&&this.write(e,n),r&&this.once("end",r),this[Oa]=!0,this.writable=!1,(this[Xn]||!this[ch])&&this[Ca](),this}[fd](){this[Mn]||(!this[Zl]&&!this[Xr].length&&(this[Ui]=!0),this[ch]=!1,this[Xn]=!0,this.emit("resume"),this[qn].length?this[NO]():this[Oa]?this[Ca]():this.emit("drain"))}resume(){return this[fd]()}pause(){this[Xn]=!1,this[ch]=!0,this[Ui]=!1}get destroyed(){return this[Mn]}get flowing(){return this[Xn]}get paused(){return this[ch]}[OV](e){this[Ir]?this[Jn]+=1:this[Jn]+=e.length,this[qn].push(e)}[OO](){return this[Ir]?this[Jn]-=1:this[Jn]-=this[qn][0].length,this[qn].shift()}[NO](e=!1){do;while(this[j8](this[OO]())&&this[qn].length);!e&&!this[qn].length&&!this[Oa]&&this.emit("drain")}[j8](e){return this.emit("data",e),this[Xn]}pipe(e,n){if(this[Mn])return e;this[Ui]=!1;let r=this[kc];return n=n||{},e===Y8.stdout||e===Y8.stderr?n.end=!1:n.end=n.end!==!1,n.proxyErrors=!!n.proxyErrors,r?n.end&&e.end():(this[Xr].push(n.proxyErrors?new DV(this,e,n):new IO(this,e,n)),this[Cs]?lh(()=>this[fd]()):this[fd]()),e}unpipe(e){let n=this[Xr].find(r=>r.dest===e);n&&(this[Xr].length===1?(this[Xn]&&this[Zl]===0&&(this[Xn]=!1),this[Xr]=[]):this[Xr].splice(this[Xr].indexOf(n),1),n.unpipe())}addListener(e,n){return this.on(e,n)}on(e,n){let r=super.on(e,n);if(e==="data")this[Ui]=!1,this[Zl]++,!this[Xr].length&&!this[Xn]&&this[fd]();else if(e==="readable"&&this[Jn]!==0)super.emit("readable");else if(Dot(e)&&this[kc])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[ah]){let i=n;this[Cs]?lh(()=>i.call(this,this[ah])):i.call(this,this[ah])}return r}removeListener(e,n){return this.off(e,n)}off(e,n){let r=super.off(e,n);return e==="data"&&(this[Zl]=this.listeners("data").length,this[Zl]===0&&!this[Ui]&&!this[Xr].length&&(this[Xn]=!1)),r}removeAllListeners(e){let n=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Zl]=0,!this[Ui]&&!this[Xr].length&&(this[Xn]=!1)),n}get emittedEnd(){return this[kc]}[Ca](){!this[gO]&&!this[kc]&&!this[Mn]&&this[qn].length===0&&this[Oa]&&(this[gO]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[RO]&&this.emit("close"),this[gO]=!1)}emit(e,...n){let r=n[0];if(e!=="error"&&e!=="close"&&e!==Mn&&this[Mn])return!1;if(e==="data")return!this[Ir]&&!r?!1:this[Cs]?(lh(()=>this[IV](r)),!0):this[IV](r);if(e==="end")return this[W8]();if(e==="close"){if(this[RO]=!0,!this[kc]&&!this[Mn])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[ah]=r,super.emit(CV,r);let o=!this[uh]||this.listeners("error").length?super.emit("error",r):!1;return this[Ca](),o}else if(e==="resume"){let o=super.emit("resume");return this[Ca](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let i=super.emit(e,...n);return this[Ca](),i}[IV](e){for(let r of this[Xr])r.dest.write(e)===!1&&this.pause();let n=this[Ui]?!1:super.emit("data",e);return this[Ca](),n}[W8](){return this[kc]?!1:(this[kc]=!0,this.readable=!1,this[Cs]?(lh(()=>this[MV]()),!0):this[MV]())}[MV](){if(this[dd]){let n=this[dd].end();if(n){for(let r of this[Xr])r.dest.write(n);this[Ui]||super.emit("data",n)}}for(let n of this[Xr])n.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Ir]||(e.dataLength=0);let n=this.promise();return this.on("data",r=>{e.push(r),this[Ir]||(e.dataLength+=r.length)}),await n,e}async concat(){if(this[Ir])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[Wo]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,n)=>{this.on(Mn,()=>n(new Error("stream destroyed"))),this.on("error",r=>n(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Ui]=!1;let e=!1,n=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return n();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[Oa])return n();let o,s,a=E=>{this.off("data",c),this.off("end",u),this.off(Mn,l),n(),s(E)},c=E=>{this.off("error",a),this.off("end",u),this.off(Mn,l),this.pause(),o({value:E,done:!!this[Oa]})},u=()=>{this.off("error",a),this.off("data",c),this.off(Mn,l),n(),o({done:!0,value:void 0})},l=()=>a(new Error("stream destroyed"));return new Promise((E,d)=>{s=d,o=E,this.once(Mn,l),this.once("error",a),this.once("end",u),this.once("data",c)})},throw:n,return:n,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ui]=!1;let e=!1,n=()=>(this.pause(),this.off(CV,n),this.off(Mn,n),this.off("end",n),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return n();let i=this.read();return i===null?n():{done:!1,value:i}};return this.once("end",n),this.once(CV,n),this.once(Mn,n),{next:r,throw:n,return:n,[Symbol.iterator](){return this}}}destroy(e){if(this[Mn])return e?this.emit("error",e):this.emit(Mn),this;this[Mn]=!0,this[Ui]=!0,this[qn].length=0,this[Jn]=0;let n=this;return typeof n.close=="function"&&!this[RO]&&n.close(),e?this.emit("error",e):this.emit(Mn),this}static get isStream(){return Cot}};var Hot=Fot.native,Eh={lstatSync:xot,readdir:Vot,readdirSync:Got,readlinkSync:Bot,realpathSync:Hot,promises:{lstat:Yot,readdir:$ot,readlink:jot,realpath:Wot}},J8=t=>!t||t===Eh||t===kot?Eh:{...Eh,...t,promises:{...Eh.promises,...t.promises||{}}},Q8=/^\\\\\?\\([a-z]:)\\?$/i,Kot=t=>t.replace(/\//g,"\\").replace(Q8,"$1\\"),zot=/[\\\/]/,eo=0,eJ=1,tJ=2,Is=4,nJ=6,rJ=8,Xl=10,iJ=12,Qi=15,_h=~Qi,yV=16,z8=32,dh=64,Ko=128,MO=256,DO=512,Z8=dh|Ko|DO,Zot=1023,bV=t=>t.isFile()?rJ:t.isDirectory()?Is:t.isSymbolicLink()?Xl:t.isCharacterDevice()?tJ:t.isBlockDevice()?nJ:t.isSocket()?iJ:t.isFIFO()?eJ:eo,X8=new Map,fh=t=>{let e=X8.get(t);if(e)return e;let n=t.normalize("NFKD");return X8.set(t,n),n},q8=new Map,PO=t=>{let e=q8.get(t);if(e)return e;let n=fh(t.toLowerCase());return q8.set(t,n),n},LO=class extends sh{constructor(){super({max:256})}},UV=class extends sh{constructor(e=16*1024){super({maxSize:e,sizeCalculation:n=>n.length+1})}},oJ=Symbol("PathScurry setAsCwd"),Mr=class{name;root;roots;parent;nocase;isCWD=!1;#e;#n;get dev(){return this.#n}#t;get mode(){return this.#t}#a;get nlink(){return this.#a}#d;get uid(){return this.#d}#p;get gid(){return this.#p}#c;get rdev(){return this.#c}#l;get blksize(){return this.#l}#r;get ino(){return this.#r}#i;get size(){return this.#i}#o;get blocks(){return this.#o}#_;get atimeMs(){return this.#_}#s;get mtimeMs(){return this.#s}#E;get ctimeMs(){return this.#E}#S;get birthtimeMs(){return this.#S}#f;get atime(){return this.#f}#T;get mtime(){return this.#T}#C;get ctime(){return this.#C}#m;get birthtime(){return this.#m}#A;#O;#h;#N;#D;#P;#u;#L;#y;#v;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,n=eo,r,i,o,s,a){this.name=e,this.#A=o?PO(e):fh(e),this.#u=n&Zot,this.nocase=o,this.roots=i,this.root=r||this,this.#L=s,this.#h=a.fullpath,this.#D=a.relative,this.#P=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=J8(a.fs)}depth(){return this.#O!==void 0?this.#O:this.parent?this.#O=this.parent.depth()+1:this.#O=0}childrenCache(){return this.#L}resolve(e){if(!e)return this;let n=this.getRootString(e),i=e.substring(n.length).split(this.splitSep);return n?this.getRoot(n).#U(i):this.#U(i)}#U(e){let n=this;for(let r of e)n=n.child(r);return n}children(){let e=this.#L.get(this);if(e)return e;let n=Object.assign([],{provisional:0});return this.#L.set(this,n),this.#u&=~yV,n}child(e,n){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),i=this.nocase?PO(e):fh(e);for(let c of r)if(c.#A===i)return c;let o=this.parent?this.sep:"",s=this.#h?this.#h+o+e:void 0,a=this.newChild(e,eo,{...n,parent:this,fullpath:s});return this.canReaddir()||(a.#u|=Ko),r.push(a),a}relative(){if(this.isCWD)return"";if(this.#D!==void 0)return this.#D;let e=this.name,n=this.parent;if(!n)return this.#D=this.name;let r=n.relative();return r+(!r||!n.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,n=this.parent;if(!n)return this.#P=this.fullpathPosix();let r=n.relativePosix();return r+(!r||!n.parent?"":"/")+e}fullpath(){if(this.#h!==void 0)return this.#h;let e=this.name,n=this.parent;if(!n)return this.#h=this.name;let i=n.fullpath()+(n.parent?this.sep:"")+e;return this.#h=i}fullpathPosix(){if(this.#N!==void 0)return this.#N;if(this.sep==="/")return this.#N=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#N=`//?/${i}`:this.#N=i}let e=this.parent,n=e.fullpathPosix(),r=n+(!n||!e.parent?"":"/")+this.name;return this.#N=r}isUnknown(){return(this.#u&Qi)===eo}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(this.#u&Qi)===rJ}isDirectory(){return(this.#u&Qi)===Is}isCharacterDevice(){return(this.#u&Qi)===tJ}isBlockDevice(){return(this.#u&Qi)===nJ}isFIFO(){return(this.#u&Qi)===eJ}isSocket(){return(this.#u&Qi)===iJ}isSymbolicLink(){return(this.#u&Xl)===Xl}lstatCached(){return this.#u&z8?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#v}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#u&Qi;return!(e!==eo&&e!==Xl||this.#u&MO||this.#u&Ko)}calledReaddir(){return!!(this.#u&yV)}isENOENT(){return!!(this.#u&Ko)}isNamed(e){return this.nocase?this.#A===PO(e):this.#A===fh(e)}async readlink(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let n=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(n);if(r)return this.#y=r}catch(n){this.#R(n.code);return}}readlinkSync(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let n=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(n);if(r)return this.#y=r}catch(n){this.#R(n.code);return}}#B(e){this.#u|=yV;for(let n=e.provisional;n<e.length;n++){let r=e[n];r&&r.#M()}}#M(){this.#u&Ko||(this.#u=(this.#u|Ko)&_h,this.#b())}#b(){let e=this.children();e.provisional=0;for(let n of e)n.#M()}#w(){this.#u|=DO,this.#x()}#x(){if(this.#u&dh)return;let e=this.#u;(e&Qi)===Is&&(e&=_h),this.#u=e|dh,this.#b()}#V(e=""){e==="ENOTDIR"||e==="EPERM"?this.#x():e==="ENOENT"?this.#M():this.children().provisional=0}#g(e=""){e==="ENOTDIR"?this.parent.#x():e==="ENOENT"&&this.#M()}#R(e=""){let n=this.#u;n|=MO,e==="ENOENT"&&(n|=Ko),(e==="EINVAL"||e==="UNKNOWN")&&(n&=_h),this.#u=n,e==="ENOTDIR"&&this.parent&&this.parent.#x()}#G(e,n){return this.#F(e,n)||this.#H(e,n)}#H(e,n){let r=bV(e),i=this.newChild(e.name,r,{parent:this}),o=i.#u&Qi;return o!==Is&&o!==Xl&&o!==eo&&(i.#u|=dh),n.unshift(i),n.provisional++,i}#F(e,n){for(let r=n.provisional;r<n.length;r++){let i=n[r];if((this.nocase?PO(e.name):fh(e.name))===i.#A)return this.#I(e,i,r,n)}}#I(e,n,r,i){let o=n.name;return n.#u=n.#u&_h|bV(e),o!==e.name&&(n.name=e.name),r!==i.provisional&&(r===i.length-1?i.pop():i.splice(r,1),i.unshift(n)),i.provisional++,n}async lstat(){if((this.#u&Ko)===0)try{return this.#$(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#g(e.code)}}lstatSync(){if((this.#u&Ko)===0)try{return this.#$(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#g(e.code)}}#$(e){let{atime:n,atimeMs:r,birthtime:i,birthtimeMs:o,blksize:s,blocks:a,ctime:c,ctimeMs:u,dev:l,gid:E,ino:d,mode:f,mtime:T,mtimeMs:p,nlink:S,rdev:m,size:O,uid:h}=e;this.#f=n,this.#_=r,this.#m=i,this.#S=o,this.#l=s,this.#o=a,this.#C=c,this.#E=u,this.#n=l,this.#p=E,this.#r=d,this.#t=f,this.#T=T,this.#s=p,this.#a=S,this.#c=m,this.#i=O,this.#d=h;let C=bV(e);this.#u=this.#u&_h|C|z8,C!==eo&&C!==Is&&C!==Xl&&(this.#u|=dh)}#Y=[];#k=!1;#j(e){this.#k=!1;let n=this.#Y.slice();this.#Y.length=0,n.forEach(r=>r(null,e))}readdirCB(e,n=!1){if(!this.canReaddir()){n?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let o=r.slice(0,r.provisional);n?e(null,o):queueMicrotask(()=>e(null,o));return}if(this.#Y.push(e),this.#k)return;this.#k=!0;let i=this.fullpath();this.#e.readdir(i,{withFileTypes:!0},(o,s)=>{if(o)this.#V(o.code),r.provisional=0;else{for(let a of s)this.#G(a,r);this.#B(r)}this.#j(r.slice(0,r.provisional))})}#W;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let n=this.fullpath();if(this.#W)await this.#W;else{let r=()=>{};this.#W=new Promise(i=>r=i);try{for(let i of await this.#e.promises.readdir(n,{withFileTypes:!0}))this.#G(i,e);this.#B(e)}catch(i){this.#V(i.code),e.provisional=0}this.#W=void 0,r()}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 n=this.fullpath();try{for(let r of this.#e.readdirSync(n,{withFileTypes:!0}))this.#G(r,e);this.#B(e)}catch(r){this.#V(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#u&Z8)return!1;let e=Qi&this.#u;return e===eo||e===Is||e===Xl}shouldWalk(e,n){return(this.#u&Is)===Is&&!(this.#u&Z8)&&!e.has(this)&&(!n||n(this))}async realpath(){if(this.#v)return this.#v;if(!((DO|MO|Ko)&this.#u))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#v=this.resolve(e)}catch{this.#w()}}realpathSync(){if(this.#v)return this.#v;if(!((DO|MO|Ko)&this.#u))try{let e=this.#e.realpathSync(this.fullpath());return this.#v=this.resolve(e)}catch{this.#w()}}[oJ](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let n=new Set([]),r=[],i=this;for(;i&&i.parent;)n.add(i),i.#D=r.join(this.sep),i.#P=r.join("/"),i=i.parent,r.push("..");for(i=e;i&&i.parent&&!n.has(i);)i.#D=void 0,i.#P=void 0,i=i.parent}},yO=class t extends Mr{sep="\\";splitSep=zot;constructor(e,n=eo,r,i,o,s,a){super(e,n,r,i,o,s,a)}newChild(e,n=eo,r={}){return new t(e,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return vV.parse(e).root}getRoot(e){if(e=Kot(e.toUpperCase()),e===this.root.name)return this.root;for(let[n,r]of Object.entries(this.roots))if(this.sameRoot(e,n))return this.roots[e]=r;return this.roots[e]=new Td(e,this).root}sameRoot(e,n=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Q8,"$1\\"),e===n}},bO=class t extends Mr{splitSep="/";sep="/";constructor(e,n=eo,r,i,o,s,a){super(e,n,r,i,o,s,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,n=eo,r={}){return new t(e,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}},vO=class{root;rootPath;roots;cwd;#e;#n;#t;nocase;#a;constructor(e=process.cwd(),n,r,{nocase:i,childrenCacheSize:o=16*1024,fs:s=Eh}={}){this.#a=J8(s),(e instanceof URL||e.startsWith("file://"))&&(e=wot(e));let a=n.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new LO,this.#n=new LO,this.#t=new UV(o);let c=a.substring(this.rootPath.length).split(r);if(c.length===1&&!c[0]&&c.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#a),this.roots[this.rootPath]=this.root;let u=this.root,l=c.length-1,E=n.sep,d=this.rootPath,f=!1;for(let T of c){let p=l--;u=u.child(T,{relative:new Array(p).fill("..").join(E),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(f?"":E)+T}),f=!0}this.cwd=u}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#t}resolve(...e){let n="";for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(!s||s===".")&&(n=n?`${s}/${n}`:s,this.isAbsolute(s)))break}let r=this.#e.get(n);if(r!==void 0)return r;let i=this.cwd.resolve(n).fullpath();return this.#e.set(n,i),i}resolvePosix(...e){let n="";for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(!s||s===".")&&(n=n?`${s}/${n}`:s,this.isAbsolute(s)))break}let r=this.#n.get(n);if(r!==void 0)return r;let i=this.cwd.resolve(n).fullpathPosix();return this.#n.set(n,i),i}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,n={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r}=n;if(e.canReaddir()){let i=await e.readdir();return r?i:i.map(o=>o.name)}else return[]}readdirSync(e=this.cwd,n={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0}=n;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(i=>i.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:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=await e.readlink();return n?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return n?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=await e.realpath();return n?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:n}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return n?r:r?.fullpath()}async walk(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=[];(!o||o(e))&&a.push(r?e:e.fullpath());let c=new Set,u=(E,d)=>{c.add(E),E.readdirCB((f,T)=>{if(f)return d(f);let p=T.length;if(!p)return d();let S=()=>{--p===0&&d()};for(let m of T)(!o||o(m))&&a.push(r?m:m.fullpath()),i&&m.isSymbolicLink()?m.realpath().then(O=>O?.isUnknown()?O.lstat():O).then(O=>O?.shouldWalk(c,s)?u(O,S):S()):m.shouldWalk(c,s)?u(m,S):S()},!0)},l=e;return new Promise((E,d)=>{u(l,f=>{if(f)return d(f);E(a)})})}walkSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=[];(!o||o(e))&&a.push(r?e:e.fullpath());let c=new Set([e]);for(let u of c){let l=u.readdirSync();for(let E of l){(!o||o(E))&&a.push(r?E:E.fullpath());let d=E;if(E.isSymbolicLink()){if(!(i&&(d=E.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(c,s)&&c.add(d)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,n={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd),this.stream(e,n)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n;(!o||o(e))&&(yield r?e:e.fullpath());let a=new Set([e]);for(let c of a){let u=c.readdirSync();for(let l of u){(!o||o(l))&&(yield r?l:l.fullpath());let E=l;if(l.isSymbolicLink()){if(!(i&&(E=l.realpathSync())))continue;E.isUnknown()&&E.lstatSync()}E.shouldWalk(a,s)&&a.add(E)}}}stream(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=new Hc({objectMode:!0});(!o||o(e))&&a.write(r?e:e.fullpath());let c=new Set,u=[e],l=0,E=()=>{let d=!1;for(;!d;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let T=(S,m,O=!1)=>{if(S)return a.emit("error",S);if(i&&!O){let h=[];for(let C of m)C.isSymbolicLink()&&h.push(C.realpath().then(P=>P?.isUnknown()?P.lstat():P));if(h.length){Promise.all(h).then(()=>T(null,m,!0));return}}for(let h of m)h&&(!o||o(h))&&(a.write(r?h:h.fullpath())||(d=!0));l--;for(let h of m){let C=h.realpathCached()||h;C.shouldWalk(c,s)&&u.push(C)}d&&!a.flowing?a.once("drain",E):p||E()},p=!0;f.readdirCB(T,!0),p=!1}};return E(),a}streamSync(e=this.cwd,n={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Mr||(n=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:o,walkFilter:s}=n,a=new Hc({objectMode:!0}),c=new Set;(!o||o(e))&&a.write(r?e:e.fullpath());let u=[e],l=0,E=()=>{let d=!1;for(;!d;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let T=f.readdirSync();for(let p of T)(!o||o(p))&&(a.write(r?p:p.fullpath())||(d=!0));l--;for(let p of T){let S=p;if(p.isSymbolicLink()){if(!(i&&(S=p.realpathSync())))continue;S.isUnknown()&&S.lstatSync()}S.shouldWalk(c,s)&&u.push(S)}}d&&!a.flowing&&a.once("drain",E)};return E(),a}chdir(e=this.cwd){let n=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[oJ](n)}},Td=class extends vO{sep="\\";constructor(e=process.cwd(),n={}){let{nocase:r=!0}=n;super(e,vV,"\\",{...n,nocase:r}),this.nocase=r;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(e){return vV.parse(e).root.toUpperCase()}newRoot(e){return new yO(this.rootPath,Is,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Sd=class extends vO{sep="/";constructor(e=process.cwd(),n={}){let{nocase:r=!1}=n;super(e,Uot,"/",{...n,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new bO(this.rootPath,Is,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Th=class extends Sd{constructor(e=process.cwd(),n={}){let{nocase:r=!0}=n;super(e,{...n,nocase:r})}},Vwt=process.platform==="win32"?yO:bO,sJ=process.platform==="win32"?Td:process.platform==="darwin"?Th:Sd;var Xot=t=>t.length>=1,qot=t=>t.length>=1,pd=class t{#e;#n;#t;length;#a;#d;#p;#c;#l;#r;#i=!0;constructor(e,n,r,i){if(!Xot(e))throw new TypeError("empty pattern list");if(!qot(n))throw new TypeError("empty glob list");if(n.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#n=n,this.#t=r,this.#a=i,this.#t===0){if(this.isUNC()){let[o,s,a,c,...u]=this.#e,[l,E,d,f,...T]=this.#n;u[0]===""&&(u.shift(),T.shift());let p=[o,s,a,c,""].join("/"),S=[l,E,d,f,""].join("/");this.#e=[p,...u],this.#n=[S,...T],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[o,...s]=this.#e,[a,...c]=this.#n;s[0]===""&&(s.shift(),c.shift());let u=o+"/",l=a+"/";this.#e=[u,...s],this.#n=[l,...c],this.length=this.#e.length}}}pattern(){return this.#e[this.#t]}isString(){return typeof this.#e[this.#t]=="string"}isGlobstar(){return this.#e[this.#t]===cr}isRegExp(){return this.#e[this.#t]instanceof RegExp}globString(){return this.#p=this.#p||(this.#t===0?this.isAbsolute()?this.#n[0]+this.#n.slice(1).join("/"):this.#n.join("/"):this.#n.slice(this.#t).join("/"))}hasMore(){return this.length>this.#t+1}rest(){return this.#d!==void 0?this.#d:this.hasMore()?(this.#d=new t(this.#e,this.#n,this.#t+1,this.#a),this.#d.#r=this.#r,this.#d.#l=this.#l,this.#d.#c=this.#c,this.#d):this.#d=null}isUNC(){let e=this.#e;return this.#l!==void 0?this.#l:this.#l=this.#a==="win32"&&this.#t===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#a==="win32"&&this.#t===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#r!==void 0?this.#r:this.#r=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#t===0?e:""}checkFollowGlobstar(){return!(this.#t===0||!this.isGlobstar()||!this.#i)}markFollowGlobstar(){return this.#t===0||!this.isGlobstar()||!this.#i?!1:(this.#i=!1,!0)}};var Jot=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",hd=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:n,nocase:r,noext:i,noglobstar:o,platform:s=Jot}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=s,this.mmopts={dot:!0,nobrace:n,nocase:r,noext:i,noglobstar:o,optimizationLevel:2,platform:s,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let n=new vi(e,this.mmopts);for(let r=0;r<n.set.length;r++){let i=n.set[r],o=n.globParts[r];if(!i||!o)throw new Error("invalid pattern object");for(;i[0]==="."&&o[0]===".";)i.shift(),o.shift();let s=new pd(i,o,0,this.platform),a=new vi(s.globString(),this.mmopts),c=o[o.length-1]==="**",u=s.isAbsolute();u?this.absolute.push(a):this.relative.push(a),c&&(u?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let n=e.fullpath(),r=`${n}/`,i=e.relative()||".",o=`${i}/`;for(let s of this.relative)if(s.match(i)||s.match(o))return!0;for(let s of this.absolute)if(s.match(n)||s.match(r))return!0;return!1}childrenIgnored(e){let n=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(r))return!0;for(let i of this.absoluteChildren)if(i.match(n))return!0;return!1}};var wV=class t{store;constructor(e=new Map){this.store=e}copy(){return new t(new Map(this.store))}hasWalked(e,n){return this.store.get(e.fullpath())?.has(n.globString())}storeWalked(e,n){let r=e.fullpath(),i=this.store.get(r);i?i.add(n.globString()):this.store.set(r,new Set([n.globString()]))}},xV=class{store=new Map;add(e,n,r){let i=(n?2:0)|(r?1:0),o=this.store.get(e);this.store.set(e,o===void 0?i:i&o)}entries(){return[...this.store.entries()].map(([e,n])=>[e,!!(n&2),!!(n&1)])}},VV=class{store=new Map;add(e,n){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(i=>i.globString()===n.globString())||r.push(n):this.store.set(e,[n])}get(e){let n=this.store.get(e);if(!n)throw new Error("attempting to walk unknown path");return n}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},Sh=class t{hasWalkedCache;matches=new xV;subwalks=new VV;patterns;follow;dot;opts;constructor(e,n){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=n?n.copy():new wV}processPatterns(e,n){this.patterns=n;let r=n.map(i=>[e,i]);for(let[i,o]of r){this.hasWalkedCache.storeWalked(i,o);let s=o.root(),a=o.isAbsolute()&&this.opts.absolute!==!1;if(s){i=i.resolve(s==="/"&&this.opts.root!==void 0?this.opts.root:s);let E=o.rest();if(E)o=E;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let c,u,l=!1;for(;typeof(c=o.pattern())=="string"&&(u=o.rest());)i=i.resolve(c),o=u,l=!0;if(c=o.pattern(),u=o.rest(),l){if(this.hasWalkedCache.hasWalked(i,o))continue;this.hasWalkedCache.storeWalked(i,o)}if(typeof c=="string"){let E=c===".."||c===""||c===".";this.matches.add(i.resolve(c),a,E);continue}else if(c===cr){(!i.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(i,o);let E=u?.pattern(),d=u?.rest();if(!u||(E===""||E===".")&&!d)this.matches.add(i,a,E===""||E===".");else if(E===".."){let f=i.parent||i;d?this.hasWalkedCache.hasWalked(f,d)||this.subwalks.add(f,d):this.matches.add(f,a,!0)}}else c instanceof RegExp&&this.subwalks.add(i,o)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new t(this.opts,this.hasWalkedCache)}filterEntries(e,n){let r=this.subwalks.get(e),i=this.child();for(let o of n)for(let s of r){let a=s.isAbsolute(),c=s.pattern(),u=s.rest();c===cr?i.testGlobstar(o,s,u,a):c instanceof RegExp?i.testRegExp(o,c,u,a):i.testString(o,c,u,a)}return i}testGlobstar(e,n,r,i){if((this.dot||!e.name.startsWith("."))&&(n.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,n):e.isSymbolicLink()&&(r&&n.checkFollowGlobstar()?this.subwalks.add(e,r):n.markFollowGlobstar()&&this.subwalks.add(e,n)))),r){let o=r.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(e,o,r.rest(),i);else if(o===".."){let s=e.parent||e;this.subwalks.add(s,r)}else o instanceof RegExp&&this.testRegExp(e,o,r.rest(),i)}}testRegExp(e,n,r,i){n.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,i,!1))}testString(e,n,r,i){e.isNamed(n)&&(r?this.subwalks.add(e,r):this.matches.add(e,i,!1))}};var Qot=(t,e)=>typeof t=="string"?new hd([t],e):Array.isArray(t)?new hd(t,e):t,UO=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#n;#t;signal;maxDepth;includeChildMatches;constructor(e,n,r){if(this.patterns=e,this.path=n,this.opts=r,this.#t=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#n=Qot(r.ignore??[],r),!this.includeChildMatches&&typeof this.#n.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#a(e){return this.seen.has(e)||!!this.#n?.ignored?.(e)}#d(e){return!!this.#n?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,n){if(n&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let o=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let s=await o.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(o,n)}matchCheckTest(e,n){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!n||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#a(e)?e:void 0}matchCheckSync(e,n){if(n&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let o=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let s=o.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(o,n)}matchFinish(e,n){if(this.#a(e))return;if(!this.includeChildMatches&&this.#n?.add){let o=`${e.relativePosix()}/**`;this.#n.add(o)}let r=this.opts.absolute===void 0?n:this.opts.absolute;this.seen.add(e);let i=this.opts.mark&&e.isDirectory()?this.#t:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let o=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(o+i)}else{let o=this.opts.posix?e.relativePosix():e.relative(),s=this.opts.dotRelative&&!o.startsWith(".."+this.#t)?"."+this.#t:"";this.matchEmit(o?s+o+i:"."+i)}}async match(e,n,r){let i=await this.matchCheck(e,r);i&&this.matchFinish(i,n)}matchSync(e,n,r){let i=this.matchCheckSync(e,r);i&&this.matchFinish(i,n)}walkCB(e,n,r){this.signal?.aborted&&r(),this.walkCB2(e,n,new Sh(this.opts),r)}walkCB2(e,n,r,i){if(this.#d(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(e,n,r,i));return}r.processPatterns(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||(o++,this.match(a,c,u).then(()=>s()));for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let c=a.readdirCached();a.calledReaddir()?this.walkCB3(a,c,r,s):a.readdirCB((u,l)=>this.walkCB3(a,l,r,s),!0)}s()}walkCB3(e,n,r,i){r=r.filterEntries(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||(o++,this.match(a,c,u).then(()=>s()));for(let[a,c]of r.subwalks.entries())o++,this.walkCB2(a,c,r.child(),s);s()}walkCBSync(e,n,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,n,new Sh(this.opts),r)}walkCB2Sync(e,n,r,i){if(this.#d(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(e,n,r,i));return}r.processPatterns(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||this.matchSync(a,c,u);for(let a of r.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let c=a.readdirSync();this.walkCB3Sync(a,c,r,s)}s()}walkCB3Sync(e,n,r,i){r=r.filterEntries(e,n);let o=1,s=()=>{--o===0&&i()};for(let[a,c,u]of r.matches.entries())this.#a(a)||this.matchSync(a,c,u);for(let[a,c]of r.subwalks.entries())o++,this.walkCB2Sync(a,c,r.child(),s);s()}},ph=class extends UO{matches=new Set;constructor(e,n,r){super(e,n,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,n)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?n(this.signal.reason):e(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}},hh=class extends UO{results;constructor(e,n,r){super(e,n,r),this.results=new Hc({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,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}};var tst=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",zo=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,n){if(!n)throw new TypeError("glob options required");if(this.withFileTypes=!!n.withFileTypes,this.signal=n.signal,this.follow=!!n.follow,this.dot=!!n.dot,this.dotRelative=!!n.dotRelative,this.nodir=!!n.nodir,this.mark=!!n.mark,n.cwd?(n.cwd instanceof URL||n.cwd.startsWith("file://"))&&(n.cwd=est(n.cwd)):this.cwd="",this.cwd=n.cwd||"",this.root=n.root,this.magicalBraces=!!n.magicalBraces,this.nobrace=!!n.nobrace,this.noext=!!n.noext,this.realpath=!!n.realpath,this.absolute=n.absolute,this.includeChildMatches=n.includeChildMatches!==!1,this.noglobstar=!!n.noglobstar,this.matchBase=!!n.matchBase,this.maxDepth=typeof n.maxDepth=="number"?n.maxDepth:1/0,this.stat=!!n.stat,this.ignore=n.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(c=>c.replace(/\\/g,"/"))),this.matchBase){if(n.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(c=>c.includes("/")?c:`./**/${c}`)}if(this.pattern=e,this.platform=n.platform||tst,this.opts={...n,platform:this.platform},n.scurry){if(this.scurry=n.scurry,n.nocase!==void 0&&n.nocase!==n.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let c=n.platform==="win32"?Td:n.platform==="darwin"?Th:n.platform?Sd:sJ;this.scurry=new c(this.cwd,{nocase:n.nocase,fs:n.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",i={...n,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},o=this.pattern.map(c=>new vi(c,i)),[s,a]=o.reduce((c,u)=>(c[0].push(...u.set),c[1].push(...u.globParts),c),[[],[]]);this.patterns=s.map((c,u)=>{let l=a[u];if(!l)throw new Error("invalid pattern object");return new pd(c,l,0,this.platform)})}async walk(){return[...await new ph(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 ph(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 hh(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 hh(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()}};var GV=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let n of t)if(new vi(n,e).hasMagic())return!0;return!1};function wO(t,e={}){return new zo(t,e).streamSync()}function cJ(t,e={}){return new zo(t,e).stream()}function uJ(t,e={}){return new zo(t,e).walkSync()}async function aJ(t,e={}){return new zo(t,e).walk()}function xO(t,e={}){return new zo(t,e).iterateSync()}function lJ(t,e={}){return new zo(t,e).iterate()}var nst=wO,rst=Object.assign(cJ,{sync:wO}),ist=xO,ost=Object.assign(lJ,{sync:xO}),sst=Object.assign(uJ,{stream:wO,iterate:xO}),md=Object.assign(aJ,{glob:aJ,globSync:uJ,sync:sst,globStream:cJ,stream:rst,globStreamSync:wO,streamSync:nst,globIterate:lJ,iterate:ost,globIterateSync:xO,iterateSync:ist,Glob:zo,hasMagic:GV,escape:ld,unescape:jo});md.glob=md;function VO(t,e){let{changedFiles:n}=e;return n.some(r=>t===r||t.endsWith(r)||r.endsWith(t))}function ast(t,e,n,r){let{fileChangeMap:i}=r,o=i.get(t);return o?o.status==="added"?!0:o.status==="removed"?!1:cst(o.patch,e,n):!1}function mh(t,e){let n=VO(t.file.path,e),r=ast(t.file.path,t.range.start.line,t.range.end.line,e);return n&&r}function cst(t,e,n){let r=t.split(`
|
|
164
164
|
`),i=0,o=!1,s=0,a=0,c=new Set,u=[];for(let l of r){let E=l.match(/^@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s+@@/);if(E){o&&s>0&&u.push([s,a]),i=parseInt(E[1],10);let d=E[2]?parseInt(E[2],10):1;s=i,a=i+d-1,o=!0;continue}if(o)if(l.startsWith("+"))c.add(i),i++;else{if(l.startsWith("-"))continue;l.startsWith("\\")||i++}}if(o&&s>0&&u.push([s,a]),!c.has(e))return!1;for(let[l,E]of u)if(e>=l&&e<=E&&n>=l&&n<=E)return!0;return!1}function BV(t,e,n){let r=new Map;for(let c=0;c<e.length;c++){let u=e[c].fingerprint;u!==void 0&&(r.has(u)||r.set(u,[]),r.get(u).push(c))}let i=new Map;for(let c=0;c<t.length;c++){let u=t[c].fingerprint;u!==void 0&&(i.has(u)||i.set(u,[]),i.get(u).push(c))}let o=new Set,s=new Set,a=new Map;for(let[c,u]of i.entries()){let l=r.get(c);if(!l)continue;let E=u.length>1?[...u].sort((d,f)=>t[f].startLine-t[d].startLine):u;for(let d of E)for(let f of l)if(!o.has(f)){s.add(d),o.add(f),n&&a.set(d,f);break}}return n?a:s}function _J(t,e,n){if(t.length===0||e.length===0)return n?new Map:new Set;let r=[];for(let a=0;a<t.length;a++){let c=t[a];for(let u=0;u<e.length;u++){let l=e[u];if(c.file!==l.file)continue;if(c.startLine===l.startLine&&c.endLine===l.endLine)r.push({newIndex:a,oldIndex:u,distance:0});else{let d=Math.abs(c.startLine-l.startLine);d<=50&&r.push({newIndex:a,oldIndex:u,distance:d})}}}r.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:t[c.newIndex].startLine-t[a.newIndex].startLine);let i=new Set,o=new Set,s=new Map;for(let a of r)i.has(a.newIndex)||o.has(a.oldIndex)||(i.add(a.newIndex),o.add(a.oldIndex),n&&s.set(a.newIndex,a.oldIndex));return n?s:i}function Ah(t,e){if(t.length===0||e.length===0)return new Set;let n=BV(t,e),r=[];for(let l=0;l<t.length;l++)n.has(l)||r.push(l);let i=r.map(l=>t[l]),o=new Set;for(let l of n){let E=t[l];for(let d=0;d<e.length;d++)if(e[d].fingerprint===E.fingerprint){o.add(d);break}}let s=e.filter((l,E)=>!o.has(E)),a=_J(i,s),c=new Set;a.forEach(l=>{let E=r[l];c.add(E)});let u=new Set;return n.forEach(l=>u.add(l)),c.forEach(l=>u.add(l)),u}function ust(t,e,n){return!t||t.length===0?t:t.map(r=>r.filePath===e?{...r,filePath:n}:r)}function EJ(t,e){if(t.length===0)return{remappedMatches:[],unmappedMatches:[]};if(e.length===0)return{remappedMatches:[],unmappedMatches:t};let n=GO(t),r=GO(e),i=BV(n,r,!0);return dJ(t,e,i)}function FV(t,e){if(t.length===0)return{remappedMatches:[],unmappedMatches:[]};if(e.length===0)return{remappedMatches:[],unmappedMatches:t};let n=GO(t),r=GO(e),i=BV(n,r,!0),o=[];for(let d=0;d<t.length;d++)i.has(d)||o.push(d);let s=new Set(i.values()),a=[];for(let d=0;d<e.length;d++)s.has(d)||a.push(d);let c=o.map(d=>n[d]),u=a.map(d=>r[d]),l=_J(c,u,!0),E=new Map;for(let[d,f]of i.entries())E.set(d,f);for(let[d,f]of l.entries()){let T=o[d],p=a[f];E.set(T,p)}return dJ(t,e,E)}function dJ(t,e,n){let r=[],i=[];for(let o=0;o<t.length;o++)if(n.has(o)){let s=n.get(o),a=t[o],c=e[s];if(a.fingerprint&&c.fingerprint&&a.fingerprint!==c.fingerprint)i.push(a);else{let u=a.file.path!==c.file.path?ust(c.edits,c.file.path,a.file.path):c.edits;r.push({...a,description:c.description,evidence:c.evidence,edits:u})}}else i.push(t[o]);return{remappedMatches:r,unmappedMatches:i}}function GO(t){return t.map(e=>({file:e.file.path,startLine:e.range.start.line,endLine:e.range.end.line,fingerprint:e.fingerprint}))}function lst(t,e){return t.startLine<=e.endLine&&t.endLine>=e.startLine}function gh(t,e){if(t.length===0||e.length===0)return t;let n=Ah(t,e);for(let r=0;r<t.length;r++){if(n.has(r))continue;let i=t[r];for(let o of e)if(i.file===o.file&&lst(i,o)){n.add(r);break}}return t.filter((r,i)=>!n.has(i))}var RJ=ue(KV(),1);function Ma(t,e){return e.length===0?!1:(0,RJ.default)().add(e).ignores(t)}var Pa=class t{environment;_filePaths=[];mode;eventEmitter;config;gitIgnoredFilesCache;skipPreExistingViolations=!1;diffMode;customDiffMode;constructor(e,n,r,i){this.environment=n,this.mode=r,this.eventEmitter=i||new zr,this.config=e}static async initialize(e,n,r,i,o,s,a){let c=new t(e,n,r,i);if(c.skipPreExistingViolations=s?.skipPreExistingViolations??!1,r==="diff"){let l=c.environment.getWorkspaceRoot(),E=s?.include,d=s?.commitSelector;if(!d||!E)throw new Error("Commit selector and include are required in diff mode");let f=await Y9(l,{include:E,commitSelector:d}).catch(S=>{throw new Error(`Error running wispbit in diff mode:
|
|
165
165
|
${S.message}`)}),T=f.files.map(S=>S.filename),p=new Map(f.files.map(S=>[S.filename,S]));if(o){let S=Ht.normalize(o),m=Ht.isAbsolute(o)?o:Ht.resolve(l,o),O=Ht.relative(l,m),h=T.filter(C=>{let P=Ht.normalize(C),G=Ht.resolve(l,C);return P===S||P.startsWith(S+Ht.sep)||C===O||C.startsWith(O+Ht.sep)||G===m||G.startsWith(m+Ht.sep)});h.length===0?c.eventEmitter.fileDiscoveryProgress(`No changes found in specified file/path: ${o}`):c.eventEmitter.fileDiscoveryProgress(`Filtered to ${h.length} changed file(s) matching: ${o}`),T=h,p=new Map(f.files.filter(C=>h.includes(C.filename)).map(C=>[C.filename,C]))}else c.eventEmitter.fileDiscoveryProgress(`Found ${T.length} changed files`);c.diffMode={gitChanges:f,changedFiles:T,fileChangeMap:p}}if(r==="session"){if(!a?.fileChanges)throw new Error("customDiffOptions.fileChanges is required in session mode");let l=a.fileChanges,E=l.map(f=>f.filename),d=new Map(l.map(f=>[f.filename,f]));c.customDiffMode={changedFiles:E,fileChangeMap:d},c.eventEmitter.fileDiscoveryProgress(`Found ${E.length} changed files`)}let u=await c.discoverFiles(o);return c._filePaths=u,c}get filePaths(){return this._filePaths}filterFiles(e){let n=e.length,r;return this.mode==="check"?r=e:r=e.filter(i=>this.isFileValid({filePath:i})),n!==r.length&&this.eventEmitter.fileFilter(n,r.length,`${this.mode}-mode-files`),r}filterMatches(e,n=[]){let r=e.length,i=e;return this.skipPreExistingViolations&&n.length>0&&(i=this.deduplicate(i,n)),this.mode==="diff"&&this.diffMode&&(i=i.filter(o=>mh(o,{changedFiles:this.diffMode.changedFiles,fileChangeMap:this.diffMode.fileChangeMap}))),this.mode==="session"&&this.customDiffMode&&(i=i.filter(o=>mh(o,{changedFiles:this.customDiffMode.changedFiles,fileChangeMap:this.customDiffMode.fileChangeMap}))),r!==i.length&&this.eventEmitter.fileFilter(r,i.length,`${this.mode}-mode-matches`),i}deduplicate(e,n){let r=new Map;e.forEach((s,a)=>{let c=s.file.path;r.has(c)||r.set(c,[]),r.get(c).push({match:s,originalIndex:a})});let i=new Map;n.forEach(s=>{let a=s.file.path;i.has(a)||i.set(a,[]),i.get(a).push(s)});let o=new Set;for(let[s,a]of r.entries()){let c=i.get(s)||[];if(c.length===0&&this.mode==="diff"&&this.diffMode){let d=this.diffMode.fileChangeMap.get(s);d?.oldFilename&&(c=i.get(d.oldFilename)||[])}if(c.length===0)continue;let u=a.map(d=>({file:d.match.file.path,startLine:d.match.range.start.line,endLine:d.match.range.end.line,fingerprint:d.match.fingerprint})),l=c.map(d=>({file:d.file.path,startLine:d.range.start.line,endLine:d.range.end.line,fingerprint:d.fingerprint}));Ah(u,l).forEach(d=>{let f=a[d].originalIndex;o.add(f)})}return e.filter((s,a)=>!o.has(a))}filterMatchesByFilePaths(e,n){if(e.length===0)return e;let r=new Set(n);return e.filter(i=>r.has(i.file.path))}get executionMode(){return this.mode}async loadGitIgnoredFiles(){let e=this.environment.getWorkspaceRoot(),n=await x9(e).catch(()=>(this.eventEmitter.fileDiscoveryProgress("Not in a git repository, skipping git-ignored files"),[])),r=new Set(n.map(i=>Ht.resolve(e,i)));return n.length>0&&this.eventEmitter.fileDiscoveryProgress(`Found ${n.length} git-ignored files`),r}applyFileCountLimit(e){return e.length>250?(this.eventEmitter.fileDiscoveryProgress(`Limiting to 250 files (found ${e.length} total)`),e.slice(0,250)):e}async discoverFiles(e){this.eventEmitter.startFileDiscovery(this.mode);let n;if(e&&this.mode!=="diff")n=await this.discoverFilesFromPath(e);else if(this.mode==="diff"){let i=this.environment.getWorkspaceRoot(),o=this.diffMode.changedFiles.filter(l=>!to.existsSync(Ht.resolve(i,l))),s=0;n=this.diffMode.changedFiles.filter(l=>{let E=Ht.resolve(i,l);return to.existsSync(E)?this.isFileTooLarge(E)?(s++,!1):!0:!1}),s>0&&this.eventEmitter.fileDiscoveryProgress(`Skipped ${s} large files (>500KB/~5-6k lines)`),o.length>0&&this.eventEmitter.fileDiscoveryProgress(`Filtered out ${o.length} deleted files`);let a=this.config.getIgnoredGlobs(),c=[];if(a.length>0){this.eventEmitter.fileDiscoveryProgress("Applying ignore patterns...");let l=n.length;c=n.filter(E=>Ma(E,a)),n=n.filter(E=>!Ma(E,a)),l!==n.length&&this.eventEmitter.fileDiscoveryProgress(`Filtered out ${l-n.length} ignored files`)}let u=this.applyFileCountLimit(n);return this.eventEmitter.completeFileDiscovery(u,this.mode,this.diffMode?.fileChangeMap,c,o),u}else if(this.mode==="session"){let i=this.environment.getWorkspaceRoot(),o=this.customDiffMode.changedFiles.filter(l=>!to.existsSync(Ht.resolve(i,l))),s=0;n=this.customDiffMode.changedFiles.filter(l=>{let E=Ht.resolve(i,l);return to.existsSync(E)?this.isFileTooLarge(E)?(s++,!1):!0:!1}),s>0&&this.eventEmitter.fileDiscoveryProgress(`Skipped ${s} large files (>500KB/~5-6k lines)`),o.length>0&&this.eventEmitter.fileDiscoveryProgress(`Filtered out ${o.length} deleted files`);let a=this.config.getIgnoredGlobs(),c=[];if(a.length>0){this.eventEmitter.fileDiscoveryProgress("Applying ignore patterns...");let l=n.length;c=n.filter(E=>Ma(E,a)),n=n.filter(E=>!Ma(E,a)),l!==n.length&&this.eventEmitter.fileDiscoveryProgress(`Filtered out ${l-n.length} ignored files`)}let u=this.applyFileCountLimit(n);return this.eventEmitter.completeFileDiscovery(u,this.mode,this.customDiffMode?.fileChangeMap,c,o),u}else{this.eventEmitter.fileDiscoveryProgress("Scanning workspace for files...");let i=this.environment.getWorkspaceRoot(),o=this.config.getIgnoredGlobs();n=await this.discoverAllFiles([i],o)}let r=this.applyFileCountLimit(n);return this.eventEmitter.completeFileDiscovery(r,this.mode),r}async discoverFilesFromPath(e){let n=this.environment.getWorkspaceRoot(),r=Ht.resolve(n,e),i=this.config.getIgnoredGlobs();if(to.existsSync(r)){let o=to.statSync(r);if(o.isDirectory())return this.eventEmitter.fileDiscoveryProgress(`Discovering files in directory: ${e}`),await this.discoverFilesFromDirectory(e,i);if(o.isFile()){this.eventEmitter.fileDiscoveryProgress(`Checking specific file: ${e}`);let s=await this.executeGlob(e,{cwd:n,ignorePatterns:i});return s.length===0&&this.eventEmitter.fileDiscoveryProgress(`File ${e} is ignored by patterns or git`),s}}return this.eventEmitter.fileDiscoveryProgress(`Discovering files matching glob pattern: ${e}`),await this.discoverFilesFromGlob(e,i)}async executeGlob(e,n){let{cwd:r,ignorePatterns:i}=n,o=["**/node_modules/**","**/.git/**",...i],s=await md(e,{cwd:r,nodir:!0,absolute:!1,dot:!0,ignore:o}),a=new Set;this.mode==="check"&&(this.gitIgnoredFilesCache||(this.gitIgnoredFilesCache=await this.loadGitIgnoredFiles()),a=this.gitIgnoredFilesCache);let c=0,u=s.filter(l=>{let E=Ht.resolve(r,l);return a.has(E)?!1:this.isFileTooLarge(E)?(c++,!1):!0});return c>0&&this.eventEmitter.fileDiscoveryProgress(`Skipped ${c} large files (>500KB/~5-6k lines)`),u}isFileTooLarge(e){try{let r=to.statSync(e).size,i=500*1024;return r>i}catch{return!1}}async discoverFilesFromGlob(e,n){let r=this.environment.getWorkspaceRoot(),i=await this.executeGlob(e,{cwd:r,ignorePatterns:n});return this.eventEmitter.fileDiscoveryProgress(`Found ${i.length} files matching pattern`),i}async discoverFilesFromDirectory(e,n){let r=this.environment.getWorkspaceRoot(),i=Ht.join(e,"**/*").replace(/\\/g,"/"),o=await this.executeGlob(i,{cwd:r,ignorePatterns:n});return this.eventEmitter.fileDiscoveryProgress(`Found ${o.length} files in directory`),o}async discoverAllFiles(e,n){let r=[],i=this.environment.getWorkspaceRoot();for(let o of e){if(!to.statSync(o).isDirectory()){let u=Ht.relative(i,o),l=await this.executeGlob(u,{cwd:i,ignorePatterns:n});r.push(...l);continue}let c=(await this.executeGlob("**/*",{cwd:o,ignorePatterns:n})).map(u=>{let l=Ht.resolve(o,u);return Ht.relative(i,l)});r.push(...c)}return[...new Set(r)]}isFileValid(e){if(this.mode==="check")return!0;let{filePath:n}=e;return this.mode==="diff"&&this.diffMode?VO(n,{changedFiles:this.diffMode.changedFiles,fileChangeMap:this.diffMode.fileChangeMap}):this.mode==="session"&&this.customDiffMode?VO(n,{changedFiles:this.customDiffMode.changedFiles,fileChangeMap:this.customDiffMode.fileChangeMap}):!0}isMatchValid(e){if(this.mode==="check")return!0;let{match:n}=e;return this.mode==="diff"&&this.diffMode?mh(n,{changedFiles:this.diffMode.changedFiles,fileChangeMap:this.diffMode.fileChangeMap}):this.mode==="session"&&this.customDiffMode?mh(n,{changedFiles:this.customDiffMode.changedFiles,fileChangeMap:this.customDiffMode.fileChangeMap}):!0}hasBaseContent(e){return this.mode!=="diff"||!this.diffMode?!1:!!this.diffMode.fileChangeMap.get(e)?.baseContent}getFileInput(e,n){let r=this.environment.getWorkspaceRoot(),i=Ht.resolve(r,e);if(n&&this.mode==="diff"&&this.diffMode){let s=this.diffMode.fileChangeMap.get(e);if(s?.baseContent)return{path:e,content:s.baseContent}}let o=to.readFileSync(i,"utf-8");return{path:e,content:o}}};import{cpus as nat}from"os";var yst=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,OJ=new Set,zV=typeof process=="object"&&process?process:{},CJ=(t,e,n,r)=>{typeof zV.emitWarning=="function"?zV.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},HO=globalThis.AbortController,NJ=globalThis.AbortSignal;if(typeof HO>"u"){NJ=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,i){this._onabort.push(i)}},HO=class{constructor(){e()}signal=new NJ;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let i of this.signal._onabort)i(r);this.signal.onabort?.(r)}}};let t=zV.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,CJ("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",e))}}var bst=t=>!OJ.has(t),Pxt=Symbol("type"),Yc=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),IJ=t=>Yc(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Rd:null:null,Rd=class extends Array{constructor(e){super(e),this.fill(0)}},ZV=class t{heap;length;static#e=!1;static create(e){let n=IJ(e);if(!n)return[];t.#e=!0;let r=new t(e,n);return t.#e=!1,r}constructor(e,n){if(!t.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},YO=class t{#e;#n;#t;#a;#d;#p;#c;#l;get perf(){return this.#l}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#r;#i;#o;#_;#s;#E;#S;#f;#T;#C;#m;#A;#O;#h;#N;#D;#P;#u;#L;static unsafeExposeInternals(e){return{starts:e.#O,ttls:e.#h,autopurgeTimers:e.#N,sizes:e.#A,keyMap:e.#o,keyList:e.#_,valList:e.#s,next:e.#E,prev:e.#S,get head(){return e.#f},get tail(){return e.#T},free:e.#C,isBackgroundFetch:n=>e.#I(n),backgroundFetch:(n,r,i,o)=>e.#F(n,r,i,o),moveToTail:n=>e.#Y(n),indexes:n=>e.#g(n),rindexes:n=>e.#R(n),isStale:n=>e.#M(n)}}get max(){return this.#e}get maxSize(){return this.#n}get calculatedSize(){return this.#i}get size(){return this.#r}get fetchMethod(){return this.#p}get memoMethod(){return this.#c}get dispose(){return this.#t}get onInsert(){return this.#a}get disposeAfter(){return this.#d}constructor(e){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:u,onInsert:l,disposeAfter:E,noDisposeOnSet:d,noUpdateTTL:f,maxSize:T=0,maxEntrySize:p=0,sizeCalculation:S,fetchMethod:m,memoMethod:O,noDeleteOnFetchRejection:h,noDeleteOnStaleGet:C,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:G,ignoreFetchAbort:Y,perf:re}=e;if(re!==void 0&&typeof re?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#l=re??yst,n!==0&&!Yc(n))throw new TypeError("max option must be a nonnegative integer");let W=n?IJ(n):Array;if(!W)throw new Error("invalid max value: "+n);if(this.#e=n,this.#n=T,this.maxEntrySize=p||this.#n,this.sizeCalculation=S,this.sizeCalculation){if(!this.#n&&!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(this.#c=O,m!==void 0&&typeof m!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#p=m,this.#P=!!m,this.#o=new Map,this.#_=new Array(n).fill(void 0),this.#s=new Array(n).fill(void 0),this.#E=new W(n),this.#S=new W(n),this.#f=0,this.#T=0,this.#C=ZV.create(n),this.#r=0,this.#i=0,typeof u=="function"&&(this.#t=u),typeof l=="function"&&(this.#a=l),typeof E=="function"?(this.#d=E,this.#m=[]):(this.#d=void 0,this.#m=void 0),this.#D=!!this.#t,this.#L=!!this.#a,this.#u=!!this.#d,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!h,this.allowStaleOnFetchRejection=!!P,this.allowStaleOnFetchAbort=!!G,this.ignoreFetchAbort=!!Y,this.maxEntrySize!==0){if(this.#n!==0&&!Yc(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!Yc(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#b()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!C,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=Yc(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!Yc(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#y()}if(this.#e===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#n){let q="LRU_CACHE_UNBOUNDED";bst(q)&&(OJ.add(q),CJ("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",q,t))}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#y(){let e=new Rd(this.#e),n=new Rd(this.#e);this.#h=e,this.#O=n;let r=this.ttlAutopurge?new Array(this.#e):void 0;this.#N=r,this.#B=(s,a,c=this.#l.now())=>{if(n[s]=a!==0?c:0,e[s]=a,r?.[s]&&(clearTimeout(r[s]),r[s]=void 0),a!==0&&r){let u=setTimeout(()=>{this.#M(s)&&this.#k(this.#_[s],"expire")},a+1);u.unref&&u.unref(),r[s]=u}},this.#v=s=>{n[s]=e[s]!==0?this.#l.now():0},this.#U=(s,a)=>{if(e[a]){let c=e[a],u=n[a];if(!c||!u)return;s.ttl=c,s.start=u,s.now=i||o();let l=s.now-u;s.remainingTTL=c-l}};let i=0,o=()=>{let s=this.#l.now();if(this.ttlResolution>0){i=s;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return s};this.getRemainingTTL=s=>{let a=this.#o.get(s);if(a===void 0)return 0;let c=e[a],u=n[a];if(!c||!u)return 1/0;let l=(i||o())-u;return c-l},this.#M=s=>{let a=n[s],c=e[s];return!!c&&!!a&&(i||o())-a>c}}#v=()=>{};#U=()=>{};#B=()=>{};#M=()=>!1;#b(){let e=new Rd(this.#e);this.#i=0,this.#A=e,this.#w=n=>{this.#i-=e[n],e[n]=0},this.#V=(n,r,i,o)=>{if(this.#I(r))return 0;if(!Yc(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(r,n),!Yc(i))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 i},this.#x=(n,r,i)=>{if(e[n]=r,this.#n){let o=this.#n-e[n];for(;this.#i>o;)this.#H(!0)}this.#i+=e[n],i&&(i.entrySize=r,i.totalCalculatedSize=this.#i)}}#w=e=>{};#x=(e,n,r)=>{};#V=(e,n,r,i)=>{if(r||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#g({allowStale:e=this.allowStale}={}){if(this.#r)for(let n=this.#T;!(!this.#G(n)||((e||!this.#M(n))&&(yield n),n===this.#f));)n=this.#S[n]}*#R({allowStale:e=this.allowStale}={}){if(this.#r)for(let n=this.#f;!(!this.#G(n)||((e||!this.#M(n))&&(yield n),n===this.#T));)n=this.#E[n]}#G(e){return e!==void 0&&this.#o.get(this.#_[e])===e}*entries(){for(let e of this.#g())this.#s[e]!==void 0&&this.#_[e]!==void 0&&!this.#I(this.#s[e])&&(yield[this.#_[e],this.#s[e]])}*rentries(){for(let e of this.#R())this.#s[e]!==void 0&&this.#_[e]!==void 0&&!this.#I(this.#s[e])&&(yield[this.#_[e],this.#s[e]])}*keys(){for(let e of this.#g()){let n=this.#_[e];n!==void 0&&!this.#I(this.#s[e])&&(yield n)}}*rkeys(){for(let e of this.#R()){let n=this.#_[e];n!==void 0&&!this.#I(this.#s[e])&&(yield n)}}*values(){for(let e of this.#g())this.#s[e]!==void 0&&!this.#I(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#R())this.#s[e]!==void 0&&!this.#I(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,n={}){for(let r of this.#g()){let i=this.#s[r],o=this.#I(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#_[r],this))return this.get(this.#_[r],n)}}forEach(e,n=this){for(let r of this.#g()){let i=this.#s[r],o=this.#I(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#_[r],this)}}rforEach(e,n=this){for(let r of this.#R()){let i=this.#s[r],o=this.#I(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(n,o,this.#_[r],this)}}purgeStale(){let e=!1;for(let n of this.#R({allowStale:!0}))this.#M(n)&&(this.#k(this.#_[n],"expire"),e=!0);return e}info(e){let n=this.#o.get(e);if(n===void 0)return;let r=this.#s[n],i=this.#I(r)?r.__staleWhileFetching:r;if(i===void 0)return;let o={value:i};if(this.#h&&this.#O){let s=this.#h[n],a=this.#O[n];if(s&&a){let c=s-(this.#l.now()-a);o.ttl=c,o.start=Date.now()}}return this.#A&&(o.size=this.#A[n]),o}dump(){let e=[];for(let n of this.#g({allowStale:!0})){let r=this.#_[n],i=this.#s[n],o=this.#I(i)?i.__staleWhileFetching:i;if(o===void 0||r===void 0)continue;let s={value:o};if(this.#h&&this.#O){s.ttl=this.#h[n];let a=this.#l.now()-this.#O[n];s.start=Math.floor(Date.now()-a)}this.#A&&(s.size=this.#A[n]),e.unshift([r,s])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let i=Date.now()-r.start;r.start=this.#l.now()-i}this.set(n,r.value,r)}}set(e,n,r={}){if(n===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=r,{noUpdateTTL:u=this.noUpdateTTL}=r,l=this.#V(e,n,r.size||0,a);if(this.maxEntrySize&&l>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let E=this.#r===0?void 0:this.#o.get(e);if(E===void 0)E=this.#r===0?this.#T:this.#C.length!==0?this.#C.pop():this.#r===this.#e?this.#H(!1):this.#r,this.#_[E]=e,this.#s[E]=n,this.#o.set(e,E),this.#E[this.#T]=E,this.#S[E]=this.#T,this.#T=E,this.#r++,this.#x(E,l,c),c&&(c.set="add"),u=!1,this.#L&&this.#a?.(n,e,"add");else{this.#Y(E);let d=this.#s[E];if(n!==d){if(this.#P&&this.#I(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=d;f!==void 0&&!s&&(this.#D&&this.#t?.(f,e,"set"),this.#u&&this.#m?.push([f,e,"set"]))}else s||(this.#D&&this.#t?.(d,e,"set"),this.#u&&this.#m?.push([d,e,"set"]));if(this.#w(E),this.#x(E,l,c),this.#s[E]=n,c){c.set="replace";let f=d&&this.#I(d)?d.__staleWhileFetching:d;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update");this.#L&&this.onInsert?.(n,e,n===d?"update":"replace")}if(i!==0&&!this.#h&&this.#y(),this.#h&&(u||this.#B(E,i,o),c&&this.#U(c,E)),!s&&this.#u&&this.#m){let d=this.#m,f;for(;f=d?.shift();)this.#d?.(...f)}return this}pop(){try{for(;this.#r;){let e=this.#s[this.#f];if(this.#H(!0),this.#I(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#u&&this.#m){let e=this.#m,n;for(;n=e?.shift();)this.#d?.(...n)}}}#H(e){let n=this.#f,r=this.#_[n],i=this.#s[n];return this.#P&&this.#I(i)?i.__abortController.abort(new Error("evicted")):(this.#D||this.#u)&&(this.#D&&this.#t?.(i,r,"evict"),this.#u&&this.#m?.push([i,r,"evict"])),this.#w(n),this.#N?.[n]&&(clearTimeout(this.#N[n]),this.#N[n]=void 0),e&&(this.#_[n]=void 0,this.#s[n]=void 0,this.#C.push(n)),this.#r===1?(this.#f=this.#T=0,this.#C.length=0):this.#f=this.#E[n],this.#o.delete(r),this.#r--,n}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:i}=n,o=this.#o.get(e);if(o!==void 0){let s=this.#s[o];if(this.#I(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#M(o))i&&(i.has="stale",this.#U(i,o));else return r&&this.#v(o),i&&(i.has="hit",this.#U(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,i=this.#o.get(e);if(i===void 0||!r&&this.#M(i))return;let o=this.#s[i];return this.#I(o)?o.__staleWhileFetching:o}#F(e,n,r,i){let o=n===void 0?void 0:this.#s[n];if(this.#I(o))return o;let s=new HO,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:r,context:i},u=(p,S=!1)=>{let{aborted:m}=s.signal,O=r.ignoreFetchAbort&&p!==void 0;if(r.status&&(m&&!S?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,O&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),m&&!O&&!S)return E(s.signal.reason);let h=f,C=this.#s[n];return(C===f||O&&S&&C===void 0)&&(p===void 0?h.__staleWhileFetching!==void 0?this.#s[n]=h.__staleWhileFetching:this.#k(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,p,c.options))),p},l=p=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=p),E(p)),E=p=>{let{aborted:S}=s.signal,m=S&&r.allowStaleOnFetchAbort,O=m||r.allowStaleOnFetchRejection,h=O||r.noDeleteOnFetchRejection,C=f;if(this.#s[n]===f&&(!h||C.__staleWhileFetching===void 0?this.#k(e,"fetch"):m||(this.#s[n]=C.__staleWhileFetching)),O)return r.status&&C.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),C.__staleWhileFetching;if(C.__returned===C)throw p},d=(p,S)=>{let m=this.#p?.(e,o,c);m&&m instanceof Promise&&m.then(O=>p(O===void 0?void 0:O),S),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(p(void 0),r.allowStaleOnFetchAbort&&(p=O=>u(O,!0)))})};r.status&&(r.status.fetchDispatched=!0);let f=new Promise(d).then(u,l),T=Object.assign(f,{__abortController:s,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(e,T,{...c.options,status:void 0}),n=this.#o.get(e)):this.#s[n]=T,T}#I(e){if(!this.#P)return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof HO}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:E=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:T=this.allowStaleOnFetchAbort,context:p,forceRefresh:S=!1,status:m,signal:O}=n;if(!this.#P)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:m});let h={allowStale:r,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:E,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:T,ignoreFetchAbort:f,status:m,signal:O},C=this.#o.get(e);if(C===void 0){m&&(m.fetch="miss");let P=this.#F(e,C,h,p);return P.__returned=P}else{let P=this.#s[C];if(this.#I(P)){let q=r&&P.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",q&&(m.returnedStale=!0)),q?P.__staleWhileFetching:P.__returned=P}let G=this.#M(C);if(!S&&!G)return m&&(m.fetch="hit"),this.#Y(C),i&&this.#v(C),m&&this.#U(m,C),P;let Y=this.#F(e,C,h,p),W=Y.__staleWhileFetching!==void 0&&r;return m&&(m.fetch=G?"stale":"refresh",W&&G&&(m.returnedStale=!0)),W?Y.__staleWhileFetching:Y.__returned=Y}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,n={}){let r=this.#c;if(!r)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:o,...s}=n,a=this.get(e,s);if(!o&&a!==void 0)return a;let c=r(e,a,{options:s,context:i});return this.set(e,c,s),c}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:s}=n,a=this.#o.get(e);if(a!==void 0){let c=this.#s[a],u=this.#I(c);return s&&this.#U(s,a),this.#M(a)?(s&&(s.get="stale"),u?(s&&r&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?c.__staleWhileFetching:void 0):(o||this.#k(e,"expire"),s&&r&&(s.returnedStale=!0),r?c:void 0)):(s&&(s.get="hit"),u?c.__staleWhileFetching:(this.#Y(a),i&&this.#v(a),c))}else s&&(s.get="miss")}#$(e,n){this.#S[n]=e,this.#E[e]=n}#Y(e){e!==this.#T&&(e===this.#f?this.#f=this.#E[e]:this.#$(this.#S[e],this.#E[e]),this.#$(this.#T,e),this.#T=e)}delete(e){return this.#k(e,"delete")}#k(e,n){let r=!1;if(this.#r!==0){let i=this.#o.get(e);if(i!==void 0)if(this.#N?.[i]&&(clearTimeout(this.#N?.[i]),this.#N[i]=void 0),r=!0,this.#r===1)this.#j(n);else{this.#w(i);let o=this.#s[i];if(this.#I(o)?o.__abortController.abort(new Error("deleted")):(this.#D||this.#u)&&(this.#D&&this.#t?.(o,e,n),this.#u&&this.#m?.push([o,e,n])),this.#o.delete(e),this.#_[i]=void 0,this.#s[i]=void 0,i===this.#T)this.#T=this.#S[i];else if(i===this.#f)this.#f=this.#E[i];else{let s=this.#S[i];this.#E[s]=this.#E[i];let a=this.#E[i];this.#S[a]=this.#S[i]}this.#r--,this.#C.push(i)}}if(this.#u&&this.#m?.length){let i=this.#m,o;for(;o=i?.shift();)this.#d?.(...o)}return r}clear(){return this.#j("delete")}#j(e){for(let n of this.#R({allowStale:!0})){let r=this.#s[n];if(this.#I(r))r.__abortController.abort(new Error("deleted"));else{let i=this.#_[n];this.#D&&this.#t?.(r,i,e),this.#u&&this.#m?.push([r,i,e])}}if(this.#o.clear(),this.#s.fill(void 0),this.#_.fill(void 0),this.#h&&this.#O){this.#h.fill(0),this.#O.fill(0);for(let n of this.#N??[])n!==void 0&&clearTimeout(n);this.#N?.fill(void 0)}if(this.#A&&this.#A.fill(0),this.#f=0,this.#T=0,this.#C.length=0,this.#i=0,this.#r=0,this.#u&&this.#m){let n=this.#m,r;for(;r=n?.shift();)this.#d?.(...r)}}};import*as Nd from"fs";import*as MJ from"os";import*as $O from"path";var XV=class{logFile;enabled=!0;constructor(){this.logFile=$O.join(MJ.homedir(),".wispbit","debug.log")}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}log(e){if(this.enabled)try{Nd.mkdirSync($O.dirname(this.logFile),{recursive:!0});let n=`[${new Date().toISOString()}] ${e}`;Nd.appendFileSync(this.logFile,`${n}
|
|
166
166
|
`)}catch{}}clear(){try{Nd.unlinkSync(this.logFile)}catch{}}logMemory(e){if(!this.enabled)return;let n=process.memoryUsage(),r=o=>`${(o/1024/1024).toFixed(2)} MB`,i=[`Memory [${e}]:`,`RSS: ${r(n.rss)}`,`Heap Used: ${r(n.heapUsed)}`,`Heap Total: ${r(n.heapTotal)}`,`External: ${r(n.external)}`].join(" | ");this.log(i)}},Ae=new XV;var Od=class{cache;inFlightParses=new Map;stats={cacheHits:0,cacheMisses:0,inFlightHits:0,parsesCalled:0,evictions:0};constructor(){this.cache=new YO({max:400,dispose:(e,n)=>{this.stats.evictions++,e.sgRoot=void 0}})}getCacheKey(e,n,r){return`${e}:${n}:${r}`}get(e){return this.cache.get(e)}set(e,n){this.cache.set(e,n)}getOrParse(e,n,r,i){let o=this.getCacheKey(e,n,r),s=this.get(o);if(s)return this.stats.cacheHits++,Promise.resolve(s);let a=this.inFlightParses.get(o);if(a)return this.stats.inFlightHits++,a;this.stats.cacheMisses++,this.stats.parsesCalled++;let c=i().then(({sgRoot:u,estimatedSize:l})=>{let E={sgRoot:u,path:e,contentHash:r,language:n,estimatedSize:l,parsedAt:Date.now()};return this.set(o,E),this.inFlightParses.delete(o),E}).catch(u=>{throw this.inFlightParses.delete(o),u});return this.inFlightParses.set(o,c),c}clear(){this.cache.clear(),this.inFlightParses.clear()}getCacheStats(){return{size:this.cache.size,calculatedSize:this.cache.calculatedSize||0}}logStats(){let e=this.stats.cacheHits+this.stats.cacheMisses>0?(this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses)*100).toFixed(1):"0";Ae.log(`[SharedAstCache] Stats: hits=${this.stats.cacheHits}, misses=${this.stats.cacheMisses}, inFlightHits=${this.stats.inFlightHits}, parses=${this.stats.parsesCalled}, evictions=${this.stats.evictions}, hitRate=${e}%, cacheSize=${this.cache.size}, cacheBytes=${Math.round((this.cache.calculatedSize||0)/1024/1024)}MB, inFlight=${this.inFlightParses.size}`)}};var jO=class{environment;constructor(e){this.environment=e}execute(e,n){let r=Date.now(),i=e;if(n.include?.length&&(i=i.filter(s=>Ma(s,n.include))),n.ignore?.length&&(i=i.filter(s=>!Ma(s,n.ignore))),n.additionalGlobs?.length){let s=e.filter(c=>Ma(c,n.additionalGlobs)),a=new Set(i);for(let c of s)a.has(c)||i.push(c)}let o=Date.now()-r;return{filteredPaths:i,executionTime:o}}};import FJ from"path";var Md=ue(fO(),1);import jst from"path";import{spawn as xst}from"child_process";import vJ from"crypto";import Cd from"fs";import Da,{dirname as yJ,join as bJ}from"path";import{promises as vst}from"fs";import Gxt from"path";async function WO(t){try{return await vst.access(t),!0}catch{return!1}}import{execSync as Ust}from"child_process";function Nh(){return Ust("which rg").toString().trim()}import KO from"fs";import wst from"path";async function PJ(t){try{if(t.includes("/")||t.includes("\\"))return await KO.promises.access(t,KO.constants.X_OK),!0;let e=process.env.PATH||"",n=process.platform==="win32"?";":":",r=e.split(n),i=process.platform==="win32"?(process.env.PATHEXT||".exe;.cmd;.bat").split(";"):[""];for(let o of r)for(let s of i){let a=wst.join(o,t+s);try{return await KO.promises.access(a,KO.constants.X_OK),!0}catch{}}return!1}catch{return!1}}var DJ=ue(KV(),1);function LJ(t){let e=t.match(/\{([^}]+)\}/);if(!e)return[t];let n=e[1].split(","),r=t.slice(0,e.index),i=t.slice(e.index+e[0].length),o=[];for(let s of n){let a=r+s+i;o.push(...LJ(a))}return o}function Oh(t,e){if(e.length===0)return!1;let n=[];for(let i of e)n.push(...LJ(i));return(0,DJ.default)().add(n).ignores(t)}function zO(t,e){let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");return t.replace(n,"").replace(/\/\//g,"/")}async function ZO(t){return await new Promise((e,n)=>{let r=vJ.createHash("sha256"),i=Cd.createReadStream(t);i.on("error",o=>n(o)),i.on("data",o=>r.update(o)),i.on("end",()=>e(r.digest("hex")))})}function Ch(t){let e=vJ.createHash("sha256");return e.update(t),e.digest("hex")}function XO(t,e){try{let n=Da.resolve(t),r=Da.resolve(t,e),i=Da.normalize(n),o=Da.normalize(r);return o===i||o.startsWith(i+Da.sep)?o:null}catch{return null}}function Vst(t,e,n){try{let i=Cd.readFileSync(t,"utf8").split(`
|
|
@@ -214,7 +214,7 @@ You can use this when we know the exact symbol/function name/etc. to search in s
|
|
|
214
214
|
${o.join(`
|
|
215
215
|
`)}`)}import{readFile as Qst}from"fs/promises";import eat from"path";async function t1(t,e,n,r=!1){let i=eat.resolve(t,e),s=(await Qst(i,"utf-8")).split(`
|
|
216
216
|
`),{start:a,end:c}=n,u=a.line-1,l=c.line-1;if(a.line===c.line){let d=s[u]||"";return r?d.substring(a.column-1,c.column-1):d}let E=[];for(let d=u;d<=l&&d<s.length;d++){let f=s[d];d===u?E.push(r?f.substring(a.column-1):f):d===l?E.push(r?f.substring(0,c.column-1):f):E.push(f)}return E.join(`
|
|
217
|
-
`)}var tat={read:WJ,grep:KJ,glob:zJ},aC=class{environment;eventEmitter;config;maxIterations;batchSize;constructor(e,n,r,i,o){this.environment=n,this.eventEmitter=r||new zr,this.config=e,this.maxIterations=i||20,this.batchSize=o||50}async executeTool(e,n,r,i){if(n==="report_fix")return{error:"Tool 'report_fix' is not supported in LLMStep. Available tools are: read, grep, glob"};let o=tat[n];if(!o)return{error:`Unknown tool: ${n}. Available tools are: read, grep, glob`};let s=HJ(n,r,[o]);if(!s.success)return{error:`Tool parameter validation failed: ${s.error}. Please fix the parameters and try again.`};let a=s.data;switch(n){case"read":{this.eventEmitter.llmToolExecution(e,"read",{file:a.target_file,offset:a.offset,limit:a.limit});let c=await qO(a,this.environment.getWorkspaceRoot());if(!("error"in c)){let u=a.target_file;i.some(l=>l.path===u)||i.push({path:u,sha:c.sha})}return"error"in c?c:c.content}case"grep":{this.eventEmitter.llmToolExecution(e,"grep",{path:a.path,pattern:a.pattern});let c=await JO(a,this.environment.getWorkspaceRoot(),[],ZJ());if(!("error"in c))for(let u of c.matches)i.some(l=>l.path===u.file)||i.push({path:u.file,sha:u.sha});return"error"in c?c:JSON.stringify(c.matches)}case"glob":{this.eventEmitter.llmToolExecution(e,"glob",{path:a.path,pattern:a.pattern});let c=await QO(a,this.environment.getWorkspaceRoot());return"error"in c?c:JSON.stringify(c.files)}default:return{error:`Unknown tool: ${n}`}}}async hydrateMatchesWithFileContent(e){let n=[];for(let r of e){let i=await t1(this.environment.getWorkspaceRoot(),r.file.path,r.range).catch(s=>{if(s.code==="ENOENT")return null;throw s});if(i===null)continue;let o=r.evidence;if(r.evidence&&r.evidence.length>0){o=[];let s=!1;for(let a of r.evidence){let c=await t1(this.environment.getWorkspaceRoot(),a.file.path,a.range).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(c===null){s=!0;break}o.push({...a,text:c})}if(s)continue}n.push({...r,text:i,evidence:o})}return n}async executeLLMValidation(e,n,r){let i=Date.now(),o=this.config.getLLMProvider();this.eventEmitter.startLLMValidation(e.id,n.length);let s=[],a=[],c=new sr(0),u=new sr(0),l=new sr(0);this.eventEmitter.startLLMSearchPhase(e.id,n.length);let E,d=[],f=[];for(let h=0;h<this.maxIterations;h++){let C=await o.search({rule:e,matches:n,tools:r,messages:s,files:a});if(f.push(C),C.usage&&C.usage.inputTokens&&C.usage.outputTokens&&C.usage.cost&&(c=c.plus(new sr(C.usage.inputTokens)),u=u.plus(new sr(C.usage.outputTokens)),l=l.plus(new sr(C.usage.cost))),C.type==="partial_matches"){let P=await this.hydrateMatchesWithFileContent(C.matches);d=[...d,...P],n=C.unresolved;continue}if(C.type==="matches"){let P=await this.hydrateMatchesWithFileContent(C.matches);E={...C,matches:[...d,...P]};break}if(C.type==="request_files"){for(let P of C.files)a.some(G=>G.path===P.path)||a.push({path:P.path,sha:P.sha});continue}if(C.type==="assistant"){s.push({type:"assistant",content:C.content}),s.push({type:"user",content:"Please use tool calls to interact with the codebase and report violations."});continue}if(C.type==="tool_request"){s.push({type:"tool_request",tool_calls:C.tool_calls});let P=await Promise.all(C.tool_calls.map(async G=>{let Y=await this.executeTool(e.id,G.function.name,G.function.arguments,a),re=typeof Y=="string"?Y:JSON.stringify(Y);return{tool_call_id:G.id,content:re}}));s.push({type:"tool_response",tool_results:P});continue}}if(!E)throw this.eventEmitter.emit("llm:max-iterations-reached",{ruleId:e.id,maxIterations:this.maxIterations,messages:s,results:f}),new Error(`Max iterations (${this.maxIterations}) reached without getting matches`);let T=E.matches;if(T.length===0){let h=c.plus(u).toNumber();return this.eventEmitter.completeLLMValidation(e.id,h,c.toNumber(),u.toNumber(),l.toString(),Date.now()-i,0,!1),{matches:[],executionTime:Date.now()-i,cost:l.toString()}}this.eventEmitter.startLLMValidationPhase(e.id,T.length);let p=[],S=T;for(;S.length>0;){let h=await o.validate({rule:e,matches:S,files:a});if(h.usage&&h.usage.inputTokens&&h.usage.outputTokens&&h.usage.cost&&(c=c.plus(new sr(h.usage.inputTokens)),u=u.plus(new sr(h.usage.outputTokens)),l=l.plus(new sr(h.usage.cost))),h.type==="partial_matches"){let C=await this.hydrateMatchesWithFileContent(h.matches);p=[...p,...C],S=h.unresolved;continue}if(h.type==="matches"){let C=await this.hydrateMatchesWithFileContent(h.matches);p=[...p,...C];break}}let m=p,O=c.plus(u).toNumber();return this.eventEmitter.completeLLMValidation(e.id,O,c.toNumber(),u.toNumber(),l.toString(),Date.now()-i,m.length,!1),{matches:m,executionTime:Date.now()-i,cost:l.toString()}}async execute(e,n,r){if(n.length===0)return{matches:[],executionTime:0,cost:"0"};let i=Date.now(),o=[...n].sort((l,E)=>l.file.path!==E.file.path?l.file.path.localeCompare(E.file.path):l.range.start.line-E.range.start.line),s=[];for(let l=0;l<o.length;l+=this.batchSize)s.push(o.slice(l,l+this.batchSize));let a=s.length,c=[],u=new sr(0);for(let l=0;l<s.length;l++){let E=s[l],d=l+1,f=n.length-(l+1)*this.batchSize,T=Math.max(0,f);a>1&&this.eventEmitter.llmValidationPhaseBatch(e.id,d,a,E.length,T,n.length);let p=await this.executeLLMValidation(e,E,r);c=[...c,...p.matches],u=u.plus(new sr(p.cost))}return{matches:c,executionTime:Date.now()-i,cost:u.toString()}}};var La=class{fileFilterStep;findMatchesStep;llmStep;environment;eventEmitter;config;previousResults=new Map;inFlightLLMRequests=new Map;sharedAstCache;constructor(e,n,r){this.environment=n,this.eventEmitter=r||new zr,this.config=e,this.sharedAstCache=new Od,this.fileFilterStep=new jO(this.environment),this.findMatchesStep=new iC(this.environment,this.eventEmitter,this.sharedAstCache),this.llmStep=new aC(this.config,this.environment,this.eventEmitter)}clearCache(){this.previousResults.clear(),this.inFlightLLMRequests.clear(),this.sharedAstCache.clear()}async executeStep(e,n,r,i,o,s){let a=n.type;if(a==="ast-grep"){let{type:c,language:u,...l}=n,E=r.map(T=>o.getFileInput(T,!1)),d=await this.findMatchesStep.execute(l,u,{fileInputs:E}),f=[];if(this.shouldDeduplicateMatches(o)){let T=r.filter(p=>o.hasBaseContent(p));if(T.length>0){let p=T.map(m=>o.getFileInput(m,!0));f=(await this.findMatchesStep.execute(l,u,{fileInputs:p})).matches}}return{matches:d.matches,oldMatches:f}}if(a==="ripgrep"){let{type:c,...u}=n,l=r.map(f=>o.getFileInput(f,!1)),E=await this.findMatchesStep.execute(u,"Unknown",{fileInputs:l}),d=[];if(this.shouldDeduplicateMatches(o)){let f=r.filter(T=>o.hasBaseContent(T));if(f.length>0){let T=f.map(S=>o.getFileInput(S,!0));d=(await this.findMatchesStep.execute(u,"Unknown",{fileInputs:T})).matches}}return{matches:E.matches,oldMatches:d}}if(a==="file-filter")return{filePaths:this.fileFilterStep.execute(r,{include:n.include,ignore:n.ignore,additionalGlobs:this.config.getAdditionalGlobs()}).filteredPaths};if(a==="llm"){if(i.length===0)return{matches:[],cost:"0"};let c=[],u=i;if(this.previousResults.has(e.internalId)){let p=this.previousResults.get(e.internalId).matches,S=FV(i,p);if(c=S.remappedMatches,u=S.unmappedMatches,c.length>0){let m=c.length+u.length;this.eventEmitter.emit("rules:rule-partial",{ruleId:e.internalId,matches:c,totalMatches:m});let O=new Map;for(let h of c){let C=h.file.path;O.has(C)||O.set(C,[]),O.get(C).push(h)}for(let[h,C]of O.entries())this.eventEmitter.emit("rules:rule-file-partial",{ruleId:e.internalId,filePath:h,matches:C,totalMatches:m})}}if(u.length===0)return{matches:c,cost:"0"};let E=this.inFlightLLMRequests.get(e.internalId);if(E){let T=await E,{remappedMatches:p,unmappedMatches:S}=FV(u,T.matches);if(S.length>0){let m=this.llmStep.execute(e,S,n.tools??[]);this.inFlightLLMRequests.set(e.internalId,m);let O=await m;return this.inFlightLLMRequests.delete(e.internalId),{matches:[...c,...p,...O.matches],cost:O.cost}}else return{matches:[...c,...p],cost:"0"}}let d=this.llmStep.execute(e,u,n.tools??[]);this.inFlightLLMRequests.set(e.internalId,d);let f=await d;return this.inFlightLLMRequests.delete(e.internalId),{matches:[...c,...f.matches],cost:f.cost}}throw new Error(`Unknown step type: ${a}`)}async executeRule(e,n,r){let i=e.id,o=r?.relativePath?n.filePaths.filter(E=>E===r.relativePath):[...n.filePaths],s=[],a;for(let E of e.steps){let d=E.id,f=E.step;if(f.type==="step-group"){let T=f.steps,p=[],m=T.some(O=>O.type==="ast-grep")?T.filter(O=>O.type!=="ripgrep"):T;for(let O=0;O<m.length;O++){let h=m[O],C=`${d}[${O}]`;this.eventEmitter.startStep(i,C,h.type,{filePaths:o,matches:s},d);let P=Date.now(),G=await this.executeStep(e,h,o,s,n,r),Y=Date.now()-P;G.filePaths!==void 0&&(o=n.filterFiles(G.filePaths));let re=[];if(G.matches!==void 0){let W=G.oldMatches||[];re=n.filterMatches(G.matches,W),p=p.concat(re)}this.eventEmitter.completeStep(i,C,h.type,{filePaths:o,matches:re},Y,d)}s=p}else{this.eventEmitter.startStep(i,d,f.type,{filePaths:o,matches:s});let T=Date.now(),p=await this.executeStep(e,f,o,s,n,r),S=Date.now()-T;if(p.filePaths!==void 0&&(o=n.filterFiles(p.filePaths),s=n.filterMatchesByFilePaths(s,o)),p.matches!==void 0){let m=p.oldMatches||[];s=n.filterMatches(p.matches,m)}p.cost!==void 0&&(a=p.cost),this.eventEmitter.completeStep(i,d,f.type,{filePaths:o,matches:s},S)}if(o.length===0)break}let c=s;if(r?.dismissedMatchesByRule){let E=r.dismissedMatchesByRule.get(e.internalId);if(E&&E.length>0){let d=new Map;for(let p of c){let S=p.file.path;d.has(S)||d.set(S,[]),d.get(S).push(p)}let f=new Map;for(let p of E){let S=p.file.path;f.has(S)||f.set(S,[]),f.get(S).push(p)}let T=[];for(let[p,S]of d){let m=f.get(p)||[];if(m.length===0){T.push(...S);continue}let O=S.map(G=>({file:p,startLine:G.range.start.line,endLine:G.range.end.line,fingerprint:G.fingerprint})),h=m.map(G=>({file:p,startLine:G.range.start.line,endLine:G.range.end.line,fingerprint:G.fingerprint})),P=gh(O,h).map(G=>S.find(Y=>Y.range.start.line===G.startLine&&Y.range.end.line===G.endLine&&Y.fingerprint===G.fingerprint));T.push(...P)}c=T}}let u=c.sort((E,d)=>E.file.path.localeCompare(d.file.path)),l={ruleId:i,matches:u,cost:a};return this.previousResults.set(e.internalId,l),l}shouldDeduplicateMatches(e){return e.hasBaseContent!==void 0}getPoolSize(){let e=nat().length;return Math.max(2,Math.min(8,e))}async execute(e,n,r){this.eventEmitter.startRules(e.length);let i=this.getPoolSize(),o=[],s=[...e],a=async d=>{let f=d.id,T=!1;for(let O of d.steps)if(O.step.type==="llm"){T=!0;break}this.eventEmitter.emit("rules:rule-start",{ruleId:f,isLlm:T,message:d.message,severity:d.severity});let p=await this.executeRule(d,n,r||{});this.eventEmitter.emit("rules:rule-complete",{ruleId:f,matches:p.matches});let S=new Map;for(let O of p.matches){let h=O.file.path;S.has(h)||S.set(h,[]),S.get(h).push(O)}let m=r?.relativePath?[r.relativePath]:n.filePaths;for(let[O,h]of S.entries())this.eventEmitter.emit("rules:rule-file-complete",{ruleId:f,filePath:O,matches:h});for(let O of m)S.has(O)||this.eventEmitter.emit("rules:rule-file-complete",{ruleId:f,filePath:O,matches:[]});return p},c=async d=>{let f=await a(d).catch(T=>T);if(f instanceof Error){if(r?.emitErrors)return this.eventEmitter.errorRule(d.id,f,d.message,d.severity),{ruleId:d.id,matches:[]};let T=new Error(`Error executing rule "${d.id}" (${d.message}): ${f.message}`);throw T.stack=f.stack,T}return f};await(async()=>{let d=async()=>{if(s.length===0)return;let T=s.shift(),p=await c(T);o.push(p),await d()},f=[];for(let T=0;T<Math.min(i,e.length);T++)f.push(d());await Promise.all(f)})();let l=new Map(e.map((d,f)=>[d.id,f]));o.sort((d,f)=>{let T=l.get(d.ruleId)??0,p=l.get(f.ruleId)??0;return T-p});let E=o.reduce((d,f)=>d+f.matches.length,0);return this.eventEmitter.completeRules(e.length,E),Ae.logMemory(`After rules: ${e.length}`),this.sharedAstCache.logStats(),o}};import{stripVTControlCharacters as yQ}from"node:util";import fC from"node:process";import tQ from"node:process";import _C from"node:process";var rat=(t,e,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let i=Object.getOwnPropertyDescriptor(t,n),o=Object.getOwnPropertyDescriptor(e,n);!iat(i,o)&&r||Object.defineProperty(t,n,o)},iat=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},oat=(t,e)=>{let n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)},sat=(t,e)=>`/* Wrapped ${t}*/
|
|
217
|
+
`)}var tat={read:WJ,grep:KJ,glob:zJ},aC=class{environment;eventEmitter;config;maxIterations;batchSize;constructor(e,n,r,i,o){this.environment=n,this.eventEmitter=r||new zr,this.config=e,this.maxIterations=i||20,this.batchSize=o||50}async executeTool(e,n,r,i){if(n==="report_fix")return{error:"Tool 'report_fix' is not supported in LLMStep. Available tools are: read, grep, glob"};let o=tat[n];if(!o)return{error:`Unknown tool: ${n}. Available tools are: read, grep, glob`};let s=HJ(n,r,[o]);if(!s.success)return{error:`Tool parameter validation failed: ${s.error}. Please fix the parameters and try again.`};let a=s.data;switch(n){case"read":{this.eventEmitter.llmToolExecution(e,"read",{file:a.target_file,offset:a.offset,limit:a.limit});let c=await qO(a,this.environment.getWorkspaceRoot());if(!("error"in c)){let u=a.target_file;i.some(l=>l.path===u)||i.push({path:u,sha:c.sha})}return"error"in c?c:c.content}case"grep":{this.eventEmitter.llmToolExecution(e,"grep",{path:a.path,pattern:a.pattern});let c=await JO(a,this.environment.getWorkspaceRoot(),[],ZJ());if(!("error"in c))for(let u of c.matches)i.some(l=>l.path===u.file)||i.push({path:u.file,sha:u.sha});return"error"in c?c:JSON.stringify(c.matches)}case"glob":{this.eventEmitter.llmToolExecution(e,"glob",{path:a.path,pattern:a.pattern});let c=await QO(a,this.environment.getWorkspaceRoot());return"error"in c?c:JSON.stringify(c.files)}default:return{error:`Unknown tool: ${n}`}}}async hydrateMatchesWithFileContent(e){let n=[];for(let r of e){let i=await t1(this.environment.getWorkspaceRoot(),r.file.path,r.range).catch(s=>{if(s.code==="ENOENT")return null;throw s});if(i===null)continue;let o=r.evidence;if(r.evidence&&r.evidence.length>0){o=[];let s=!1;for(let a of r.evidence){let c=await t1(this.environment.getWorkspaceRoot(),a.file.path,a.range).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(c===null){s=!0;break}o.push({...a,text:c})}if(s)continue}n.push({...r,text:i,evidence:o})}return n}async executeLLMValidation(e,n,r){let i=Date.now(),o=this.config.getLLMProvider();this.eventEmitter.startLLMValidation(e.id,n.length);let s=[],a=[],c=new sr(0),u=new sr(0),l=new sr(0);this.eventEmitter.startLLMSearchPhase(e.id,n.length);let E,d=[],f=[];for(let h=0;h<this.maxIterations;h++){let C=await o.search({rule:e,matches:n,tools:r,messages:s,files:a});if(f.push(C),C.usage&&C.usage.inputTokens&&C.usage.outputTokens&&C.usage.cost&&(c=c.plus(new sr(C.usage.inputTokens)),u=u.plus(new sr(C.usage.outputTokens)),l=l.plus(new sr(C.usage.cost))),C.type==="partial_matches"){let P=await this.hydrateMatchesWithFileContent(C.matches);d=[...d,...P],n=C.unresolved;continue}if(C.type==="matches"){let P=await this.hydrateMatchesWithFileContent(C.matches);E={...C,matches:[...d,...P]};break}if(C.type==="request_files"){for(let P of C.files)a.some(G=>G.path===P.path)||a.push({path:P.path,sha:P.sha});continue}if(C.type==="assistant"){s.push({type:"assistant",content:C.content}),s.push({type:"user",content:"Please use tool calls to interact with the codebase and report violations."});continue}if(C.type==="tool_request"){s.push({type:"tool_request",tool_calls:C.tool_calls});let P=await Promise.all(C.tool_calls.map(async G=>{let Y=await this.executeTool(e.id,G.function.name,G.function.arguments,a),re=typeof Y=="string"?Y:JSON.stringify(Y);return{tool_call_id:G.id,content:re}}));s.push({type:"tool_response",tool_results:P});continue}}if(!E)throw this.eventEmitter.emit("llm:max-iterations-reached",{ruleId:e.id,maxIterations:this.maxIterations,messages:s,results:f}),new Error(`Max iterations (${this.maxIterations}) reached without getting matches`);let T=E.matches;if(T.length===0){let h=c.plus(u).toNumber();return this.eventEmitter.completeLLMValidation(e.id,h,c.toNumber(),u.toNumber(),l.toString(),Date.now()-i,0,!1),{matches:[],executionTime:Date.now()-i,cost:l.toString()}}this.eventEmitter.startLLMValidationPhase(e.id,T.length);let p=[],S=T;for(;S.length>0;){let h=await o.validate({rule:e,matches:S,files:a});if(h.usage&&h.usage.inputTokens&&h.usage.outputTokens&&h.usage.cost&&(c=c.plus(new sr(h.usage.inputTokens)),u=u.plus(new sr(h.usage.outputTokens)),l=l.plus(new sr(h.usage.cost))),h.type==="partial_matches"){let C=await this.hydrateMatchesWithFileContent(h.matches);p=[...p,...C],S=h.unresolved;continue}if(h.type==="matches"){let C=await this.hydrateMatchesWithFileContent(h.matches);p=[...p,...C];break}}let m=p,O=c.plus(u).toNumber();return this.eventEmitter.completeLLMValidation(e.id,O,c.toNumber(),u.toNumber(),l.toString(),Date.now()-i,m.length,!1),{matches:m,executionTime:Date.now()-i,cost:l.toString()}}async execute(e,n,r){if(n.length===0)return{matches:[],executionTime:0,cost:"0"};let i=Date.now(),o=[...n].sort((l,E)=>l.file.path!==E.file.path?l.file.path.localeCompare(E.file.path):l.range.start.line-E.range.start.line),s=[];for(let l=0;l<o.length;l+=this.batchSize)s.push(o.slice(l,l+this.batchSize));let a=s.length,c=[],u=new sr(0);for(let l=0;l<s.length;l++){let E=s[l],d=l+1,f=n.length-(l+1)*this.batchSize,T=Math.max(0,f);a>1&&this.eventEmitter.llmValidationPhaseBatch(e.id,d,a,E.length,T,n.length);let p=await this.executeLLMValidation(e,E,r);c=[...c,...p.matches],u=u.plus(new sr(p.cost))}return{matches:c,executionTime:Date.now()-i,cost:u.toString()}}};var La=class{fileFilterStep;findMatchesStep;llmStep;environment;eventEmitter;config;previousResults=new Map;inFlightLLMRequests=new Map;sharedAstCache;constructor(e,n,r){this.environment=n,this.eventEmitter=r||new zr,this.config=e,this.sharedAstCache=new Od,this.fileFilterStep=new jO(this.environment),this.findMatchesStep=new iC(this.environment,this.eventEmitter,this.sharedAstCache),this.llmStep=new aC(this.config,this.environment,this.eventEmitter)}clearCache(){this.previousResults.clear(),this.inFlightLLMRequests.clear(),this.sharedAstCache.clear()}async executeStep(e,n,r,i,o,s){let a=n.type;if(a==="ast-grep"){let{type:c,language:u,...l}=n,E=r.map(T=>o.getFileInput(T,!1)),d=await this.findMatchesStep.execute(l,u,{fileInputs:E}),f=[];if(this.shouldDeduplicateMatches(o)){let T=r.filter(p=>o.hasBaseContent(p));if(T.length>0){let p=T.map(m=>o.getFileInput(m,!0));f=(await this.findMatchesStep.execute(l,u,{fileInputs:p})).matches}}return{matches:d.matches,oldMatches:f}}if(a==="ripgrep"){let{type:c,...u}=n,l=r.map(f=>o.getFileInput(f,!1)),E=await this.findMatchesStep.execute(u,"Unknown",{fileInputs:l}),d=[];if(this.shouldDeduplicateMatches(o)){let f=r.filter(T=>o.hasBaseContent(T));if(f.length>0){let T=f.map(S=>o.getFileInput(S,!0));d=(await this.findMatchesStep.execute(u,"Unknown",{fileInputs:T})).matches}}return{matches:E.matches,oldMatches:d}}if(a==="file-filter")return{filePaths:this.fileFilterStep.execute(r,{include:n.include,ignore:n.ignore,additionalGlobs:this.config.getAdditionalGlobs()}).filteredPaths};if(a==="llm"){if(i.length===0)return{matches:[],cost:"0"};let c=[],u=i;if(this.previousResults.has(e.internalId)){let p=this.previousResults.get(e.internalId).matches,S=FV(i,p);if(c=S.remappedMatches,u=S.unmappedMatches,c.length>0){let m=c.length+u.length;this.eventEmitter.emit("rules:rule-partial",{ruleId:e.internalId,matches:c,totalMatches:m});let O=new Map;for(let h of c){let C=h.file.path;O.has(C)||O.set(C,[]),O.get(C).push(h)}for(let[h,C]of O.entries())this.eventEmitter.emit("rules:rule-file-partial",{ruleId:e.internalId,filePath:h,matches:C,totalMatches:m})}}if(u.length===0)return{matches:c,cost:"0"};let E=this.inFlightLLMRequests.get(e.internalId);if(E){let T=await E,{remappedMatches:p,unmappedMatches:S}=FV(u,T.matches);if(S.length>0){let m=this.llmStep.execute(e,S,n.tools??[]);this.inFlightLLMRequests.set(e.internalId,m);let O=await m;return this.inFlightLLMRequests.delete(e.internalId),{matches:[...c,...p,...O.matches],cost:O.cost}}else return{matches:[...c,...p],cost:"0"}}let d=this.llmStep.execute(e,u,n.tools??[]);this.inFlightLLMRequests.set(e.internalId,d);let f=await d;return this.inFlightLLMRequests.delete(e.internalId),{matches:[...c,...f.matches],cost:f.cost}}throw new Error(`Unknown step type: ${a}`)}async executeRule(e,n,r){let i=e.id,o=n.filePaths||[],s=r?.relativePath?o.filter(d=>d===r.relativePath):[...o],a=[],c;for(let d of e.steps){let f=d.id,T=d.step;if(T.type==="step-group"){let p=T.steps,S=[],O=p.some(h=>h.type==="ast-grep")?p.filter(h=>h.type!=="ripgrep"):p;for(let h=0;h<O.length;h++){let C=O[h],P=`${f}[${h}]`;this.eventEmitter.startStep(i,P,C.type,{filePaths:s,matches:a},f);let G=Date.now(),Y=await this.executeStep(e,C,s,a,n,r),re=Date.now()-G;Y.filePaths!==void 0&&(s=n.filterFiles(Y.filePaths));let W=[];if(Y.matches!==void 0){let q=Y.oldMatches||[];W=n.filterMatches(Y.matches,q),S=S.concat(W)}this.eventEmitter.completeStep(i,P,C.type,{filePaths:s,matches:W},re,f)}a=S}else{this.eventEmitter.startStep(i,f,T.type,{filePaths:s,matches:a});let p=Date.now(),S=await this.executeStep(e,T,s,a,n,r),m=Date.now()-p;if(S.filePaths!==void 0&&(s=n.filterFiles(S.filePaths),a=n.filterMatchesByFilePaths(a,s)),S.matches!==void 0){let O=S.oldMatches||[];a=n.filterMatches(S.matches,O)}S.cost!==void 0&&(c=S.cost),this.eventEmitter.completeStep(i,f,T.type,{filePaths:s,matches:a},m)}if(s.length===0)break}let u=a;if(r?.dismissedMatchesByRule){let d=r.dismissedMatchesByRule.get(e.internalId);if(d&&d.length>0){let f=new Map;for(let S of u){let m=S.file.path;f.has(m)||f.set(m,[]),f.get(m).push(S)}let T=new Map;for(let S of d){let m=S.file.path;T.has(m)||T.set(m,[]),T.get(m).push(S)}let p=[];for(let[S,m]of f){let O=T.get(S)||[];if(O.length===0){p.push(...m);continue}let h=m.map(Y=>({file:S,startLine:Y.range.start.line,endLine:Y.range.end.line,fingerprint:Y.fingerprint})),C=O.map(Y=>({file:S,startLine:Y.range.start.line,endLine:Y.range.end.line,fingerprint:Y.fingerprint})),G=gh(h,C).map(Y=>m.find(re=>re.range.start.line===Y.startLine&&re.range.end.line===Y.endLine&&re.fingerprint===Y.fingerprint));p.push(...G)}u=p}}let l=u.sort((d,f)=>d.file.path.localeCompare(f.file.path)),E={ruleId:i,matches:l,cost:c};return this.previousResults.set(e.internalId,E),E}shouldDeduplicateMatches(e){return e.hasBaseContent!==void 0}getPoolSize(){let e=nat().length;return Math.max(2,Math.min(8,e))}async execute(e,n,r){this.eventEmitter.startRules(e.length);let i=this.getPoolSize(),o=[],s=[...e],a=async d=>{let f=d.id,T=!1;for(let O of d.steps)if(O.step.type==="llm"){T=!0;break}this.eventEmitter.emit("rules:rule-start",{ruleId:f,isLlm:T,message:d.message,severity:d.severity});let p=await this.executeRule(d,n,r||{});this.eventEmitter.emit("rules:rule-complete",{ruleId:f,matches:p.matches});let S=new Map;for(let O of p.matches){let h=O.file.path;S.has(h)||S.set(h,[]),S.get(h).push(O)}let m=r?.relativePath?[r.relativePath]:n.filePaths||[];for(let[O,h]of S.entries())this.eventEmitter.emit("rules:rule-file-complete",{ruleId:f,filePath:O,matches:h});for(let O of m)S.has(O)||this.eventEmitter.emit("rules:rule-file-complete",{ruleId:f,filePath:O,matches:[]});return p},c=async d=>{let f=await a(d).catch(T=>T);if(f instanceof Error){if(r?.emitErrors)return this.eventEmitter.errorRule(d.id,f,d.message,d.severity),{ruleId:d.id,matches:[]};let T=new Error(`Error executing rule "${d.id}" (${d.message}): ${f.message}`);throw T.stack=f.stack,T}return f};await(async()=>{let d=async()=>{if(s.length===0)return;let T=s.shift(),p=await c(T);o.push(p),await d()},f=[];for(let T=0;T<Math.min(i,e.length);T++)f.push(d());await Promise.all(f)})();let l=new Map(e.map((d,f)=>[d.id,f]));o.sort((d,f)=>{let T=l.get(d.ruleId)??0,p=l.get(f.ruleId)??0;return T-p});let E=o.reduce((d,f)=>d+f.matches.length,0);return this.eventEmitter.completeRules(e.length,E),Ae.logMemory(`After rules: ${e.length}`),this.sharedAstCache.logStats(),o}};import{stripVTControlCharacters as yQ}from"node:util";import fC from"node:process";import tQ from"node:process";import _C from"node:process";var rat=(t,e,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;let i=Object.getOwnPropertyDescriptor(t,n),o=Object.getOwnPropertyDescriptor(e,n);!iat(i,o)&&r||Object.defineProperty(t,n,o)},iat=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},oat=(t,e)=>{let n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)},sat=(t,e)=>`/* Wrapped ${t}*/
|
|
218
218
|
${e}`,aat=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),cat=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),uat=(t,e,n)=>{let r=n===""?"":`with ${n.trim()}() `,i=sat.bind(null,r,e.toString());Object.defineProperty(i,"name",cat);let{writable:o,enumerable:s,configurable:a}=aat;Object.defineProperty(t,"toString",{value:i,writable:o,enumerable:s,configurable:a})};function n1(t,e,{ignoreNonConfigurable:n=!1}={}){let{name:r}=t;for(let i of Reflect.ownKeys(e))rat(t,e,i,n);return oat(t,e),uat(t,e,r),t}var cC=new WeakMap,XJ=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let n,r=0,i=t.displayName||t.name||"<anonymous>",o=function(...s){if(cC.set(o,++r),r===1)n=t.apply(this,s),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return n};return n1(o,t),cC.set(o,r),o};XJ.callCount=t=>{if(!cC.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return cC.get(t)};var qJ=XJ;var ql=[];ql.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&ql.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&ql.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var uC=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",r1=Symbol.for("signal-exit emitter"),i1=globalThis,lat=Object.defineProperty.bind(Object),o1=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(i1[r1])return i1[r1];lat(i1,r1,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,n){this.listeners[e].push(n)}removeListener(e,n){let r=this.listeners[e],i=r.indexOf(n);i!==-1&&(i===0&&r.length===1?r.length=0:r.splice(i,1))}emit(e,n,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let o of this.listeners[e])i=o(n,r)===!0||i;return e==="exit"&&(i=this.emit("afterExit",n,r)||i),i}},lC=class{},_at=t=>({onExit(e,n){return t.onExit(e,n)},load(){return t.load()},unload(){return t.unload()}}),s1=class extends lC{onExit(){return()=>{}}load(){}unload(){}},a1=class extends lC{#e=c1.platform==="win32"?"SIGINT":"SIGHUP";#n=new o1;#t;#a;#d;#p={};#c=!1;constructor(e){super(),this.#t=e,this.#p={};for(let n of ql)this.#p[n]=()=>{let r=this.#t.listeners(n),{count:i}=this.#n,o=e;if(typeof o.__signal_exit_emitter__=="object"&&typeof o.__signal_exit_emitter__.count=="number"&&(i+=o.__signal_exit_emitter__.count),r.length===i){this.unload();let s=this.#n.emit("exit",null,n),a=n==="SIGHUP"?this.#e:n;s||e.kill(e.pid,a)}};this.#d=e.reallyExit,this.#a=e.emit}onExit(e,n){if(!uC(this.#t))return()=>{};this.#c===!1&&this.load();let r=n?.alwaysLast?"afterExit":"exit";return this.#n.on(r,e),()=>{this.#n.removeListener(r,e),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#c){this.#c=!0,this.#n.count+=1;for(let e of ql)try{let n=this.#p[e];n&&this.#t.on(e,n)}catch{}this.#t.emit=(e,...n)=>this.#r(e,...n),this.#t.reallyExit=e=>this.#l(e)}}unload(){this.#c&&(this.#c=!1,ql.forEach(e=>{let n=this.#p[e];if(!n)throw new Error("Listener not defined for signal: "+e);try{this.#t.removeListener(e,n)}catch{}}),this.#t.emit=this.#a,this.#t.reallyExit=this.#d,this.#n.count-=1)}#l(e){return uC(this.#t)?(this.#t.exitCode=e||0,this.#n.emit("exit",this.#t.exitCode,null),this.#d.call(this.#t,this.#t.exitCode)):0}#r(e,...n){let r=this.#a;if(e==="exit"&&uC(this.#t)){typeof n[0]=="number"&&(this.#t.exitCode=n[0]);let i=r.call(this.#t,e,...n);return this.#n.emit("exit",this.#t.exitCode,null),i}else return r.call(this.#t,e,...n)}},c1=globalThis.process,{onExit:JJ,load:b1t,unload:v1t}=_at(uC(c1)?new a1(c1):new s1);var QJ=_C.stderr.isTTY?_C.stderr:_C.stdout.isTTY?_C.stdout:void 0,Eat=QJ?qJ(()=>{JJ(()=>{QJ.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},eQ=Eat;var EC=!1,Pd={};Pd.show=(t=tQ.stderr)=>{t.isTTY&&(EC=!1,t.write("\x1B[?25h"))};Pd.hide=(t=tQ.stderr)=>{t.isTTY&&(eQ(),EC=!0,t.write("\x1B[?25l"))};Pd.toggle=(t,e)=>{t!==void 0&&(EC=t),EC?Pd.show(e):Pd.hide(e)};var u1=Pd;var l1={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots14:{interval:80,frames:["\u2809\u2809","\u2808\u2819","\u2800\u2839","\u2800\u28B8","\u2800\u28F0","\u2880\u28E0","\u28C0\u28C0","\u28C4\u2840","\u28C6\u2800","\u2847\u2800","\u280F\u2800","\u280B\u2801"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},dotsCircle:{interval:80,frames:["\u288E ","\u280E\u2801","\u280A\u2811","\u2808\u2831"," \u2871","\u2880\u2870","\u2884\u2860","\u2886\u2840"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},rollingLine:{interval:80,frames:["/ "," - "," \\ "," |"," |"," \\ "," - ","/ "]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u{1F497} "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}};var Mh=l1,$1t=Object.keys(l1);var Jl={};or(Jl,{error:()=>mat,info:()=>Sat,success:()=>pat,warning:()=>hat});import fat from"node:tty";var Tat=fat?.WriteStream?.prototype?.hasColors?.()??!1,_t=(t,e)=>{if(!Tat)return i=>i;let n=`\x1B[${t}m`,r=`\x1B[${e}m`;return i=>{let o=i+"",s=o.indexOf(r);if(s===-1)return n+o+r;let a=n,c=0;for(;s!==-1;)a+=o.slice(c,s)+n,c=s+r.length,s=o.indexOf(r,c);return a+=o.slice(c)+r,a}},K1t=_t(0,0),z1t=_t(1,22),Z1t=_t(2,22),X1t=_t(3,23),q1t=_t(4,24),J1t=_t(53,55),Q1t=_t(7,27),eGt=_t(8,28),tGt=_t(9,29),nGt=_t(30,39),nQ=_t(31,39),rQ=_t(32,39),iQ=_t(33,39),oQ=_t(34,39),rGt=_t(35,39),iGt=_t(36,39),oGt=_t(37,39),sGt=_t(90,39),aGt=_t(40,49),cGt=_t(41,49),uGt=_t(42,49),lGt=_t(43,49),_Gt=_t(44,49),EGt=_t(45,49),dGt=_t(46,49),fGt=_t(47,49),TGt=_t(100,49),SGt=_t(91,39),pGt=_t(92,39),hGt=_t(93,39),mGt=_t(94,39),AGt=_t(95,39),gGt=_t(96,39),RGt=_t(97,39),NGt=_t(101,49),OGt=_t(102,49),CGt=_t(103,49),IGt=_t(104,49),MGt=_t(105,49),PGt=_t(106,49),DGt=_t(107,49);import sQ from"node:process";function Ph(){let{env:t}=sQ,{TERM:e,TERM_PROGRAM:n}=t;return sQ.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var dC=Ph(),Sat=oQ(dC?"\u2139":"i"),pat=rQ(dC?"\u2714":"\u221A"),hat=iQ(dC?"\u26A0":"\u203C"),mat=nQ(dC?"\u2716":"\xD7");function _1({onlyFirst:t=!1}={}){let n=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(n,t?void 0:"g")}var Aat=_1();function E1(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(Aat,"")}var pQ=ue(SQ(),1);function T1({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import Ms from"node:process";var Cat=3,S1=class{#e=0;start(){this.#e++,this.#e===1&&this.#n()}stop(){if(this.#e<=0)throw new Error("`stop` called more times than `start`");this.#e--,this.#e===0&&this.#t()}#n(){Ms.platform==="win32"||!Ms.stdin.isTTY||(Ms.stdin.setRawMode(!0),Ms.stdin.on("data",this.#a),Ms.stdin.resume())}#t(){Ms.stdin.isTTY&&(Ms.stdin.off("data",this.#a),Ms.stdin.pause(),Ms.stdin.setRawMode(!1))}#a(e){e[0]===Cat&&Ms.emit("SIGINT")}},Iat=new S1,p1=Iat;var h1=class{#e=0;#n=!1;#t=0;#a=-1;#d=0;#p=0;#c;#l;#r;#i;#o;#_;#s;#E;#S;#f;#T;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#c={color:"cyan",stream:fC.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#c.color,this.spinner=this.#c.spinner,this.#o=this.#c.interval,this.#r=this.#c.stream,this.#_=typeof this.#c.isEnabled=="boolean"?this.#c.isEnabled:T1({stream:this.#r}),this.#s=typeof this.#c.isSilent=="boolean"?this.#c.isSilent:!1,this.text=this.#c.text,this.prefixText=this.#c.prefixText,this.suffixText=this.#c.suffixText,this.indent=this.#c.indent,fC.env.NODE_ENV==="test"&&(this._stream=this.#r,this._isEnabled=this.#_,Object.defineProperty(this,"_linesToClear",{get(){return this.#e},set(n){this.#e=n}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#a}}),Object.defineProperty(this,"_lineCount",{get(){return this.#t}}))}get indent(){return this.#E}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#E=e,this.#h()}get interval(){return this.#o??this.#l.interval??100}get spinner(){return this.#l}set spinner(e){if(this.#a=-1,this.#o=void 0,typeof e=="object"){if(!Array.isArray(e.frames)||e.frames.length===0||e.frames.some(n=>typeof n!="string"))throw new Error("The given spinner must have a non-empty `frames` array of strings");if(e.interval!==void 0&&!(Number.isInteger(e.interval)&&e.interval>0))throw new Error("`spinner.interval` must be a positive integer if provided");this.#l=e}else if(!Ph())this.#l=Mh.line;else if(e===void 0)this.#l=Mh.dots;else if(e!=="default"&&Mh[e])this.#l=Mh[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#S}set text(e=""){this.#S=e,this.#h()}get prefixText(){return this.#f}set prefixText(e=""){this.#f=e,this.#h()}get suffixText(){return this.#T}set suffixText(e=""){this.#T=e,this.#h()}get isSpinning(){return this.#i!==void 0}#C(e,n,r=!1){let i=typeof e=="function"?e():e;return typeof i=="string"&&i!==""?r?n+i:i+n:""}#m(e=this.#f,n=" "){return this.#C(e,n,!1)}#A(e=this.#T,n=" "){return this.#C(e,n,!0)}#O(e,n){let r=0;for(let i of E1(e).split(`
|
|
219
219
|
`))r+=Math.max(1,Math.ceil((0,pQ.default)(i)/n));return r}#h(){let e=this.#r.columns??80,n=typeof this.#f=="function"?"":this.#f,r=typeof this.#T=="function"?"":this.#T,i=typeof n=="string"&&n!==""?n+" ":"",o=typeof r=="string"&&r!==""?" "+r:"",a=" ".repeat(this.#E)+i+"-"+(typeof this.#S=="string"?" "+this.#S:"")+o;this.#t=this.#O(a,e)}get isEnabled(){return this.#_&&!this.#s}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#_=e}get isSilent(){return this.#s}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#s=e}frame(){let e=Date.now();(this.#a===-1||e-this.#d>=this.interval)&&(this.#a=++this.#a%this.#l.frames.length,this.#d=e);let{frames:n}=this.#l,r=n[this.#a];this.color&&(r=j[this.color](r));let i=this.#m(this.#f," "),o=typeof this.text=="string"?" "+this.text:"",s=this.#A(this.#T," ");return i+r+o+s}clear(){if(!this.#_||!this.#r.isTTY)return this;this.#r.cursorTo(0);for(let e=0;e<this.#e;e++)e>0&&this.#r.moveCursor(0,-1),this.#r.clearLine(1);return(this.#E||this.#p!==this.#E)&&this.#r.cursorTo(this.#E),this.#p=this.#E,this.#e=0,this}render(){if(!this.#_||this.#s)return this;this.clear();let e=this.frame(),n=this.#r.columns??80,r=this.#O(e,n),i=this.#r.rows;if(i&&i>1&&r>i){let o=e.split(`
|
|
220
220
|
`),s=i-1;e=[...o.slice(0,s),"... (content truncated to fit terminal)"].join(`
|
|
@@ -278,12 +278,12 @@ ${Re}`)}else u.push(Z)}let E="";if(o&&(o.mode==="check"?E=o.filePath?` ${j.dim(`
|
|
|
278
278
|
`+f),i&&s.size>0&&i.start()}).catch(f=>{console.error("Error formatting rule result:",f),i&&s.size>0&&i.start()}),a.add(u.ruleId)}}c()}),t.on("rules:rule-error",u=>{s.delete(u.ruleId),c()}),t.on("llm:tool-execution",u=>{let l=s.get(u.ruleId);l&&(l.toolInfo={toolName:u.toolName,file:u.file,path:u.path,pattern:u.pattern,offset:u.offset,limit:u.limit},c())}),t.on("llm:search-phase:start",u=>{let l=s.get(u.ruleId);l&&(l.searchPhase={matchCount:u.matchCount},c())}),t.on("llm:validation-phase:start",u=>{let l=s.get(u.ruleId);l&&(l.toolInfo=void 0,l.searchPhase=void 0,l.validationPhase={matchCount:u.matchCount},c())}),t.on("llm:validation-phase:batch",u=>{let l=s.get(u.ruleId);l&&(l.batchInfo={currentBatch:u.currentBatch,totalBatches:u.totalBatches,batchSize:u.batchSize,remainingMatches:u.remainingMatches,totalMatches:u.totalMatches},c())}),t.on("rules:progress",u=>{c()}),t.on("rules:complete",()=>{i&&(i._updateInterval&&clearInterval(i._updateInterval),i.stopAndPersist(),i=null),s.clear()}),()=>{i&&(i._updateInterval&&clearInterval(i._updateInterval),i.stopAndPersist(),i=null),s.clear()}}var hC=class extends _O{provider="claude";dataSchema=P6;eventSchemas=M6;getConversationId(e){return e.session_id}async handleEvent(e,n){switch(e){case"SessionStart":return await this.handleSessionStart(n);case"PostToolUse":return await this.handlePostToolUse(n);case"Stop":return await this.handleStop(n);case"SessionEnd":return await this.handleSessionEnd(n);default:throw new Error(`Unknown Claude event: ${e}`)}}async isSessionValid(e){let n=new Kr({repositoryUrl:void 0,workspaceRoot:e}),r=await mC(),i=await Yo.initialize(n,{apiKey:r||void 0});return"failed"in i?{valid:!1,error:i.error}:{valid:!0}}async handleSessionStart(e){Ae.log(`[ClaudeHookHandler] SessionStart for session ${e.session_id}`);let n=await this.isSessionValid(e.cwd);if(!n.valid){Ae.log(`[ClaudeHookHandler] API key not configured or invalid. Error: ${n.error}. Skipping session initialization.`);return}Ae.log("[ClaudeHookHandler] Config validated successfully");let i=await new Na().initializeSession(e.cwd,"claude",e.session_id);Ae.log(`[ClaudeHookHandler] Initialized wispbit session: ${i}`);let o=process.env.CLAUDE_ENV_FILE;if(o){Ae.log(`[ClaudeHookHandler] Writing session ID to CLAUDE_ENV_FILE: ${o}`);let a=`export WISPBIT_SESSION_ID="${i}"
|
|
279
279
|
`;await wQ.promises.appendFile(o,a)}return{systemMessage:new Cl({level:3}).dim.italic("wispbit will automatically review all changes in this session")}}async handlePostToolUse(e){Ae.log(`[ClaudeHookHandler] PostToolUse (${e.tool_name}) for file ${e.tool_input.file_path}`);let n=new Na;if(!await n.getSession("claude",e.session_id)){Ae.log("[ClaudeHookHandler] Session not initialized, skipping PostToolUse");return}let i=e.tool_input.file_path,o=AC.isAbsolute(i)?AC.relative(e.cwd,i):i,s,a;e.tool_name==="Write"?(a="",s=e.tool_input.content||""):(a=e.tool_input.old_string||"",s=e.tool_input.new_string||""),await n.addFileChange(o,a,s),Ae.log(`[ClaudeHookHandler] Added change for ${o}`)}async handleStop(e){Ae.log(`[ClaudeHookHandler] Stop for session ${e.session_id}`);let n=new Na,r=await n.getSession("claude",e.session_id);if(!r){Ae.log("[ClaudeHookHandler] Session not initialized, skipping Stop");return}Ae.log(`[ClaudeHookHandler] Wispbit session ID: ${r.wispbitSessionId}`);let i=n.getLastCheckpointTimestamp();if((i?n.getFileChanges(i):n.getFileChanges()).length===0){Ae.log("[ClaudeHookHandler] No file changes since last checkpoint, skipping");return}let s=n.getFileChanges();Ae.log(`[ClaudeHookHandler] Found ${s.length} files changed in session`);for(let P of s)Ae.log(`
|
|
280
280
|
[ClaudeHookHandler] File: ${P.filename} (${P.status})`),Ae.log(`[ClaudeHookHandler] +${P.additions} -${P.deletions}`),Ae.log(`[ClaudeHookHandler] Diff:
|
|
281
|
-
${P.patch}`);let{results:a,rules:c}=await this.runPowerlint(e.cwd,s),u=a.flatMap(P=>P.matches.map(G=>({...G,ruleId:P.ruleId}))),l=n.getLastCheckpointMatches(),E=new Map;for(let P of u){let G=P.ruleId;E.has(G)||E.set(G,[]),E.get(G).push(P)}let d=new Map;for(let P of l)d.has(P.ruleId)||d.set(P.ruleId,[]),d.get(P.ruleId).push(P);let f=[];for(let[P,G]of E.entries()){let Y=d.get(P)||[],re=G.map(H=>({file:H.file.path,startLine:H.range.start.line,endLine:H.range.end.line,fingerprint:H.fingerprint})),W=Y.map(H=>({file:H.file.path,startLine:H.range.start.line,endLine:H.range.end.line,fingerprint:H.fingerprint})),q=Ah(re,W),Z=G.filter((H,oe)=>!q.has(oe));f.push(...Z)}let T=new Map;for(let P of f){let G=P.ruleId;T.has(G)||T.set(G,[]),T.get(G).push(P)}let p=Array.from(T.entries()).map(([P,G])=>({ruleId:P,matches:G})),S=new Map;for(let P of u){let G=P.ruleId;S.has(G)||S.set(G,[]),S.get(G).push(P)}let m=Array.from(S.entries()).map(([P,G])=>({ruleId:P,matches:G})),O=f.length,h=u.length;Ae.log(`[ClaudeHookHandler] New: ${O}, Total: ${h}`),await n.createCheckpoint(f);let C=await this.buildStopMessage(p,m,c,e.cwd,O,h,s.length);if(Ae.log(`[ClaudeHookHandler] Built system message: ${C?"yes":"no"}`),!!C)return{systemMessage:C}}async handleSessionEnd(e){Ae.log(`[ClaudeHookHandler] SessionEnd (${e.reason}) for session ${e.session_id}`);let n=new Na;if(!await n.getSession("claude",e.session_id)){Ae.log("[ClaudeHookHandler] Session not initialized, skipping SessionEnd");return}await n.endSession()}async runPowerlint(e,n){let r=new Kr({repositoryUrl:void 0,workspaceRoot:e}),i=await mC(),o=await Yo.initialize(r,{apiKey:i||void 0});if("failed"in o)throw new Error(`Failed to initialize config: ${o.error}`);let s=o,a=new zr,c=new $o(s,r),u=await c.loadAllRules(),l=new La(s,r,a),E=await c.getDismissals([]),d=new Map;for(let p of E)d.has(p.ruleId)||d.set(p.ruleId,[]),d.get(p.ruleId).push(p.match);let f=await Pa.initialize(s,r,"session",a,void 0,void 0,{fileChanges:n});return{results:await l.execute(u,f,{dismissedMatchesByRule:d}),rules:u}}async buildStopMessage(e,n,r,i,o,s,a){let c=e.filter(f=>f.matches.length>0),u=n.filter(f=>f.matches.length>0),l=new Cl({level:3}),E;if(s===o)if(o>0)E=l.red("wispbit found ")+l.red.bold(`${o} new`)+l.red(` ${o===1?"issue":"issues"}`);else return null;else o>0?E=l.red("wispbit found ")+l.red.bold(`${o} new`)+l.red(` ${o===1?"issue":"issues"}`)+l.dim(` (${s} total)`):E=l.dim.italic(`wispbit found ${s} total ${s===1?"issue":"issues"} from ${a} ${a===1?"file edit":"file edits"} this session`);let d=[];if(c.length>0){let f=new Set;for(let p of u)for(let S of p.matches)f.add(S.file.path);let T=await vh(c,r,i,l,{maxMatchesPerRule:1,maxDiffLines:10});d.push(T),d.push("",E),d.push(l.dim("Run ")+l.cyan("!wispbit")+l.dim(" to view, ")+l.cyan("!wispbit --fix")+l.dim(" to fix, ")+l.cyan("!wispbit --dismiss")+l.dim(" to dismiss (add ")+l.cyan("RULE-123")+l.dim(" for specific rules)"))}else u.length>0?d.push(E+l.dim.italic(". Run ")+l.cyan("!wispbit")+l.dim.italic(" to view and fix issues.")):d.push(E);return d.join(`
|
|
282
|
-
`)}};function xQ(t){switch(t){case"claude":return new hC;default:throw new Error(`Unknown hook provider: ${t}`)}}import*as Wc from"fs/promises";import*as VQ from"os";import*as Uh from"path";var gC=class{getStorageDir(){return Uh.join(VQ.homedir(),".wispbit","hooks")}getStoragePath(e){return Uh.join(this.getStorageDir(),`${e}.json`)}async load(e){let n=this.getStoragePath(e);try{let r=await Wc.readFile(n,"utf-8");return JSON.parse(r)}catch{return null}}async save(e,n){let r=this.getStoragePath(e);await Wc.mkdir(Uh.dirname(r),{recursive:!0}),await Wc.writeFile(r,JSON.stringify(n,null,2))}async clear(e){let n=this.getStoragePath(e);try{await Wc.unlink(n)}catch{}}};async function GQ(t,e){let[n,r]=t.split(".");if(!n||!r)throw new Error(`Invalid providerEvent format: ${t}. Expected "provider.event"`);let i=xQ(n),o=new gC,s=i.eventSchemas[r];if(!s)throw new Error(`Unknown event: ${r} for provider: ${n}`);let a=s.parse(e),c=i.getConversationId(a);i._setContext(o,c);let u=await i.handleEvent(r,a);return i._clearContext(),u??{}}var _r=ue(are(),1);import{promises as _re}from"fs";import{join as u_,relative as Ere}from"path";import{fileURLToPath as Jo,pathToFileURL as tlt}from"url";var WI=class t{constructor(e,n,r,i){this._uri=e,this._languageId=n,this._version=r,this._content=i,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){let n=this.offsetAt(e.start),r=this.offsetAt(e.end);return this._content.substring(n,r)}return this._content}update(e,n){for(let r of e)if(t.isIncremental(r)){let i=lre(r.range),o=this.offsetAt(i.start),s=this.offsetAt(i.end);this._content=this._content.substring(0,o)+r.text+this._content.substring(s,this._content.length);let a=Math.max(i.start.line,0),c=Math.max(i.end.line,0),u=this._lineOffsets,l=cre(r.text,!1,o);if(c-a===l.length)for(let d=0,f=l.length;d<f;d++)u[d+a+1]=l[d];else l.length<1e4?u.splice(a+1,c-a,...l):this._lineOffsets=u=u.slice(0,a+1).concat(l,u.slice(c+1));let E=r.text.length-(s-o);if(E!==0)for(let d=a+1+l.length,f=u.length;d<f;d++)u[d]=u[d]+E}else if(t.isFull(r))this._content=r.text,this._lineOffsets=void 0;else throw new Error("Unknown change event received");this._version=n}getLineOffsets(){return this._lineOffsets===void 0&&(this._lineOffsets=cre(this._content,!0)),this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);let n=this.getLineOffsets(),r=0,i=n.length;if(i===0)return{line:0,character:e};for(;r<i;){let s=Math.floor((r+i)/2);n[s]>e?i=s:r=s+1}let o=r-1;return e=this.ensureBeforeEOL(e,n[o]),{line:o,character:e-n[o]}}offsetAt(e){let n=this.getLineOffsets();if(e.line>=n.length)return this._content.length;if(e.line<0)return 0;let r=n[e.line];if(e.character<=0)return r;let i=e.line+1<n.length?n[e.line+1]:this._content.length,o=Math.min(r+e.character,i);return this.ensureBeforeEOL(o,r)}ensureBeforeEOL(e,n){for(;e>n&&ure(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){let n=e;return n!=null&&typeof n.text=="string"&&n.range!==void 0&&(n.rangeLength===void 0||typeof n.rangeLength=="number")}static isFull(e){let n=e;return n!=null&&typeof n.text=="string"&&n.range===void 0&&n.rangeLength===void 0}},rm;(function(t){function e(i,o,s,a){return new WI(i,o,s,a)}t.create=e;function n(i,o,s){if(i instanceof WI)return i.update(o,s),i;throw new Error("TextDocument.update: document must be created by TextDocument.create")}t.update=n;function r(i,o){let s=i.getText(),a=CF(o.map(Xut),(l,E)=>{let d=l.range.start.line-E.range.start.line;return d===0?l.range.start.character-E.range.start.character:d}),c=0,u=[];for(let l of a){let E=i.offsetAt(l.range.start);if(E<c)throw new Error("Overlapping edit");E>c&&u.push(s.substring(c,E)),l.newText.length&&u.push(l.newText),c=i.offsetAt(l.range.end)}return u.push(s.substr(c)),u.join("")}t.applyEdits=r})(rm||(rm={}));function CF(t,e){if(t.length<=1)return t;let n=t.length/2|0,r=t.slice(0,n),i=t.slice(n);CF(r,e),CF(i,e);let o=0,s=0,a=0;for(;o<r.length&&s<i.length;)e(r[o],i[s])<=0?t[a++]=r[o++]:t[a++]=i[s++];for(;o<r.length;)t[a++]=r[o++];for(;s<i.length;)t[a++]=i[s++];return t}function cre(t,e,n=0){let r=e?[n]:[];for(let i=0;i<t.length;i++){let o=t.charCodeAt(i);ure(o)&&(o===13&&i+1<t.length&&t.charCodeAt(i+1)===10&&i++,r.push(n+i+1))}return r}function ure(t){return t===13||t===10}function lre(t){let e=t.start,n=t.end;return e.line>n.line||e.line===n.line&&e.character>n.character?{start:n,end:e}:t}function Xut(t){let e=lre(t.range);return e!==t.range?{newText:t.newText,range:e}:t}function qr(t){let e=decodeURIComponent(t);return e.startsWith("file:///")&&(e=e.replace(/\\/g,"/")),e=e.replace(/^file:\/\/\/([a-z]):/,(n,r)=>`file:///${r.toUpperCase()}:`),e}var KI=class{syncedDocuments=new Map;diagnosticsByFileAndRule=new Map;dismissalsByFile=new Map;fixesByFile=new Map;listen(e,n){e.onDidOpenTextDocument(r=>{let i=r.textDocument,o=qr(i.uri),s=rm.create(o,i.languageId,i.version,i.text);this.syncedDocuments.set(o,s),n.onDidOpen?.(o,s)}),e.onDidChangeTextDocument(r=>{let i=r.textDocument,o=qr(i.uri),s=r.contentChanges;if(s.length===0)return;let a=i.version;if(a==null)return;let c=this.syncedDocuments.get(o);c&&(c=rm.update(c,s,a),this.syncedDocuments.set(o,c),n.onDidChangeContent?.(o,c,s))}),e.onDidCloseTextDocument(r=>{let i=qr(r.textDocument.uri);this.syncedDocuments.delete(i),n.onDidClose?.(i)}),e.onDidSaveTextDocument(r=>{let i=qr(r.textDocument.uri),o=this.syncedDocuments.get(i);o&&n.onDidSave?.(i,o)})}getDocument(e){let n=qr(e);return this.syncedDocuments.get(n)}getAllDocumentUris(){return Array.from(this.syncedDocuments.values()).map(e=>e.uri)}getAllDiagnosticUris(){return Array.from(this.diagnosticsByFileAndRule.keys())}setDiagnosticsForRule(e,n,r){let i=qr(e);this.diagnosticsByFileAndRule.has(i)||this.diagnosticsByFileAndRule.set(i,new Map),this.diagnosticsByFileAndRule.get(i).set(n,r)}getDiagnosticsForRule(e,n){let r=qr(e),i=this.diagnosticsByFileAndRule.get(r);return i?i.get(n)||[]:[]}getDiagnostics(e){let n=qr(e),r=this.diagnosticsByFileAndRule.get(n);if(!r)return[];let i=[];for(let[o,s]of r.entries())i.push(...s);return i}clearDiagnostics(e){let n=qr(e);this.diagnosticsByFileAndRule.delete(n)}setDismissals(e,n){this.dismissalsByFile.set(e,n)}getDismissals(e){return this.dismissalsByFile.get(e)||[]}hasDismissals(e){return this.dismissalsByFile.has(e)}clearDismissals(e){this.dismissalsByFile.delete(e)}setFixes(e,n){this.fixesByFile.set(e,n)}getFixes(e){return this.fixesByFile.get(e)||[]}hasFixes(e){return this.fixesByFile.has(e)}clearFixes(e){this.fixesByFile.delete(e)}};import{sep as elt}from"path";var zI=class{runtimeManager;config;environment;apiClient;previousResults=new Map;constructor(e,n,r){this.runtimeManager=e,this.config=n,this.environment=r,this.apiClient=new Gl({baseUrl:n.getBaseUrl(),apiKey:n.getApiKey()})}clearCache(){this.previousResults.clear()}async execute(e,n,r){let i=this.environment.getWorkspaceRoot(),o=[],s=n?e.filePaths.filter(E=>E===n):e.filePaths,a=await this.runtimeManager.getDuplicates(i,n),c=await a.loadFileContents(i),u=a.clusterBySharedFiles()
|
|
283
|
-
`)[0].length}},language:this.detectLanguage(
|
|
281
|
+
${P.patch}`);let{results:a,rules:c}=await this.runPowerlint(e.cwd,s),u=a.flatMap(P=>P.matches.map(G=>({...G,ruleId:P.ruleId}))),l=n.getLastCheckpointMatches(),E=new Map;for(let P of u){let G=P.ruleId;E.has(G)||E.set(G,[]),E.get(G).push(P)}let d=new Map;for(let P of l)d.has(P.ruleId)||d.set(P.ruleId,[]),d.get(P.ruleId).push(P);let f=[];for(let[P,G]of E.entries()){let Y=d.get(P)||[],re=G.map(H=>({file:H.file.path,startLine:H.range.start.line,endLine:H.range.end.line,fingerprint:H.fingerprint})),W=Y.map(H=>({file:H.file.path,startLine:H.range.start.line,endLine:H.range.end.line,fingerprint:H.fingerprint})),q=Ah(re,W),Z=G.filter((H,oe)=>!q.has(oe));f.push(...Z)}let T=new Map;for(let P of f){let G=P.ruleId;T.has(G)||T.set(G,[]),T.get(G).push(P)}let p=Array.from(T.entries()).map(([P,G])=>({ruleId:P,matches:G})),S=new Map;for(let P of u){let G=P.ruleId;S.has(G)||S.set(G,[]),S.get(G).push(P)}let m=Array.from(S.entries()).map(([P,G])=>({ruleId:P,matches:G})),O=f.length,h=u.length;Ae.log(`[ClaudeHookHandler] New: ${O}, Total: ${h}`),await n.createCheckpoint(f);let C=await this.buildStopMessage(p,m,c,e.cwd,O,h,s.length);if(Ae.log(`[ClaudeHookHandler] Built system message: ${C?"yes":"no"}`),!!C)return{systemMessage:C}}async handleSessionEnd(e){Ae.log(`[ClaudeHookHandler] SessionEnd (${e.reason}) for session ${e.session_id}`);let n=new Na;if(!await n.getSession("claude",e.session_id)){Ae.log("[ClaudeHookHandler] Session not initialized, skipping SessionEnd");return}await n.endSession()}async runPowerlint(e,n){let r=new Kr({repositoryUrl:void 0,workspaceRoot:e}),i=await mC(),o=await Yo.initialize(r,{apiKey:i||void 0});if("failed"in o)throw new Error(`Failed to initialize config: ${o.error}`);let s=o,a=new zr,c=new $o(s,r),u=await c.loadAllRules(),l=new La(s,r,a),E=await c.getDismissals([]),d=new Map;for(let p of E)d.has(p.ruleId)||d.set(p.ruleId,[]),d.get(p.ruleId).push(p.match);let f=await Pa.initialize(s,r,"session",a,void 0,void 0,{fileChanges:n});return{results:await l.execute(u,f,{dismissedMatchesByRule:d,emitErrors:!0}),rules:u}}async buildStopMessage(e,n,r,i,o,s,a){let c=e.filter(f=>f.matches.length>0),u=n.filter(f=>f.matches.length>0),l=new Cl({level:3}),E;if(s===o)if(o>0)E=l.red("wispbit found ")+l.red.bold(`${o} new`)+l.red(` ${o===1?"issue":"issues"}`);else return null;else o>0?E=l.red("wispbit found ")+l.red.bold(`${o} new`)+l.red(` ${o===1?"issue":"issues"}`)+l.dim(` (${s} total)`):E=l.dim.italic(`wispbit found ${s} total ${s===1?"issue":"issues"} from ${a} ${a===1?"file edit":"file edits"} this session`);let d=[];if(c.length>0){let f=new Set;for(let p of u)for(let S of p.matches)f.add(S.file.path);let T=await vh(c,r,i,l,{maxMatchesPerRule:1,maxDiffLines:10});d.push(T),d.push("",E),d.push(l.dim("Run ")+l.cyan("!wispbit")+l.dim(" to view, ")+l.cyan("!wispbit --fix")+l.dim(" to fix, ")+l.cyan("!wispbit --dismiss")+l.dim(" to dismiss (add ")+l.cyan("RULE-123")+l.dim(" for specific rules)"))}else u.length>0?d.push(E+l.dim.italic(". Run ")+l.cyan("!wispbit")+l.dim.italic(" to view and fix issues.")):d.push(E);return d.join(`
|
|
282
|
+
`)}};function xQ(t){switch(t){case"claude":return new hC;default:throw new Error(`Unknown hook provider: ${t}`)}}import*as Wc from"fs/promises";import*as VQ from"os";import*as Uh from"path";var gC=class{getStorageDir(){return Uh.join(VQ.homedir(),".wispbit","hooks")}getStoragePath(e){return Uh.join(this.getStorageDir(),`${e}.json`)}async load(e){let n=this.getStoragePath(e);try{let r=await Wc.readFile(n,"utf-8");return JSON.parse(r)}catch{return null}}async save(e,n){let r=this.getStoragePath(e);await Wc.mkdir(Uh.dirname(r),{recursive:!0}),await Wc.writeFile(r,JSON.stringify(n,null,2))}async clear(e){let n=this.getStoragePath(e);try{await Wc.unlink(n)}catch{}}};async function GQ(t,e){let[n,r]=t.split(".");if(!n||!r)throw new Error(`Invalid providerEvent format: ${t}. Expected "provider.event"`);let i=xQ(n),o=new gC,s=i.eventSchemas[r];if(!s)throw new Error(`Unknown event: ${r} for provider: ${n}`);let a=s.parse(e),c=i.getConversationId(a);i._setContext(o,c);let u=await i.handleEvent(r,a);return i._clearContext(),u??{}}var _r=ue(are(),1);import{promises as _re}from"fs";import{join as u_,relative as Ere}from"path";import{fileURLToPath as Jo,pathToFileURL as tlt}from"url";var WI=class t{constructor(e,n,r,i){this._uri=e,this._languageId=n,this._version=r,this._content=i,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){let n=this.offsetAt(e.start),r=this.offsetAt(e.end);return this._content.substring(n,r)}return this._content}update(e,n){for(let r of e)if(t.isIncremental(r)){let i=lre(r.range),o=this.offsetAt(i.start),s=this.offsetAt(i.end);this._content=this._content.substring(0,o)+r.text+this._content.substring(s,this._content.length);let a=Math.max(i.start.line,0),c=Math.max(i.end.line,0),u=this._lineOffsets,l=cre(r.text,!1,o);if(c-a===l.length)for(let d=0,f=l.length;d<f;d++)u[d+a+1]=l[d];else l.length<1e4?u.splice(a+1,c-a,...l):this._lineOffsets=u=u.slice(0,a+1).concat(l,u.slice(c+1));let E=r.text.length-(s-o);if(E!==0)for(let d=a+1+l.length,f=u.length;d<f;d++)u[d]=u[d]+E}else if(t.isFull(r))this._content=r.text,this._lineOffsets=void 0;else throw new Error("Unknown change event received");this._version=n}getLineOffsets(){return this._lineOffsets===void 0&&(this._lineOffsets=cre(this._content,!0)),this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);let n=this.getLineOffsets(),r=0,i=n.length;if(i===0)return{line:0,character:e};for(;r<i;){let s=Math.floor((r+i)/2);n[s]>e?i=s:r=s+1}let o=r-1;return e=this.ensureBeforeEOL(e,n[o]),{line:o,character:e-n[o]}}offsetAt(e){let n=this.getLineOffsets();if(e.line>=n.length)return this._content.length;if(e.line<0)return 0;let r=n[e.line];if(e.character<=0)return r;let i=e.line+1<n.length?n[e.line+1]:this._content.length,o=Math.min(r+e.character,i);return this.ensureBeforeEOL(o,r)}ensureBeforeEOL(e,n){for(;e>n&&ure(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){let n=e;return n!=null&&typeof n.text=="string"&&n.range!==void 0&&(n.rangeLength===void 0||typeof n.rangeLength=="number")}static isFull(e){let n=e;return n!=null&&typeof n.text=="string"&&n.range===void 0&&n.rangeLength===void 0}},rm;(function(t){function e(i,o,s,a){return new WI(i,o,s,a)}t.create=e;function n(i,o,s){if(i instanceof WI)return i.update(o,s),i;throw new Error("TextDocument.update: document must be created by TextDocument.create")}t.update=n;function r(i,o){let s=i.getText(),a=CF(o.map(Xut),(l,E)=>{let d=l.range.start.line-E.range.start.line;return d===0?l.range.start.character-E.range.start.character:d}),c=0,u=[];for(let l of a){let E=i.offsetAt(l.range.start);if(E<c)throw new Error("Overlapping edit");E>c&&u.push(s.substring(c,E)),l.newText.length&&u.push(l.newText),c=i.offsetAt(l.range.end)}return u.push(s.substr(c)),u.join("")}t.applyEdits=r})(rm||(rm={}));function CF(t,e){if(t.length<=1)return t;let n=t.length/2|0,r=t.slice(0,n),i=t.slice(n);CF(r,e),CF(i,e);let o=0,s=0,a=0;for(;o<r.length&&s<i.length;)e(r[o],i[s])<=0?t[a++]=r[o++]:t[a++]=i[s++];for(;o<r.length;)t[a++]=r[o++];for(;s<i.length;)t[a++]=i[s++];return t}function cre(t,e,n=0){let r=e?[n]:[];for(let i=0;i<t.length;i++){let o=t.charCodeAt(i);ure(o)&&(o===13&&i+1<t.length&&t.charCodeAt(i+1)===10&&i++,r.push(n+i+1))}return r}function ure(t){return t===13||t===10}function lre(t){let e=t.start,n=t.end;return e.line>n.line||e.line===n.line&&e.character>n.character?{start:n,end:e}:t}function Xut(t){let e=lre(t.range);return e!==t.range?{newText:t.newText,range:e}:t}function qr(t){let e=decodeURIComponent(t);return e.startsWith("file:///")&&(e=e.replace(/\\/g,"/")),e=e.replace(/^file:\/\/\/([a-z]):/,(n,r)=>`file:///${r.toUpperCase()}:`),e}var KI=class{syncedDocuments=new Map;diagnosticsByFileAndRule=new Map;dismissalsByFile=new Map;fixesByFile=new Map;listen(e,n){e.onDidOpenTextDocument(r=>{let i=r.textDocument,o=qr(i.uri),s=rm.create(o,i.languageId,i.version,i.text);this.syncedDocuments.set(o,s),n.onDidOpen?.(o,s)}),e.onDidChangeTextDocument(r=>{let i=r.textDocument,o=qr(i.uri),s=r.contentChanges;if(s.length===0)return;let a=i.version;if(a==null)return;let c=this.syncedDocuments.get(o);c&&(c=rm.update(c,s,a),this.syncedDocuments.set(o,c),n.onDidChangeContent?.(o,c,s))}),e.onDidCloseTextDocument(r=>{let i=qr(r.textDocument.uri);this.syncedDocuments.delete(i),n.onDidClose?.(i)}),e.onDidSaveTextDocument(r=>{let i=qr(r.textDocument.uri),o=this.syncedDocuments.get(i);o&&n.onDidSave?.(i,o)})}getDocument(e){let n=qr(e);return this.syncedDocuments.get(n)}getAllDocumentUris(){return Array.from(this.syncedDocuments.values()).map(e=>e.uri)}getAllDiagnosticUris(){return Array.from(this.diagnosticsByFileAndRule.keys())}setDiagnosticsForRule(e,n,r){let i=qr(e);this.diagnosticsByFileAndRule.has(i)||this.diagnosticsByFileAndRule.set(i,new Map),this.diagnosticsByFileAndRule.get(i).set(n,r)}getDiagnosticsForRule(e,n){let r=qr(e),i=this.diagnosticsByFileAndRule.get(r);return i?i.get(n)||[]:[]}getDiagnostics(e){let n=qr(e),r=this.diagnosticsByFileAndRule.get(n);if(!r)return[];let i=[];for(let[o,s]of r.entries())i.push(...s);return i}clearDiagnostics(e){let n=qr(e);this.diagnosticsByFileAndRule.delete(n)}setDismissals(e,n){this.dismissalsByFile.set(e,n)}getDismissals(e){return this.dismissalsByFile.get(e)||[]}hasDismissals(e){return this.dismissalsByFile.has(e)}clearDismissals(e){this.dismissalsByFile.delete(e)}setFixes(e,n){this.fixesByFile.set(e,n)}getFixes(e){return this.fixesByFile.get(e)||[]}hasFixes(e){return this.fixesByFile.has(e)}clearFixes(e){this.fixesByFile.delete(e)}};import{sep as elt}from"path";var zI=class{runtimeManager;config;environment;apiClient;previousResults=new Map;constructor(e,n,r){this.runtimeManager=e,this.config=n,this.environment=r,this.apiClient=new Gl({baseUrl:n.getBaseUrl(),apiKey:n.getApiKey()})}clearCache(){this.previousResults.clear()}async execute(e,n,r){let i=this.environment.getWorkspaceRoot(),o=[],s=n?e.filePaths.filter(E=>E===n):e.filePaths,a=await this.runtimeManager.getDuplicates(i,n),c=await a.loadFileContents(i),u=a.clusterBySharedFiles();Ae.log(`[DuplicateManager] Found ${u.length} clusters`);let l=new Set;for(let E of u){let d=Array.from(E.files),f=new Map,T=!0,p=new Map;for(let h of E.groups)for(let C of h.fragments)p.set(C.file,C.file_sha);for(let h of d){let C=this.previousResults.get(h);if(C&&C.length>0){let P=p.get(h);C.some(Y=>Y.file.sha!==P)?(this.previousResults.delete(h),T=!1):f.set(h,C)}else T=!1}if(T&&f.size===d.length){for(let[h,C]of f.entries())r(h,C,C.length,!1),o.push(...C),l.add(h);continue}let S=[];for(let h of E.groups){let C=await this.createMatchForGroup(h,c,i,a,e);if(!C)continue;let P=e.filterMatches([C],[]);P.length!==0&&S.push({match:P[0],group:h})}if(S.length===0)continue;let m=await this.processClusterMatches(S,d,i,r,c,a),O=new Map;for(let h of m){let C=h.file.path;O.has(C)||O.set(C,[]),O.get(C).push(h)}for(let[h,C]of O.entries())this.previousResults.set(h,C),r(h,C,C.length,!1),o.push(...C),l.add(h)}for(let E of s)!l.has(E)&&this.previousResults.has(E)&&(r(E,[],0,!1),this.previousResults.delete(E));return o}async createMatchForGroup(e,n,r,i,o){if(e.fragments.length===0)return null;let s=[...e.fragments].sort((E,d)=>E.start_line-d.start_line),a=s[0];for(let E of s){let d={file:{path:E.file,sha:E.file_sha},text:"",range:{start:{line:E.start_line+1,column:E.start_column+1,index:E.start_index},end:{line:E.start_line+1,column:9999,index:E.start_index}},language:this.detectLanguage(E.file),fingerprint:e.hash,description:"",evidence:[]};if(o.filterMatches([d],[]).length>0){a=E;break}}let c=await i.extractFragmentSnippet(a,r,n),u=await Promise.all(e.fragments.filter(E=>!(E.file===a.file&&E.start_line===a.start_line)).map(async E=>{let d=await i.extractFragmentSnippet(E,r,n);return{file:{path:E.file,sha:E.file_sha},text:d,range:{start:{line:E.start_line+1,column:E.start_column+1,index:E.start_index},end:{line:E.end_line+1,column:E.end_column+1,index:E.end_index}},language:this.detectLanguage(E.file),description:"Duplicate location"}}));return{file:{path:a.file,sha:a.file_sha},text:c,range:{start:{line:a.start_line+1,column:a.start_column+1,index:a.start_index},end:{line:a.start_line+1,column:9999,index:a.start_index+c.split(`
|
|
283
|
+
`)[0].length}},language:this.detectLanguage(a.file),fingerprint:e.hash,description:`Duplicate code found in ${e.fragments.length} locations`,evidence:u}}async processClusterMatches(e,n,r,i,o,s){let a=e.map(T=>T.match),c=[];for(let T of n){let p=this.previousResults.get(T);p&&c.push(...p)}let{remappedMatches:u,unmappedMatches:l}=EJ(a,c),E=u.length+l.length;if(u.length>0){let T=new Map;for(let p of u){let S=p.file.path;T.has(S)||T.set(S,[]),T.get(S).push(p)}for(let[p,S]of T.entries())i(p,S,E,!0);Ae.log(`[DuplicateManager] Emitted ${u.length} remapped duplicates, processing ${l.length} through LLM`)}else l.length>0&&Ae.log(`[DuplicateManager] No remapped duplicates, processing ${l.length} through LLM`);if(l.length===0)return u;let d=e.filter(T=>l.some(p=>p.fingerprint===T.match.fingerprint&&p.file.path===T.match.file.path));Ae.log(`[DuplicateManager] Processing ${d.length} duplicates through LLM validation and fix generation`);let f=await this.processMatchesWithLLM(d,r,o,s);return[...u,...f]}async processMatchesWithLLM(e,n,r,i){let o=e.map(T=>T.match),s=this.config.getContext();if(!s)throw new Error("Context is required for duplicate processing. Please ensure the configuration is initialized with repository information.");Ae.log(`[DuplicateManager] Querying validation cache for ${o.length} duplicates`);let a=await this.apiClient.queryLlmCache({matches:o,type:"duplicate_validate",repository_id:s.repository_id});if("error"in a)return Ae.log(`[DuplicateManager] ERROR: Cache query failed: ${a.error}`),await this.processMatchesWithoutCache(e,n,s,r,i);let c=new Map,u=[];for(let T of a.results){let p=`${T.match.fingerprint}:${T.match.file.path}`;if(T.hit&&T.data)c.set(p,T.data[0]);else{let S=o.find(m=>m.fingerprint===T.match.fingerprint&&m.file.path===T.match.file.path);S&&u.push(S)}}Ae.log(`[DuplicateManager] Validation cache: ${c.size} hits, ${u.length} misses`);let l=[];for(let T of o){let p=`${T.fingerprint}:${T.file.path}`,S=c.get(p);S&&(S.isValid?(l.push(T),Ae.log(`[DuplicateManager] Cached validation for ${T.file.path}:${T.range.start.line}: VALID - ${S.reason}`)):Ae.log(`[DuplicateManager] Cached validation for ${T.file.path}:${T.range.start.line}: INVALID - ${S.reason}`))}for(let T=0;T<u.length;T++){let p=u[T];Ae.log(`[DuplicateManager] [${T+1}/${u.length}] Validating duplicate in ${p.file.path}:${p.range.start.line}`);let S=e.find(h=>h.match.fingerprint===p.fingerprint&&h.match.file.path===p.file.path);if(!S){Ae.log(`[DuplicateManager] ERROR: Could not find group for match ${p.file.path}`);continue}let m=this.extractContextForMatch(S.group,i,r),O=await this.apiClient.validateDuplicates({matches:[p],language:p.language,repository_id:s.repository_id,context:m});if("error"in O){let h=p.text?.substring(0,80).replace(/\n/g," ")||"";Ae.log(`[DuplicateManager] ERROR: Validation failed for ${p.file.path}:${p.range.start.line} "${h}...": ${O.error}`);continue}Ae.log(`[DuplicateManager] [${T+1}/${u.length}] Validation result: ${O.isValid?"VALID":"INVALID"} - ${O.reason}`),O.isValid&&l.push(p)}if(l.length===0)return[];Ae.log(`[DuplicateManager] Querying fix generation cache for ${l.length} duplicates`);let E=await this.apiClient.queryLlmCache({matches:l,type:"duplicate_generate",repository_id:s.repository_id});if("error"in E)return Ae.log(`[DuplicateManager] ERROR: Fix cache query failed: ${E.error}`),await this.generateFixesForMatches(l,n,new Map);let d=new Map,f=[];for(let T of E.results){let p=`${T.match.fingerprint}:${T.match.file.path}`;if(T.hit&&T.data)d.set(p,T.data);else{let S=l.find(m=>m.fingerprint===T.match.fingerprint&&m.file.path===T.match.file.path);S&&f.push(S)}}return Ae.log(`[DuplicateManager] Fix generation cache: ${d.size} hits, ${f.length} misses`),await this.generateFixesForMatches(l,n,d)}async generateFixesForMatches(e,n,r){let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=`${s.fingerprint}:${s.file.path}`,c=r.get(a);if(c){Ae.log(`[DuplicateManager] [${o+1}/${e.length}] Using cached fix for ${s.file.path}:${s.range.start.line}`);let u=await this.replayCachedConversation(c,[s],n);if(u){let l={...s,edits:u.edits,description:u.description};i.push(l),Ae.log(`[DuplicateManager] [${o+1}/${e.length}] Cached fix applied: ${u.description}`)}}else{Ae.log(`[DuplicateManager] [${o+1}/${e.length}] Generating fix for ${s.file.path}:${s.range.start.line}`);let u=await this.generateFixesWithToolLoop([s],n);if(u){let l={...s,edits:u.edits,description:u.description};i.push(l),Ae.log(`[DuplicateManager] [${o+1}/${e.length}] Fix generated successfully: ${u.description}`)}else{let l=s.text?.substring(0,80).replace(/\n/g," ")||"";Ae.log(`[DuplicateManager] ERROR: Fix generation failed for ${s.file.path}:${s.range.start.line} "${l}..."`)}}}return i}async processMatchesWithoutCache(e,n,r,i,o){let s=e.map(c=>c.match),a=[];Ae.log(`[DuplicateManager] Processing ${s.length} duplicates without cache`);for(let c=0;c<e.length;c++){let{match:u,group:l}=e[c],E=this.extractContextForMatch(l,o,i),d=await this.apiClient.validateDuplicates({matches:[u],language:u.language,repository_id:r.repository_id,context:E});"error"in d||d.isValid&&a.push(u)}return await this.generateFixesForMatches(a,n,new Map)}async replayCachedConversation(e,n,r){let i=[];return Ae.log(`[DuplicateManager] Resuming from cached conversation with ${e.length} messages`),await this.continueFixGenerationWithLLM(n,r,e,i)}async continueFixGenerationWithLLM(e,n,r,i){let s=this.config.getContext();if(!s)throw new Error("Context is required for fix generation");for(let a=0;a<20;a++){let c=await this.executeToolCalls(r,n,e[0].file.path,i);if(c.length>0){let f=this.extractReportFixResult(c);if(f)return f;r.push(...c)}Ae.log(`[DuplicateManager] LLM call (resume) - Input: ${r.length} previous messages, Match: ${e[0].file.path}:${e[0].range.start.line}`);let u=await this.apiClient.generateDuplicateFixes({matches:e,language:e[0].language,messages:r,repository_id:s.repository_id,visited_files:i});if("error"in u){let f=e[0]?.text?.substring(0,80).replace(/\n/g," ")||"unknown";Ae.log(`[DuplicateManager] ERROR: generateDuplicateFixes API call failed (resume) for ${e[0]?.file?.path}:${e[0]?.range?.start?.line} "${f}...": ${u.error}`);let T=r.slice(-3);return Ae.log(`[DuplicateManager] Last ${T.length} messages before failure:
|
|
284
284
|
${JSON.stringify(T,null,2)}`),null}let l=u.messages,E=await this.executeToolCalls(l,n,e[0].file.path,i);r.push(...l);let d=this.checkForSuccessfulReportFix(l);if(d)return d;if(E.length>0){let f=this.extractReportFixResult(E);if(f)return f;r.push(...E)}}return Ae.log("[DuplicateManager] Max iterations (20) reached without valid fix"),null}extractReportFixFromMessages(e){for(let n of e)if(n.role==="tool"&&n.content){for(let r of n.content)if(r.toolName==="report_fix"){let i=JSON.parse(r.output.value);if(i.success&&i.result)return i.result}}return null}extractReportFixResult(e){return this.extractReportFixFromMessages(e)}async generateFixesWithToolLoop(e,n){let r=[],o=this.config.getContext(),s=[];if(!o)throw new Error("Context is required for fix generation. Please ensure the configuration is initialized with repository information.");for(let a=0;a<20;a++){Ae.log(`[DuplicateManager] LLM call - Input: ${r.length} previous messages, Match: ${e[0].file.path}:${e[0].range.start.line}`);let c=await this.apiClient.generateDuplicateFixes({matches:e,language:e[0].language,messages:r,repository_id:o.repository_id,visited_files:s});if("error"in c){let f=e[0]?.text?.substring(0,80).replace(/\n/g," ")||"unknown";Ae.log(`[DuplicateManager] ERROR: generateDuplicateFixes API call failed for ${e[0]?.file?.path}:${e[0]?.range?.start?.line} "${f}...": ${c.error}`);let T=r.slice(-3);return Ae.log(`[DuplicateManager] Last ${T.length} messages before failure:
|
|
285
285
|
${JSON.stringify(T,null,2)}`),null}let u=c.messages,l=u.find(f=>f.role==="assistant");if(l){let f=Array.isArray(l.content)?l.content.filter(T=>T.type==="tool-call"):[];if(f.length>0){let T=f.map(p=>p.toolName).join(", ");Ae.log(`[DuplicateManager] LLM response - Tool calls: ${T}`)}else if(l.content){let T=typeof l.content=="string"?l.content.substring(0,100):JSON.stringify(l.content).substring(0,100);Ae.log(`[DuplicateManager] LLM response - Content: ${T}...`)}}let E=await this.executeToolCalls(u,n,e[0].file.path,s);r.push(...u);let d=this.checkForSuccessfulReportFix(u);if(d)return d;if(E.length>0){for(let f of E)if(f.role==="tool"&&f.content)for(let T of f.content){let p=typeof T.output?.value=="string"?T.output.value.substring(0,150):JSON.stringify(T.output?.value||"").substring(0,150);if(Ae.log(`[DuplicateManager] Tool result (${T.toolName}): ${p}${p.length>=150?"...":""}`),T.toolName==="report_fix"){let S=JSON.parse(T.output.value);if(S.success&&S.result)return S.result}}r.push(...E)}}return Ae.log("[DuplicateManager] Max iterations (20) reached without valid fix"),null}checkForSuccessfulReportFix(e){return this.extractReportFixFromMessages(e)}async validateFix(e,n,r){let i=await jc(e,n,r).catch(o=>({error:o.message}));return!i||"error"in i?{valid:!1,error:i?.error||"Failed to compute fix"}:{valid:!0}}async executeToolCalls(e,n,r,i){let o=[];for(let s=0;s<e.length;s++){let a=e[s];if(a.role==="assistant"&&Array.isArray(a.content)){let c=a.content.filter(d=>d.type==="tool-call");if(c.length===0)continue;let u=e[s+1];if(u&&u.role==="tool")continue;let E=await Promise.all(c.map(async d=>{let f=await this.executeTool(d.toolName,d.input,n,r,i);return{type:"tool-result",toolCallId:d.toolCallId,toolName:d.toolName,output:{type:"text",value:typeof f=="string"?f:JSON.stringify(f)}}}));o.push({role:"tool",content:E})}}return o}async executeTool(e,n,r,i,o){let s=[];switch(e){case"read":{let a=await qO(n,r,s);if("error"in a)return a;let c=n.target_file;return o.some(u=>u.path===c)||o.push({path:c,sha:a.sha}),a.content}case"grep":{let a=await JO(n,r,s);if("error"in a)return a;for(let c of a.matches)o.some(u=>u.path===c.file)||o.push({path:c.file,sha:c.sha});return JSON.stringify(a)}case"glob":{let a=await QO(n,r,s);return"error"in a?a:JSON.stringify(a)}case"report_fix":{let a=(n.edits||[]).map(u=>({...u,replaceAll:u.replaceAll??!0}));Ae.log(`[DuplicateManager] LLM proposed fix with ${a.length} edits: ${n.description||"Duplicate code refactored"}`);let c=await this.validateFix(a,i,r);return c.valid?(Ae.log("[DuplicateManager] Fix validation passed"),JSON.stringify({success:!0,result:{edits:a,description:n.description||"Duplicate code refactored"}})):(Ae.log(`[DuplicateManager] Fix validation failed, sending error back to LLM: ${c.error}`),JSON.stringify({success:!1,error:c.error,message:"The fix could not be applied. Please review the error and provide a corrected fix."}))}default:return{error:`Unknown tool: ${e}`}}}extractContextForMatch(e,n,r){return n.extractGroupContext(e,r,20)}detectLanguage(e){switch(e.split(".").pop()?.toLowerCase()){case"ts":return"TypeScript";case"tsx":return"Tsx";case"js":case"jsx":return"JavaScript";case"py":return"Python";default:return"TypeScript"}}};import{spawn as qut}from"child_process";var ZI=class{serverProcess=null;requestId=0;pendingRequests=new Map;workspaceRoot;stderrBuffer=[];constructor(e){this.workspaceRoot=e}initialize(){return new Promise((e,n)=>{let r=this.getRuntimePath();this.serverProcess=qut(r,["server"],{stdio:["pipe","pipe","pipe"]}),this.serverProcess.on("error",o=>{Ae.log(`[Runtime] Spawn error: ${o.message}`),n(new Error(`Failed to spawn runtime server: ${o.message}`))});let i="";this.serverProcess.stdout?.on("data",o=>{i+=o.toString();let s=i.split(`
|
|
286
|
-
`);i=s.pop()||"";for(let a of s)if(a.trim()){let c=a.length>100?a.substring(0,100)+"...":a;Ae.log(`[Runtime stdout] ${c}`);
|
|
286
|
+
`);i=s.pop()||"";for(let a of s)if(a.trim()){let c=a.length>100?a.substring(0,100)+"...":a;Ae.log(`[Runtime stdout] ${c}`);let u=JSON.parse(a);this.handleResponse(u)}}),this.serverProcess.stderr?.on("data",o=>{let s=o.toString();this.stderrBuffer.push(s),this.stderrBuffer.length>100&&this.stderrBuffer.shift(),Ae.log(`[Runtime stderr] ${s}`)}),this.serverProcess.on("exit",o=>{Ae.log(`Runtime server exited with code ${o}`);for(let{reject:s}of this.pendingRequests.values())s(new Error("Runtime server exited"));this.pendingRequests.clear()}),setTimeout(()=>e(),100)})}getRecentStderr(){return this.stderrBuffer.join("")}clearStderr(){this.stderrBuffer=[]}async sendRequest(e,n=6e5){if(!this.serverProcess)throw new Error("Runtime server not initialized or shutting down");let r=String(++this.requestId);this.clearStderr();let i={id:r,...e};return await new Promise((o,s)=>{if(this.pendingRequests.set(r,{resolve:o,reject:s}),!this.serverProcess||!this.serverProcess.stdin){this.pendingRequests.delete(r),s(new Error("Runtime server shut down before request could be sent"));return}this.serverProcess.stdin.write(JSON.stringify(i)+`
|
|
287
287
|
`),setTimeout(()=>{if(this.pendingRequests.has(r)){this.pendingRequests.delete(r);let a=this.getRecentStderr(),c=a?`Request timed out. Runtime logs:
|
|
288
288
|
${a}`:"Request timed out";s(new Error(c))}},n)})}async shutdown(){if(!this.serverProcess)return;let e=new Error().stack;Ae.log(`[RuntimeProvider] shutdown() called from:
|
|
289
289
|
${e}`);let r={id:String(++this.requestId),command:"shutdown"};this.serverProcess.stdin.write(JSON.stringify(r)+`
|
|
@@ -291,7 +291,7 @@ ${e}`);let r={id:String(++this.requestId),command:"shutdown"};this.serverProcess
|
|
|
291
291
|
${u}`:r.message;c(new Error(l))}else a(r);else if(i)if(i==="success")a(o);else{let u=this.getRecentStderr(),l=u?`${s||"Request failed"}. Runtime logs:
|
|
292
292
|
${u}`:s||"Request failed";c(new Error(l))}else Ae.log("[Runtime] Unknown response format"),c(new Error("Unknown response format"))}getRuntimePath(){let e=globalThis.__POWERLINT_ASSETS__;if(!e?.runtime)throw new Error("Runtime binary not found. This should be set by the Bun executable build. Make sure you're running the compiled Bun executable, not the source code directly.");return Ae.log(`[RuntimeProvider] Using runtime from Bun executable: ${e.runtime}`),e.runtime}};import{homedir as Jut}from"os";import{join as Qut}from"path";import{promises as IF}from"fs";import*as XI from"path";var im=class{groups;constructor(e){this.groups=e}patternCount(){return this.groups.length}patternCost(){return this.groups.reduce((e,n)=>e+n.cost*n.fragments.length,0)}patternDensity(){let e=this.patternCount();return e>0?this.patternCost()/e:0}fragmentOccurrences(e){let n=this.groups.find(r=>r.hash===e);return n?n.fragments.length:0}patternHash(e){return this.groups[e]?.hash}fileCount(){let e=new Set;for(let n of this.groups)for(let r of n.fragments)e.add(r.file);return e.size}title(e){let n=this.groups.find(o=>o.hash===e);if(!n||n.fragments.length===0)return"Unknown pattern";let r=n.fragments[0];return`${r.file.split("/").pop()||r.file}:${r.start_line+1}-${r.end_line+1} (${n.fragments.length} occurrences)`}fragmentsByFile(e){let n=new Map,r=this.groups.find(i=>i.hash===e);if(!r)return n;for(let i of r.fragments){let o=n.get(i.file)||[];o.push(i),n.set(i.file,o)}return n}getGroups(){return this.groups}async getFragmentText(e,n){let r=XI.join(n,e.file),i=await IF.readFile(r,"utf-8");return Buffer.from(i,"utf-8").slice(e.start_index,e.end_index).toString("utf-8")}getFragmentsInFile(e){let n=[];for(let r of this.groups)for(let i of r.fragments)i.file===e&&n.push(i);return n}getStatistics(){let e=this.groups.reduce((n,r)=>n+r.fragments.length,0);return{patternCount:this.patternCount(),totalCost:this.patternCost(),averageCost:this.patternDensity(),fileCount:this.fileCount(),totalFragments:e}}async extractFragmentSnippet(e,n,r){let i;if(r.has(e.file))i=r.get(e.file);else{let s=XI.join(n,e.file);i=await IF.readFile(s,"utf-8"),r.set(e.file,i)}return Buffer.from(i,"utf-8").slice(e.start_index,e.end_index).toString("utf-8")}async loadFileContents(e){let n=new Map,r=new Set;for(let i of this.groups)for(let o of i.fragments)r.add(o.file);return await Promise.all(Array.from(r).map(async i=>{let o=XI.join(e,i),s=await IF.readFile(o,"utf-8");n.set(i,s)})),n}extractFragmentContext(e,n,r=20){let i=n.get(e.file);if(!i)throw new Error(`File content not available for ${e.file}`);let o=i.split(`
|
|
293
293
|
`),s=e.start_line,a=Math.max(0,s-r),c=Math.min(o.length-1,s+r),u=o.slice(a,c+1).join(`
|
|
294
|
-
`);return{file:e.file,range:{start:{line:a+1,column:1},end:{line:c+1,column:o[c]?.length||1}},text:u}}extractGroupContext(e,n,r=20){return e.fragments.map(i=>this.extractFragmentContext(i,n,r))}clusterBySharedFiles(){if(this.groups.length===0)return[];let e=new Map;this.groups.forEach((o,s)=>{let a=new Set;for(let c of o.fragments)a.add(c.file);for(let c of a)e.has(c)||e.set(c,[]),e.get(c).push(s)});let n=new MF(this.groups.length);for(let o of e.values())for(let s=1;s<o.length;s++)n.union(o[0],o[s]);let r=new Map;for(let o=0;o<this.groups.length;o++){let s=n.find(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}let i=[];for(let o of r.values()){let s=o.map(c=>this.groups[c]),a=new Set;for(let c of s)for(let u of c.fragments)a.add(u.file);i.push({groups:s,files:a})}return i}},MF=class{parent=new Map;rank=new Map;constructor(e){for(let n=0;n<e;n++)this.parent.set(n,n),this.rank.set(n,0)}find(e){return this.parent.get(e)!==e&&this.parent.set(e,this.find(this.parent.get(e))),this.parent.get(e)}union(e,n){let r=this.find(e),i=this.find(n);if(r===i)return;let o=this.rank.get(r),s=this.rank.get(i);o<s?this.parent.set(r,i):o>s?this.parent.set(i,r):(this.parent.set(i,r),this.rank.set(r,o+1))}};var qI=class t{static INDEX_FOLDER=Qut(Jut(),".wispbit","indexes");provider;initialized=!1;constructor(e){this.provider=e}async initializeProvider(){this.initialized||(await this.provider.initialize(),this.initialized=!0)}async initialize(e){await this.initializeProvider();let n=await this.provider.sendRequest({command:"initialize_workspaces",workspace_configs:e.workspaceConfigs.map(r=>({workspace_root:r.workspaceRoot,base_commit_sha:r.baseCommitSha})),index_folder:t.INDEX_FOLDER,ignores:e.ignores});if("error"in n&&n.error)throw new Error(`Failed to initialize workspaces: ${n.error}`);return{fullScan:n.full_scan||!1}}async getDuplicates(e,n){await this.initializeProvider();let r=await this.provider.sendRequest({command:"get_duplicates",workspace_root:e,file_path:n});if("error"in r&&r.error)throw new Error(`Failed to get duplicates: ${r.error}`);let i=r;return new im(i)}async getDuplicatesForFile(e,n){await this.initializeProvider();let r=await this.provider.sendRequest({command:"get_duplicates",workspace_root:e,file_path:n});if("error"in r&&r.error)throw new Error(`Failed to get duplicates for file: ${r.error}`);let i=r;return new im(i)}invalidationQueue=Promise.resolve();async invalidateFiles(e,n){let r=this.invalidationQueue.then(async()=>{await this.initializeProvider();let i=Date.now(),o=await this.provider.sendRequest({command:"invalidate_files",workspace_root:e,files:n.map(a=>({file_path:a.filePath,content_sha:a.contentSha}))}),s=Date.now()-i;if(Ae.log(`[RuntimeManager] Invalidated ${n.length} file(s) in ${s}ms for ${e}`),"error"in o&&o.error)throw new Error(`Failed to invalidate files: ${o.error}`)}).catch(i=>{throw Ae.log(`[RuntimeManager] Invalidation failed: ${i.message}`),i});this.invalidationQueue=r.catch(()=>{}),await r}isInitialized(){return this.initialized}async shutdown(){this.initialized&&(Ae.log("[RuntimeManager] Shutdown requested, waiting for in-flight operations..."),await this.invalidationQueue.catch(()=>{}),Ae.log("[RuntimeManager] All operations complete, shutting down runtime..."),await this.provider.shutdown(),this.initialized=!1)}};var JI=class{contexts=new Map;workspacePath;apiKey;lspClient;sharedRuntimeManager=null;RULES_CACHE_TTL_MS=300*1e3;constructor(e){this.workspacePath=e.workspacePath,this.apiKey=e.apiKey,this.lspClient=e.lspClient}async discoverAndInitialize(e,n){let r=await tO(this.workspacePath),i=[];for(let s of r){let a=await this.initializeContext(s).catch(c=>(n?.(s,c),null));if(a){let{baseCommitSha:c}=await ga(s);i.push({repoRoot:s,context:a,baseCommitSha:c}),this.contexts.set(s,a),e?.(s,a)}}let o=[];for(let{repoRoot:s,context:a,baseCommitSha:c}of i)a.config.getEnableDeduplicator()&&o.push({workspaceRoot:s,baseCommitSha:c});if(o.length>0){let s=new ZI(o[0].workspaceRoot);this.sharedRuntimeManager=new qI(s);for(let{context:a}of i)a.config.getEnableDeduplicator()&&(a.runtimeManager=this.sharedRuntimeManager,a.duplicateManager=new zI(this.sharedRuntimeManager,a.config,a.environment))}}async initializeContext(e){let n=new Kr({workspaceRoot:e}),r=await Yo.initialize(n,{apiKey:this.apiKey,lspClient:this.lspClient});if("failed"in r)throw new Error(`Config initialization failed for ${e}: ${r.error}`);let i=r,o=new $o(i,n),s=new zr,a=new La(i,n,s);return{repoRoot:e,environment:n,config:i,ruleProvider:o,eventEmitter:s,ruleExecutor:a,cachedRules:null,rulesById:new Map,rulesCacheTimestamp:0,rulesLoadingPromise:null,lastCommitSelector:null,currentExecutionRules:[],completedRulesCount:0,isExecuting:!1,currentExecutionPromise:null,runtimeManager:null,duplicateManager:null,executionContext:null}}findContextForFile(e){let n=e.toLowerCase();return Array.from(this.contexts.entries()).filter(([i])=>{let o=i.toLowerCase();return n.startsWith(o+elt)||n===o}).sort((i,o)=>o[0].length-i[0].length)[0]?.[1]||null}getAllContexts(){return Array.from(this.contexts.values())}getRepoCount(){return this.contexts.size}hasRepositories(){return this.contexts.size>0}getContext(e){return this.contexts.get(e)}async initializeRuntimeManager(){if(!this.sharedRuntimeManager)return!1;let e=[],n=[];for(let r of this.contexts.values())if(r.config.getEnableDeduplicator()){let{baseCommitSha:i}=await ga(r.repoRoot);e.push({workspaceRoot:r.repoRoot,baseCommitSha:i}),n.length===0&&(n=r.config.getIgnoredGlobs())}return e.length===0?!1:(await this.sharedRuntimeManager.initialize({workspaceConfigs:e,ignores:n}),!0)}async shutdown(){for(let e of this.contexts.values())e.ruleExecutor.clearCache(),e.duplicateManager&&e.duplicateManager.clearCache();this.sharedRuntimeManager&&(await this.sharedRuntimeManager.shutdown(),this.sharedRuntimeManager=null),this.contexts.clear()}};function dre(t,e,n){if(t.fingerprint)return`${e}:${t.fingerprint}`;let r=t.text?.slice(0,100)||"",i=`${t.range.start.line}:${t.range.start.column}-${t.range.end.line}:${t.range.end.column}`;return`${e}:${n}:${i}:${nlt(r)}`}function nlt(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return e.toString(36)}function fre(t){return t.end.line-t.start.line+1>20?{start:{line:t.start.line-1,character:t.start.column-1},end:{line:t.start.line-1,character:Number.MAX_SAFE_INTEGER}}:{start:{line:t.start.line-1,character:t.start.column-1},end:{line:t.end.line-1,character:t.end.column-1}}}var PF=class{connection;documentManager;repositoryContextManager;workspacePath;apiKey;lspClient;batchProgressReporter=null;batchProgressToken="wispbit-batch-lint";progressTokenCreated=!1;fixQueue=[];isProcessingFix=!1;branchCheckTimer=null;BRANCH_CHECK_DEBOUNCE_MS=1e3;branchCheckInterval=null;BRANCH_CHECK_INTERVAL_MS=3e4;executionDebounceTimer=null;EXECUTION_DEBOUNCE_MS=1e3;changedFiles=new Set;hasRunInitialCheck=!1;isExecutingInitial=!1;dismissalsLoadingPromises=new Map;fixesLoadingPromises=new Map;localDismissals=[];constructor(e){this.workspacePath=e.workspacePath,this.apiKey=e.apiKey,this.lspClient=e.lspClient,this.connection=(0,_r.createConnection)(_r.ProposedFeatures.all,process.stdin,process.stdout),this.documentManager=new KI,this.repositoryContextManager=new JI({workspacePath:this.workspacePath,apiKey:this.apiKey,lspClient:this.lspClient}),this.registerHandlers()}addLocalDismissal(e){this.localDismissals.push(e)}isLocallyDismissed(e,n,r,i,o){return this.localDismissals.some(s=>s.matchId===o&&s.uri===e?!0:s.uri===e&&s.ruleId===n?s.startLine<=i&&s.endLine>=r:!1)}clearLocalDismissalsForUri(e){this.localDismissals=this.localDismissals.filter(n=>n.uri!==e)}clearAllLocalDismissals(){this.localDismissals=[]}findContextForFile(e){let n=Jo(e);return this.repositoryContextManager.findContextForFile(n)}pathToNormalizedUri(e){let n=tlt(e).toString();return decodeURIComponent(n)}getDiagnosticsForUri(e){let n=this.documentManager.getDiagnostics(e);if(n.length===0){let r=qr(e),i=this.documentManager.getAllDiagnosticUris();for(let o of i)if(qr(o)===r){n=this.documentManager.getDiagnostics(o);break}}return n}handleRuleComplete(e,n,r){if(!e.isExecuting||e.currentExecutionRules.length===0)return;e.completedRulesCount++;let i=Math.round(e.completedRulesCount/e.currentExecutionRules.length*100);this.updateBatchProgress(i,n)}async handleRuleFileComplete(e,n,r,i){if(!e.isExecuting||e.currentExecutionRules.length===0)return;let o=e.currentExecutionRules.find(u=>u.id===n);if(!o){this.connection.console.log(`[${e.repoRoot}] Warning: Rule ${n} not found in current execution`);return}let s=u_(e.repoRoot,r),a=this.pathToNormalizedUri(s);if(i.length===0){this.updateDiagnosticsForRule(a,o.internalId,[]);return}let c=await this.createDiagnosticsForFile(e,r,o.internalId,i,e.currentExecutionRules);this.updateDiagnosticsForRule(a,o.internalId,c)}async handleRuleFilePartial(e,n,r,i,o){if(!e.isExecuting||e.currentExecutionRules.length===0)return;let s=e.currentExecutionRules.find(l=>l.internalId===n);if(!s){this.connection.console.log(`[${e.repoRoot}] Warning: Rule ${n} not found in current execution`);return}let a=u_(e.repoRoot,r),c=this.pathToNormalizedUri(a);if(i.length===0){this.updateDiagnosticsForRule(c,s.internalId,[]);return}let u=await this.createDiagnosticsForFile(e,r,s.internalId,i,e.currentExecutionRules);this.updateDiagnosticsForRule(c,s.internalId,u)}async convertDuplicateResultsToDiagnostics(e,n,r,i){let o=[];for(let s of n)for(let a of s.matches){let c=dre(a,"DUPLICATE",i);if(this.isLocallyDismissed(i,"DUPLICATE",a.range.start.line,a.range.end.line,c))continue;let u=fre(a.range),l=a.evidence?.map(f=>{let T=u_(e.repoRoot,f.file.path);return{location:{uri:this.pathToNormalizedUri(T),range:{start:{line:f.range.start.line-1,character:f.range.start.column-1},end:{line:f.range.end.line-1,character:f.range.end.column-1}}},message:"Duplicate location"}}),E=null;a.edits&&a.edits.length>0&&(E=await this.computeFixForMatch(a,e).catch(f=>(this.connection.console.log(`Warning: Failed to compute fix for duplicate: ${f}`),null)));let d={range:u,severity:_r.DiagnosticSeverity.Warning,message:a.description||"Duplicate code detected",code:"DUPLICATE",source:"wispbit",relatedInformation:l,data:{uri:i,match:a,matchId:c,fix:E?{diff:E.diff,diffs:E.diffs,autofix:!1}:null,ruleId:"DUPLICATE",filePath:a.file.path,rule:{id:"DUPLICATE",displayId:"DUPLICATE",summary:null}}};o.push(d)}return o}async handleDuplicateFileComplete(e,n,r,i,o){let s=u_(e.repoRoot,n),a=this.pathToNormalizedUri(s),c=await this.createDiagnosticsForFile(e,n,"DUPLICATE",r,[],this.convertDuplicateResultsToDiagnostics.bind(this));this.updateDiagnosticsForRule(a,"DUPLICATE",c)}setupProgressListenersForContext(e){e.eventEmitter.on("rules:progress",n=>{this.updateBatchProgress(n.percentage,n.ruleId)}),e.eventEmitter.on("rules:rule-complete",n=>{this.handleRuleComplete(e,n.ruleId,n.matches)}),e.eventEmitter.on("rules:rule-file-complete",async n=>{await this.handleRuleFileComplete(e,n.ruleId,n.filePath,n.matches)}),e.eventEmitter.on("rules:rule-file-partial",async n=>{await this.handleRuleFilePartial(e,n.ruleId,n.filePath,n.matches,n.totalMatches)})}toRelativePath(e,n){if(!n){let r=this.pathToNormalizedUri(e);n=this.findContextForFile(r)||void 0}return n?Ere(n.repoRoot,e):Ere(this.workspacePath,e)}updateDiagnosticsForRule(e,n,r){this.documentManager.setDiagnosticsForRule(e,n,r);let i=this.documentManager.getDiagnostics(e);this.connection.sendDiagnostics({uri:e,diagnostics:i})}removeDiagnosticByMatchId(e,n){let r=this.documentManager.getDiagnostics(e),i=r.find(a=>a.data?.matchId===n);if(!i)return;let o=i.data?.rule?.id;if(!o)return;let s=r.filter(a=>a.data?.rule?.id===o&&a.data?.matchId!==n);this.updateDiagnosticsForRule(e,o,s)}clearAllDiagnostics(){let e=this.documentManager.getAllDiagnosticUris();for(let n of e)this.clearDiagnosticsForFile(n);this.clearAllLocalDismissals()}clearDiagnosticsForFile(e){this.documentManager.clearDiagnostics(e),this.clearLocalDismissalsForUri(e),this.connection.sendDiagnostics({uri:e,diagnostics:[]})}handleDocumentChangesWithRanges(e,n){let r=this.documentManager.getDiagnostics(e);if(r.length===0)return;this.connection.console.log(`Document changed: ${e}, ${n.length} change(s), ${r.length} diagnostic(s)`);let i=new Set;for(let o of n){if(!o.range){this.connection.console.log("Full document change detected - removing all diagnostics");for(let s of r)s.data?.matchId&&i.add(s.data.matchId);continue}for(let s of r)this.rangesOverlap(o.range,s.range)&&s.data?.matchId&&i.add(s.data.matchId)}for(let o of i)this.removeDiagnosticByMatchId(e,o);i.size>0&&this.connection.console.log(`Removed ${i.size} diagnostic(s) due to document edits`)}rangesOverlap(e,n){return e.end.line<n.start.line||e.start.line>n.end.line?!1:e.start.line<=n.end.line&&e.end.line>=n.start.line}async createDiagnosticsForFile(e,n,r,i,o,s){let a=i.length;this.documentManager.hasDismissals(n)||await this.loadDismissalsForFile(e,n),this.documentManager.hasFixes(n)||await this.loadFixesForFile(e,n);let c={ruleId:r,matches:i},u=this.filterDismissedResults([c],n),l=u[0]?.matches.length||0,E=a-l,d=await this.filterFixedResults(e,u,n),f=d[0]?.matches.length||0,T=l-f,p=u_(e.repoRoot,n),S=this.pathToNormalizedUri(p),m=await(s||this.convertResultsToDiagnostics.bind(this))(e,d,o,S);if(a>0){let h=o.find(P=>P.internalId===r)?.id||r,C=[];E>0&&C.push(`${E} dismissed`),T>0&&C.push(`${T} fixed`),C.length>0?this.connection.console.log(`[${e.repoRoot}] ${n}: ${m.length} diagnostic(s) created, ${C.join(", ")} (rule: ${h})`):this.connection.console.log(`[${e.repoRoot}] ${n}: ${m.length} diagnostic(s) created (rule: ${h})`)}return m}async getFileContent(e){let n=this.pathToNormalizedUri(e),r=this.documentManager.getDocument(n);return r?r.getText():await _re.readFile(e,"utf-8").catch(()=>null)}async computeFixForMatch(e,n){if(!e.edits||e.edits.length===0)return null;let r=await jc(e.edits,e.file.path,n.repoRoot,o=>this.getFileContent(o));return r?{fileChanges:r.fileChanges.map(o=>({...o,fileUri:this.pathToNormalizedUri(o.filePath)})),diff:r.diff,diffs:r.diffs}:null}async loadRulesWithCache(e){let r=Date.now()-e.rulesCacheTimestamp;return e.cachedRules&&r<this.repositoryContextManager.RULES_CACHE_TTL_MS?(this.connection.console.log(`[${e.repoRoot}] Using cached rules (age: ${Math.round(r/1e3)}s / ${this.repositoryContextManager.RULES_CACHE_TTL_MS/1e3}s)`),e.cachedRules):e.rulesLoadingPromise?(this.connection.console.log(`[${e.repoRoot}] Rules are already being loaded, waiting for existing request...`),e.rulesLoadingPromise):(this.connection.console.log(`[${e.repoRoot}] Loading fresh rules from API...`),e.rulesLoadingPromise=e.ruleProvider.loadAllRules().then(i=>{let o=i.filter(s=>s.execution==="llm");e.cachedRules=o,e.rulesCacheTimestamp=Date.now(),e.rulesById.clear();for(let s of o)e.rulesById.set(s.id,s);if(this.connection.console.log(`[${e.repoRoot}] Loaded ${o.length} rules (cache valid for ${this.repositoryContextManager.RULES_CACHE_TTL_MS/1e3}s)`),o.length>0){this.connection.console.log(`[${e.repoRoot}] Fetched rules:`);for(let s of o){let a=s.autofix||!1,c="";a&&(c=" (autofix)"),this.connection.console.log(`[${e.repoRoot}] - ${s.id}: ${s.message}${c}`)}}return o}).finally(()=>{e.rulesLoadingPromise=null}),await e.rulesLoadingPromise)}async loadDismissalsForFile(e,n){if(this.documentManager.hasDismissals(n))return;let r=this.dismissalsLoadingPromises.get(n);if(r)return await r;let i=(async()=>{let s=(await e.ruleProvider.getDismissals([n])).map(a=>({ruleId:a.ruleId,file:a.match.file.path,startLine:a.match.range.start.line,endLine:a.match.range.end.line,fingerprint:a.match.fingerprint,dismissedAt:a.createdAt,dismissalId:a.dismissalId}));this.documentManager.setDismissals(n,s)})().finally(()=>{this.dismissalsLoadingPromises.delete(n)});return this.dismissalsLoadingPromises.set(n,i),await i}async loadFixesForFile(e,n){if(this.documentManager.hasFixes(n))return;let r=this.fixesLoadingPromises.get(n);if(r)return await r;let i=(async()=>{let o=await e.ruleProvider.getFixes([n]);this.documentManager.setFixes(n,o)})().finally(()=>{this.fixesLoadingPromises.delete(n)});return this.fixesLoadingPromises.set(n,i),await i}filterDismissedResults(e,n){let r=this.documentManager.getDismissals(n);return r.length===0?e:e.map(i=>{let o=r.filter(u=>u.ruleId===i.ruleId);if(o.length===0)return i;let s=i.matches.map(u=>({file:n,startLine:u.range.start.line,endLine:u.range.end.line,fingerprint:u.fingerprint})),c=gh(s,o).map(u=>i.matches.find(l=>l.range.start.line===u.startLine&&l.range.end.line===u.endLine&&l.fingerprint===u.fingerprint));return{...i,matches:c}})}async filterFixedResults(e,n,r){let i=this.documentManager.getFixes(r);if(i.length===0)return n;this.connection.console.log(`[${e.repoRoot}] Filtering fixes for ${r}: ${i.length} fix(es) loaded`);let o=u_(e.repoRoot,r),s=await this.getFileContent(o);return s===null?n:n.map(a=>{let c=i.filter(S=>S.ruleId===a.ruleId);if(c.length===0)return a;let u=new Set;for(let S of c)S.match?.edits?.some(O=>O.oldString&&m1(s,O.oldString))&&S.match.fingerprint&&u.add(S.match.fingerprint);let l=c.length-u.size;u.size>0&&this.connection.console.log(`[${e.repoRoot}] ${r}: ${u.size} fix(es) reverted, ${l} still active`);let E=a.matches.map(S=>({file:r,startLine:S.range.start.line,endLine:S.range.end.line,fingerprint:S.fingerprint})),d=c.filter(S=>!S.match.fingerprint||!u.has(S.match.fingerprint)).map(S=>({file:r,startLine:S.match.range.start.line,endLine:S.match.range.end.line,fingerprint:S.match.fingerprint})),T=gh(E,d).map(S=>a.matches.find(m=>m.range.start.line===S.startLine&&m.range.end.line===S.endLine&&m.fingerprint===S.fingerprint)),p=a.matches.length-T.length;return p>0&&this.connection.console.log(`[${e.repoRoot}] ${r}: Filtered out ${p} match(es) with active fixes`),{...a,matches:T}})}async convertResultsToDiagnostics(e,n,r,i){let o=[],s=new Set;for(let a of n){let c=r.find(u=>u.internalId===a.ruleId);if(!c){this.connection.console.log(`Warning: Could not find rule with internal ID ${a.ruleId}`);continue}for(let u of a.matches){let l=`${u.range.start.line}-${u.range.end.line}`;if(s.has(l))continue;s.add(l);let E=dre(u,c.internalId,i);if(this.isLocallyDismissed(i,c.internalId,u.range.start.line,u.range.end.line,E))continue;let d=null;u.edits&&u.edits.length>0&&(d=await this.computeFixForMatch(u,e).catch(p=>(this.connection.console.log(`Warning: Failed to compute fix for match: ${p}`),null)));let T={range:fre(u.range),severity:_r.DiagnosticSeverity.Warning,message:u.description||c.message,code:c.id,codeDescription:{href:`https://app.wispbit.com/rules/${c.internalId}`},source:"wispbit",data:{uri:i,match:u,matchId:E,fix:d?{diff:d.diff,diffs:d.diffs,autofix:c.autofix||!1}:null,rule:{id:c.internalId,displayId:c.id,summary:c.summary||null}}};o.push(T)}}return o}triggerExecution(){this.executionDebounceTimer&&(clearTimeout(this.executionDebounceTimer),this.executionDebounceTimer=null),this.executionDebounceTimer=setTimeout(()=>{this.executionDebounceTimer=null,this.executeQueuedFiles()},this.EXECUTION_DEBOUNCE_MS)}lintDocument(e){if(!this.documentManager.getDocument(e)){this.connection.console.log(`Document not found: ${e}`);return}let r=Jo(e),i=this.toRelativePath(r);this.connection.console.log(`File changed: ${i}`),this.changedFiles.add(e),this.triggerExecution()}async executeQueuedFiles(){let e=this.repositoryContextManager.getAllContexts();if(e.length===0){this.connection.console.log("No repositories found, skipping execution");return}if(!this.hasRunInitialCheck){if(this.isExecutingInitial){this.connection.console.log("Initial check already in progress, files will be queued for next run");return}this.changedFiles.clear(),this.isExecutingInitial=!0;try{await this.repositoryContextManager.initializeRuntimeManager()&&this.connection.console.log("RuntimeManager initialized successfully"),this.hasRunInitialCheck=!0,this.cleanupProgress(),await this.startBatchProgress(0);try{for(let i of e)await this.executeForContext(i,null);this.cleanupProgress()}catch(i){this.connection.console.error(`Error executing rules: ${i.message}`),this.connection.console.error(i.stack),this.cleanupProgress()}}finally{this.isExecutingInitial=!1}}else{let r=Array.from(this.changedFiles);if(this.changedFiles.clear(),r.length===0){this.connection.console.log("No files to check, skipping incremental execution");return}this.connection.console.log(`Incremental check for ${r.length} file(s)`),await this.startBatchProgress(0);try{for(let i of e)await this.executeForContext(i,r);this.cleanupProgress()}catch(i){this.connection.console.error(`Error executing rules: ${i.message}`),this.connection.console.error(i.stack),this.cleanupProgress()}}}async executeForContext(e,n){e.isExecuting=!0;try{let r=await this.loadRulesWithCache(e);e.completedRulesCount=0,e.currentExecutionRules=r;let{commitSelector:i,include:o}=await ga(e.repoRoot);e.lastCommitSelector=i;let s=await Pa.initialize(e.config,e.environment,"diff",e.eventEmitter,void 0,{include:o,commitSelector:i,skipPreExistingViolations:!0});if(e.executionContext=s,e.runtimeManager){let a=[];if(n!==null&&n.length>0?a=n.filter(c=>this.findContextForFile(c)?.repoRoot===e.repoRoot).map(c=>({filePath:this.toRelativePath(Jo(c),e)})):a=s.filePaths.map(c=>({filePath:c})),a.length>0){this.connection.console.log(`[${e.repoRoot}] Starting invalidation of ${a.length} file(s) in RuntimeManager...`);let c=Date.now();await e.runtimeManager.invalidateFiles(e.repoRoot,a);let u=Date.now()-c;this.connection.console.log(`[${e.repoRoot}] Completed invalidation in ${u}ms`)}}if(n!==null&&n.length>0){let a=n.filter(c=>this.findContextForFile(c)?.repoRoot===e.repoRoot);if(a.length===0){this.connection.console.log(`[${e.repoRoot}] No changed files in this repository, skipping`);return}for(let c of a){let u=this.toRelativePath(Jo(c),e);this.connection.console.log(`[${e.repoRoot}] Executing rules for ${u}`),e.completedRulesCount=0;let l=e.ruleExecutor.execute(r,s,{relativePath:u}),E=e.duplicateManager?e.duplicateManager.execute(s,u,(d,f,T,p)=>{this.handleDuplicateFileComplete(e,d,f,T,p)}):Promise.resolve();await Promise.all([l,E])}}else{let a=e.ruleExecutor.execute(r,s),c=e.duplicateManager?(async()=>{let u=e.duplicateManager;this.connection.console.log(`[${e.repoRoot}] Starting duplicate detection...`);let l=Date.now();await u.execute(s,void 0,(d,f,T,p)=>{this.handleDuplicateFileComplete(e,d,f,T,p)});let E=Date.now()-l;this.connection.console.log(`[${e.repoRoot}] Completed duplicate detection in ${E}ms`)})():Promise.resolve();await Promise.all([a,c])}}catch(r){this.connection.console.error(`[${e.repoRoot}] Error executing rules: ${r.message}`),this.connection.console.error(r.stack)}finally{e.isExecuting=!1}}async startBatchProgress(e){if(this.batchProgressReporter)this.batchProgressReporter.report(e,"Checking workspace");else try{this.progressTokenCreated||(await this.connection.sendRequest("window/workDoneProgress/create",{token:this.batchProgressToken}),this.progressTokenCreated=!0),this.batchProgressReporter=await this.connection.window.createWorkDoneProgress(),this.batchProgressReporter.begin("wispbit",e,"Checking workspace",!1)}catch(n){this.connection.console.log(`Failed to create batch progress: ${n}`)}}cleanupProgress(){this.batchProgressReporter&&(this.batchProgressReporter.done(),this.batchProgressReporter=null)}updateBatchProgress(e,n){if(!this.batchProgressReporter)return;let r=`Checking workspace (${n})`;this.batchProgressReporter.report(e,r)}async processFixQueue(){if(!this.isProcessingFix){for(this.isProcessingFix=!0;this.fixQueue.length>0;){let e=this.fixQueue.shift();e&&await e()}this.isProcessingFix=!1}}handleQuickfix(e){let{uri:n,matchId:r}=e[0];this.fixQueue.push(async()=>{await this.applyQuickfix(n,r)}),this.processFixQueue()}async applyQuickfix(e,n){let i=this.getDiagnosticsForUri(e).find(T=>T.data?.matchId===n);if(!i){this.connection.window.showErrorMessage("Could not apply fix"),this.connection.console.error(`Diagnostic not found for matchId: ${n}`);return}let o=i.data?.match,s=i.data?.rule;if(!o?.edits||o.edits.length===0){this.connection.window.showErrorMessage("No fix available"),this.connection.console.error(`No fix available for matchId ${n}, rule ${s?.id}`);return}let a=this.findContextForFile(e);if(!a){this.connection.window.showErrorMessage("File is not in any repository"),this.connection.console.error(`No repository context found for ${e}`);return}let c=Jo(e),u=this.toRelativePath(c,a);this.connection.console.log(`[${a.repoRoot}] Applying fix for matchId ${n}, rule ${s?.id}`);let l=await this.computeFixForMatch(o,a);if(!l){this.connection.window.showErrorMessage("Failed to compute fix"),this.connection.console.error(`[${a.repoRoot}] Failed to compute fix for matchId ${n}, rule ${s?.id}`);return}let E=Jo(e),d=[];for(let T of l.fileChanges){let S=T.filePath===E?e:T.fileUri,m=this.documentManager.getDocument(S),O=m?m.lineCount:T.oldContent.split(`
|
|
294
|
+
`);return{file:e.file,range:{start:{line:a+1,column:1},end:{line:c+1,column:o[c]?.length||1}},text:u}}extractGroupContext(e,n,r=20){return e.fragments.map(i=>this.extractFragmentContext(i,n,r))}clusterBySharedFiles(){if(this.groups.length===0)return[];let e=new Map;this.groups.forEach((o,s)=>{let a=new Set;for(let c of o.fragments)a.add(c.file);for(let c of a)e.has(c)||e.set(c,[]),e.get(c).push(s)});let n=new MF(this.groups.length);for(let o of e.values())for(let s=1;s<o.length;s++)n.union(o[0],o[s]);let r=new Map;for(let o=0;o<this.groups.length;o++){let s=n.find(o);r.has(s)||r.set(s,[]),r.get(s).push(o)}let i=[];for(let o of r.values()){let s=o.map(c=>this.groups[c]),a=new Set;for(let c of s)for(let u of c.fragments)a.add(u.file);i.push({groups:s,files:a})}return i}},MF=class{parent=new Map;rank=new Map;constructor(e){for(let n=0;n<e;n++)this.parent.set(n,n),this.rank.set(n,0)}find(e){return this.parent.get(e)!==e&&this.parent.set(e,this.find(this.parent.get(e))),this.parent.get(e)}union(e,n){let r=this.find(e),i=this.find(n);if(r===i)return;let o=this.rank.get(r),s=this.rank.get(i);o<s?this.parent.set(r,i):o>s?this.parent.set(i,r):(this.parent.set(i,r),this.rank.set(r,o+1))}};var qI=class t{static INDEX_FOLDER=Qut(Jut(),".wispbit","indexes");provider;initialized=!1;constructor(e){this.provider=e}async initializeProvider(){this.initialized||(await this.provider.initialize(),this.initialized=!0)}async initialize(e){await this.initializeProvider();let n=await this.provider.sendRequest({command:"initialize_workspaces",workspace_configs:e.workspaceConfigs.map(r=>({workspace_root:r.workspaceRoot,base_commit_sha:r.baseCommitSha})),index_folder:t.INDEX_FOLDER,ignores:e.ignores});if("error"in n&&n.error)throw new Error(`Failed to initialize workspaces: ${n.error}`);return{fullScan:n.full_scan||!1}}async getDuplicates(e,n){await this.initializeProvider();let r=await this.provider.sendRequest({command:"get_duplicates",workspace_root:e,file_path:n});if("error"in r&&r.error)throw new Error(`Failed to get duplicates: ${r.error}`);let i=r;return new im(i)}async getDuplicatesForFile(e,n){await this.initializeProvider();let r=await this.provider.sendRequest({command:"get_duplicates",workspace_root:e,file_path:n});if("error"in r&&r.error)throw new Error(`Failed to get duplicates for file: ${r.error}`);let i=r;return new im(i)}invalidationQueue=Promise.resolve();async invalidateFiles(e,n){let r=this.invalidationQueue.then(async()=>{await this.initializeProvider();let i=Date.now(),o=await this.provider.sendRequest({command:"invalidate_files",workspace_root:e,files:n.map(a=>({file_path:a.filePath,content_sha:a.contentSha}))}),s=Date.now()-i;if(Ae.log(`[RuntimeManager] Invalidated ${n.length} file(s) in ${s}ms for ${e}`),"error"in o&&o.error)throw new Error(`Failed to invalidate files: ${o.error}`)}).catch(i=>{throw Ae.log(`[RuntimeManager] Invalidation failed: ${i.message}`),i});this.invalidationQueue=r.catch(()=>{}),await r}isInitialized(){return this.initialized}async shutdown(){this.initialized&&(Ae.log("[RuntimeManager] Shutdown requested, waiting for in-flight operations..."),await this.invalidationQueue.catch(()=>{}),Ae.log("[RuntimeManager] All operations complete, shutting down runtime..."),await this.provider.shutdown(),this.initialized=!1)}};var JI=class{contexts=new Map;workspacePath;apiKey;lspClient;sharedRuntimeManager=null;RULES_CACHE_TTL_MS=300*1e3;constructor(e){this.workspacePath=e.workspacePath,this.apiKey=e.apiKey,this.lspClient=e.lspClient}async discoverAndInitialize(e,n){let r=await tO(this.workspacePath),i=[];for(let s of r){let a=await this.initializeContext(s).catch(c=>(n?.(s,c),null));if(a){let{baseCommitSha:c}=await ga(s);i.push({repoRoot:s,context:a,baseCommitSha:c}),this.contexts.set(s,a),e?.(s,a)}}let o=[];for(let{repoRoot:s,context:a,baseCommitSha:c}of i)a.config.getEnableDeduplicator()&&o.push({workspaceRoot:s,baseCommitSha:c});if(o.length>0){let s=new ZI(o[0].workspaceRoot);this.sharedRuntimeManager=new qI(s);for(let{context:a}of i)a.config.getEnableDeduplicator()&&(a.runtimeManager=this.sharedRuntimeManager,a.duplicateManager=new zI(this.sharedRuntimeManager,a.config,a.environment))}}async initializeContext(e){let n=new Kr({workspaceRoot:e}),r=await Yo.initialize(n,{apiKey:this.apiKey,lspClient:this.lspClient});if("failed"in r)throw new Error(`Config initialization failed for ${e}: ${r.error}`);let i=r,o=new $o(i,n),s=new zr,a=new La(i,n,s);return{repoRoot:e,environment:n,config:i,ruleProvider:o,eventEmitter:s,ruleExecutor:a,cachedRules:null,rulesById:new Map,rulesCacheTimestamp:0,rulesLoadingPromise:null,lastCommitSelector:null,currentExecutionRules:[],completedRulesCount:0,isExecuting:!1,currentExecutionPromise:null,runtimeManager:null,duplicateManager:null,executionContext:null}}findContextForFile(e){let n=e.toLowerCase();return Array.from(this.contexts.entries()).filter(([i])=>{let o=i.toLowerCase();return n.startsWith(o+elt)||n===o}).sort((i,o)=>o[0].length-i[0].length)[0]?.[1]||null}getAllContexts(){return Array.from(this.contexts.values())}getRepoCount(){return this.contexts.size}hasRepositories(){return this.contexts.size>0}getContext(e){return this.contexts.get(e)}async initializeRuntimeManager(){if(!this.sharedRuntimeManager)return!1;let e=[],n=[];for(let r of this.contexts.values())if(r.config.getEnableDeduplicator()){let{baseCommitSha:i}=await ga(r.repoRoot);e.push({workspaceRoot:r.repoRoot,baseCommitSha:i}),n.length===0&&(n=r.config.getIgnoredGlobs())}return e.length===0?!1:(await this.sharedRuntimeManager.initialize({workspaceConfigs:e,ignores:n}),!0)}async shutdown(){for(let e of this.contexts.values())e.ruleExecutor.clearCache(),e.duplicateManager&&e.duplicateManager.clearCache();this.sharedRuntimeManager&&(await this.sharedRuntimeManager.shutdown(),this.sharedRuntimeManager=null),this.contexts.clear()}};function dre(t,e,n){if(t.fingerprint)return`${e}:${t.fingerprint}`;let r=t.text?.slice(0,100)||"",i=`${t.range.start.line}:${t.range.start.column}-${t.range.end.line}:${t.range.end.column}`;return`${e}:${n}:${i}:${nlt(r)}`}function nlt(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return e.toString(36)}function fre(t){return t.end.line-t.start.line+1>20?{start:{line:t.start.line-1,character:t.start.column-1},end:{line:t.start.line-1,character:Number.MAX_SAFE_INTEGER}}:{start:{line:t.start.line-1,character:t.start.column-1},end:{line:t.end.line-1,character:t.end.column-1}}}var PF=class{connection;documentManager;repositoryContextManager;workspacePath;apiKey;lspClient;batchProgressReporter=null;batchProgressToken="wispbit-batch-lint";progressTokenCreated=!1;fixQueue=[];isProcessingFix=!1;branchCheckTimer=null;BRANCH_CHECK_DEBOUNCE_MS=1e3;branchCheckInterval=null;BRANCH_CHECK_INTERVAL_MS=3e4;executionDebounceTimer=null;EXECUTION_DEBOUNCE_MS=1e3;changedFiles=new Set;hasRunInitialCheck=!1;isExecutingInitial=!1;dismissalsLoadingPromises=new Map;fixesLoadingPromises=new Map;localDismissals=[];constructor(e){this.workspacePath=e.workspacePath,this.apiKey=e.apiKey,this.lspClient=e.lspClient,this.connection=(0,_r.createConnection)(_r.ProposedFeatures.all,process.stdin,process.stdout),this.documentManager=new KI,this.repositoryContextManager=new JI({workspacePath:this.workspacePath,apiKey:this.apiKey,lspClient:this.lspClient}),this.registerHandlers()}addLocalDismissal(e){this.localDismissals.push(e)}isLocallyDismissed(e,n,r,i,o){return this.localDismissals.some(s=>s.matchId===o&&s.uri===e?!0:s.uri===e&&s.ruleId===n?s.startLine<=i&&s.endLine>=r:!1)}clearLocalDismissalsForUri(e){this.localDismissals=this.localDismissals.filter(n=>n.uri!==e)}clearAllLocalDismissals(){this.localDismissals=[]}findContextForFile(e){let n=Jo(e);return this.repositoryContextManager.findContextForFile(n)}pathToNormalizedUri(e){let n=tlt(e).toString();return decodeURIComponent(n)}getDiagnosticsForUri(e){let n=this.documentManager.getDiagnostics(e);if(n.length===0){let r=qr(e),i=this.documentManager.getAllDiagnosticUris();for(let o of i)if(qr(o)===r){n=this.documentManager.getDiagnostics(o);break}}return n}handleRuleComplete(e,n,r){if(!e.isExecuting||e.currentExecutionRules.length===0)return;e.completedRulesCount++;let i=Math.round(e.completedRulesCount/e.currentExecutionRules.length*100);this.updateBatchProgress(i,n)}async handleRuleFileComplete(e,n,r,i){if(!e.isExecuting||e.currentExecutionRules.length===0)return;let o=e.currentExecutionRules.find(u=>u.id===n);if(!o){this.connection.console.log(`[${e.repoRoot}] Warning: Rule ${n} not found in current execution`);return}let s=u_(e.repoRoot,r),a=this.pathToNormalizedUri(s);if(i.length===0){this.updateDiagnosticsForRule(a,o.internalId,[]);return}let c=await this.createDiagnosticsForFile(e,r,o.internalId,i,e.currentExecutionRules);this.updateDiagnosticsForRule(a,o.internalId,c)}async handleRuleFilePartial(e,n,r,i,o){if(!e.isExecuting||e.currentExecutionRules.length===0)return;let s=e.currentExecutionRules.find(l=>l.internalId===n);if(!s){this.connection.console.log(`[${e.repoRoot}] Warning: Rule ${n} not found in current execution`);return}let a=u_(e.repoRoot,r),c=this.pathToNormalizedUri(a);if(i.length===0){this.updateDiagnosticsForRule(c,s.internalId,[]);return}let u=await this.createDiagnosticsForFile(e,r,s.internalId,i,e.currentExecutionRules);this.updateDiagnosticsForRule(c,s.internalId,u)}async convertDuplicateResultsToDiagnostics(e,n,r,i){let o=[];for(let s of n)for(let a of s.matches){let c=dre(a,"DUPLICATE",i);if(this.isLocallyDismissed(i,"DUPLICATE",a.range.start.line,a.range.end.line,c))continue;let u=fre(a.range),l=a.evidence?.map(f=>{let T=u_(e.repoRoot,f.file.path);return{location:{uri:this.pathToNormalizedUri(T),range:{start:{line:f.range.start.line-1,character:f.range.start.column-1},end:{line:f.range.end.line-1,character:f.range.end.column-1}}},message:"Duplicate location"}}),E=null;a.edits&&a.edits.length>0&&(E=await this.computeFixForMatch(a,e).catch(f=>(this.connection.console.log(`Warning: Failed to compute fix for duplicate: ${f}`),null)));let d={range:u,severity:_r.DiagnosticSeverity.Warning,message:a.description||"Duplicate code detected",code:"DUPLICATE",source:"wispbit",relatedInformation:l,data:{uri:i,match:a,matchId:c,fix:E?{diff:E.diff,diffs:E.diffs,autofix:!1}:null,ruleId:"DUPLICATE",filePath:a.file.path,rule:{id:"DUPLICATE",displayId:"DUPLICATE",summary:null}}};o.push(d)}return o}async handleDuplicateFileComplete(e,n,r,i,o){let s=u_(e.repoRoot,n),a=this.pathToNormalizedUri(s),c=await this.createDiagnosticsForFile(e,n,"DUPLICATE",r,[],this.convertDuplicateResultsToDiagnostics.bind(this));this.updateDiagnosticsForRule(a,"DUPLICATE",c)}setupProgressListenersForContext(e){e.eventEmitter.on("rules:progress",n=>{this.updateBatchProgress(n.percentage,n.ruleId)}),e.eventEmitter.on("rules:rule-complete",n=>{this.handleRuleComplete(e,n.ruleId,n.matches)}),e.eventEmitter.on("rules:rule-file-complete",async n=>{await this.handleRuleFileComplete(e,n.ruleId,n.filePath,n.matches)}),e.eventEmitter.on("rules:rule-file-partial",async n=>{await this.handleRuleFilePartial(e,n.ruleId,n.filePath,n.matches,n.totalMatches)})}toRelativePath(e,n){if(!n){let r=this.pathToNormalizedUri(e);n=this.findContextForFile(r)||void 0}return n?Ere(n.repoRoot,e):Ere(this.workspacePath,e)}updateDiagnosticsForRule(e,n,r){this.documentManager.setDiagnosticsForRule(e,n,r);let i=this.documentManager.getDiagnostics(e);this.connection.sendDiagnostics({uri:e,diagnostics:i})}removeDiagnosticByMatchId(e,n){let r=this.documentManager.getDiagnostics(e),i=r.find(a=>a.data?.matchId===n);if(!i)return;let o=i.data?.rule?.id;if(!o)return;let s=r.filter(a=>a.data?.rule?.id===o&&a.data?.matchId!==n);this.updateDiagnosticsForRule(e,o,s)}clearAllDiagnostics(){let e=this.documentManager.getAllDiagnosticUris();for(let n of e)this.clearDiagnosticsForFile(n);this.clearAllLocalDismissals()}clearDiagnosticsForFile(e){this.documentManager.clearDiagnostics(e),this.clearLocalDismissalsForUri(e),this.connection.sendDiagnostics({uri:e,diagnostics:[]})}handleDocumentChangesWithRanges(e,n){let r=this.documentManager.getDiagnostics(e);if(r.length===0)return;this.connection.console.log(`Document changed: ${e}, ${n.length} change(s), ${r.length} diagnostic(s)`);let i=new Set;for(let o of n){if(!o.range){this.connection.console.log("Full document change detected - removing all diagnostics");for(let s of r)s.data?.matchId&&i.add(s.data.matchId);continue}for(let s of r)this.rangesOverlap(o.range,s.range)&&s.data?.matchId&&i.add(s.data.matchId)}for(let o of i)this.removeDiagnosticByMatchId(e,o);i.size>0&&this.connection.console.log(`Removed ${i.size} diagnostic(s) due to document edits`)}rangesOverlap(e,n){return e.end.line<n.start.line||e.start.line>n.end.line?!1:e.start.line<=n.end.line&&e.end.line>=n.start.line}async createDiagnosticsForFile(e,n,r,i,o,s){let a=i.length;this.documentManager.hasDismissals(n)||await this.loadDismissalsForFile(e,n),this.documentManager.hasFixes(n)||await this.loadFixesForFile(e,n);let c={ruleId:r,matches:i},u=this.filterDismissedResults([c],n),l=u[0]?.matches.length||0,E=a-l,d=await this.filterFixedResults(e,u,n),f=d[0]?.matches.length||0,T=l-f,p=u_(e.repoRoot,n),S=this.pathToNormalizedUri(p),m=await(s||this.convertResultsToDiagnostics.bind(this))(e,d,o,S);if(a>0){let h=o.find(P=>P.internalId===r)?.id||r,C=[];E>0&&C.push(`${E} dismissed`),T>0&&C.push(`${T} fixed`),C.length>0?this.connection.console.log(`[${e.repoRoot}] ${n}: ${m.length} diagnostic(s) created, ${C.join(", ")} (rule: ${h})`):this.connection.console.log(`[${e.repoRoot}] ${n}: ${m.length} diagnostic(s) created (rule: ${h})`)}return m}async getFileContent(e){let n=this.pathToNormalizedUri(e),r=this.documentManager.getDocument(n);return r?r.getText():await _re.readFile(e,"utf-8").catch(()=>null)}async computeFixForMatch(e,n){if(!e.edits||e.edits.length===0)return null;let r=await jc(e.edits,e.file.path,n.repoRoot,o=>this.getFileContent(o));return r?{fileChanges:r.fileChanges.map(o=>({...o,fileUri:this.pathToNormalizedUri(o.filePath)})),diff:r.diff,diffs:r.diffs}:null}async loadRulesWithCache(e){let r=Date.now()-e.rulesCacheTimestamp;return e.cachedRules&&r<this.repositoryContextManager.RULES_CACHE_TTL_MS?(this.connection.console.log(`[${e.repoRoot}] Using cached rules (age: ${Math.round(r/1e3)}s / ${this.repositoryContextManager.RULES_CACHE_TTL_MS/1e3}s)`),e.cachedRules):e.rulesLoadingPromise?(this.connection.console.log(`[${e.repoRoot}] Rules are already being loaded, waiting for existing request...`),e.rulesLoadingPromise):(this.connection.console.log(`[${e.repoRoot}] Loading fresh rules from API...`),e.rulesLoadingPromise=e.ruleProvider.loadAllRules().then(i=>{let o=i.filter(s=>s.execution==="llm");e.cachedRules=o,e.rulesCacheTimestamp=Date.now(),e.rulesById.clear();for(let s of o)e.rulesById.set(s.id,s);if(this.connection.console.log(`[${e.repoRoot}] Loaded ${o.length} rules (cache valid for ${this.repositoryContextManager.RULES_CACHE_TTL_MS/1e3}s)`),o.length>0){this.connection.console.log(`[${e.repoRoot}] Fetched rules:`);for(let s of o){let a=s.autofix||!1,c="";a&&(c=" (autofix)"),this.connection.console.log(`[${e.repoRoot}] - ${s.id}: ${s.message}${c}`)}}return o}).finally(()=>{e.rulesLoadingPromise=null}),await e.rulesLoadingPromise)}async loadDismissalsForFile(e,n){if(this.documentManager.hasDismissals(n))return;let r=this.dismissalsLoadingPromises.get(n);if(r)return await r;let i=(async()=>{let s=(await e.ruleProvider.getDismissals([n])).map(a=>({ruleId:a.ruleId,file:a.match.file.path,startLine:a.match.range.start.line,endLine:a.match.range.end.line,fingerprint:a.match.fingerprint,dismissedAt:a.createdAt,dismissalId:a.dismissalId}));this.documentManager.setDismissals(n,s)})().finally(()=>{this.dismissalsLoadingPromises.delete(n)});return this.dismissalsLoadingPromises.set(n,i),await i}async loadFixesForFile(e,n){if(this.documentManager.hasFixes(n))return;let r=this.fixesLoadingPromises.get(n);if(r)return await r;let i=(async()=>{let o=await e.ruleProvider.getFixes([n]);this.documentManager.setFixes(n,o)})().finally(()=>{this.fixesLoadingPromises.delete(n)});return this.fixesLoadingPromises.set(n,i),await i}filterDismissedResults(e,n){let r=this.documentManager.getDismissals(n);return r.length===0?e:e.map(i=>{let o=r.filter(u=>u.ruleId===i.ruleId);if(o.length===0)return i;let s=i.matches.map(u=>({file:n,startLine:u.range.start.line,endLine:u.range.end.line,fingerprint:u.fingerprint})),c=gh(s,o).map(u=>i.matches.find(l=>l.range.start.line===u.startLine&&l.range.end.line===u.endLine&&l.fingerprint===u.fingerprint));return{...i,matches:c}})}async filterFixedResults(e,n,r){let i=this.documentManager.getFixes(r);if(i.length===0)return n;this.connection.console.log(`[${e.repoRoot}] Filtering fixes for ${r}: ${i.length} fix(es) loaded`);let o=u_(e.repoRoot,r),s=await this.getFileContent(o);return s===null?n:n.map(a=>{let c=i.filter(S=>S.ruleId===a.ruleId);if(c.length===0)return a;let u=new Set;for(let S of c)S.match?.edits?.some(O=>O.oldString&&m1(s,O.oldString))&&S.match.fingerprint&&u.add(S.match.fingerprint);let l=c.length-u.size;u.size>0&&this.connection.console.log(`[${e.repoRoot}] ${r}: ${u.size} fix(es) reverted, ${l} still active`);let E=a.matches.map(S=>({file:r,startLine:S.range.start.line,endLine:S.range.end.line,fingerprint:S.fingerprint})),d=c.filter(S=>!S.match.fingerprint||!u.has(S.match.fingerprint)).map(S=>({file:r,startLine:S.match.range.start.line,endLine:S.match.range.end.line,fingerprint:S.match.fingerprint})),T=gh(E,d).map(S=>a.matches.find(m=>m.range.start.line===S.startLine&&m.range.end.line===S.endLine&&m.fingerprint===S.fingerprint)),p=a.matches.length-T.length;return p>0&&this.connection.console.log(`[${e.repoRoot}] ${r}: Filtered out ${p} match(es) with active fixes`),{...a,matches:T}})}async convertResultsToDiagnostics(e,n,r,i){let o=[],s=new Set;for(let a of n){let c=r.find(u=>u.internalId===a.ruleId);if(!c){this.connection.console.log(`Warning: Could not find rule with internal ID ${a.ruleId}`);continue}for(let u of a.matches){let l=`${u.range.start.line}-${u.range.end.line}`;if(s.has(l))continue;s.add(l);let E=dre(u,c.internalId,i);if(this.isLocallyDismissed(i,c.internalId,u.range.start.line,u.range.end.line,E))continue;let d=null;u.edits&&u.edits.length>0&&(d=await this.computeFixForMatch(u,e).catch(p=>(this.connection.console.log(`Warning: Failed to compute fix for match: ${p}`),null)));let T={range:fre(u.range),severity:_r.DiagnosticSeverity.Warning,message:u.description||c.message,code:c.id,codeDescription:{href:`https://app.wispbit.com/rules/${c.internalId}`},source:"wispbit",data:{uri:i,match:u,matchId:E,fix:d?{diff:d.diff,diffs:d.diffs,autofix:c.autofix||!1}:null,rule:{id:c.internalId,displayId:c.id,summary:c.summary||null}}};o.push(T)}}return o}triggerExecution(){this.executionDebounceTimer&&(clearTimeout(this.executionDebounceTimer),this.executionDebounceTimer=null),this.executionDebounceTimer=setTimeout(()=>{this.executionDebounceTimer=null,this.executeQueuedFiles()},this.EXECUTION_DEBOUNCE_MS)}lintDocument(e){if(!this.documentManager.getDocument(e)){this.connection.console.log(`Document not found: ${e}`);return}let r=Jo(e),i=this.toRelativePath(r);this.connection.console.log(`File changed: ${i}`),this.changedFiles.add(e),this.triggerExecution()}async executeQueuedFiles(){let e=this.repositoryContextManager.getAllContexts();if(e.length===0){this.connection.console.log("No repositories found, skipping execution");return}if(!this.hasRunInitialCheck){if(this.isExecutingInitial){this.connection.console.log("Initial check already in progress, files will be queued for next run");return}this.changedFiles.clear(),this.isExecutingInitial=!0;try{await this.repositoryContextManager.initializeRuntimeManager()&&this.connection.console.log("RuntimeManager initialized successfully"),this.hasRunInitialCheck=!0,this.cleanupProgress(),await this.startBatchProgress(0);try{for(let i of e)await this.executeForContext(i,null);this.cleanupProgress()}catch(i){this.connection.console.error(`Error executing rules: ${i.message}`),this.connection.console.error(i.stack),this.cleanupProgress()}}finally{this.isExecutingInitial=!1}}else{let r=Array.from(this.changedFiles);if(this.changedFiles.clear(),r.length===0){this.connection.console.log("No files to check, skipping incremental execution");return}this.connection.console.log(`Incremental check for ${r.length} file(s)`),await this.startBatchProgress(0);try{for(let i of e)await this.executeForContext(i,r);this.cleanupProgress()}catch(i){this.connection.console.error(`Error executing rules: ${i.message}`),this.connection.console.error(i.stack),this.cleanupProgress()}}}async executeForContext(e,n){e.isExecuting=!0;try{let r=await this.loadRulesWithCache(e);e.completedRulesCount=0,e.currentExecutionRules=r;let{commitSelector:i,include:o}=await ga(e.repoRoot);e.lastCommitSelector=i;let s=await Pa.initialize(e.config,e.environment,"diff",e.eventEmitter,void 0,{include:o,commitSelector:i,skipPreExistingViolations:!0});if(e.executionContext=s,e.runtimeManager){let a=[];if(n!==null&&n.length>0?a=n.filter(c=>this.findContextForFile(c)?.repoRoot===e.repoRoot).map(c=>({filePath:this.toRelativePath(Jo(c),e)})):a=s.filePaths.map(c=>({filePath:c})),a.length>0){this.connection.console.log(`[${e.repoRoot}] Starting invalidation of ${a.length} file(s) in RuntimeManager...`);let c=Date.now();await e.runtimeManager.invalidateFiles(e.repoRoot,a);let u=Date.now()-c;this.connection.console.log(`[${e.repoRoot}] Completed invalidation in ${u}ms`)}}if(n!==null&&n.length>0){let a=n.filter(c=>this.findContextForFile(c)?.repoRoot===e.repoRoot);if(a.length===0){this.connection.console.log(`[${e.repoRoot}] No changed files in this repository, skipping`);return}for(let c of a){let u=this.toRelativePath(Jo(c),e);this.connection.console.log(`[${e.repoRoot}] Executing rules for ${u}`),e.completedRulesCount=0;let l=e.ruleExecutor.execute(r,s,{relativePath:u,emitErrors:!0}),E=e.duplicateManager?e.duplicateManager.execute(s,u,(d,f,T,p)=>{this.handleDuplicateFileComplete(e,d,f,T,p)}):Promise.resolve();await Promise.all([l,E])}}else{let a=e.ruleExecutor.execute(r,s,{emitErrors:!0}),c=e.duplicateManager?(async()=>{let u=e.duplicateManager;this.connection.console.log(`[${e.repoRoot}] Starting duplicate detection...`);let l=Date.now();await u.execute(s,void 0,(d,f,T,p)=>{this.handleDuplicateFileComplete(e,d,f,T,p)});let E=Date.now()-l;this.connection.console.log(`[${e.repoRoot}] Completed duplicate detection in ${E}ms`)})():Promise.resolve();await Promise.all([a,c])}}catch(r){this.connection.console.error(`[${e.repoRoot}] Error executing rules: ${r.message}`),this.connection.console.error(r.stack)}finally{e.isExecuting=!1}}async startBatchProgress(e){if(this.batchProgressReporter)this.batchProgressReporter.report(e,"Checking workspace");else try{this.progressTokenCreated||(await this.connection.sendRequest("window/workDoneProgress/create",{token:this.batchProgressToken}),this.progressTokenCreated=!0),this.batchProgressReporter=await this.connection.window.createWorkDoneProgress(),this.batchProgressReporter.begin("wispbit",e,"Checking workspace",!1)}catch(n){this.connection.console.log(`Failed to create batch progress: ${n}`)}}cleanupProgress(){this.batchProgressReporter&&(this.batchProgressReporter.done(),this.batchProgressReporter=null)}updateBatchProgress(e,n){if(!this.batchProgressReporter)return;let r=`Checking workspace (${n})`;this.batchProgressReporter.report(e,r)}async processFixQueue(){if(!this.isProcessingFix){for(this.isProcessingFix=!0;this.fixQueue.length>0;){let e=this.fixQueue.shift();e&&await e()}this.isProcessingFix=!1}}handleQuickfix(e){let{uri:n,matchId:r}=e[0];this.fixQueue.push(async()=>{await this.applyQuickfix(n,r)}),this.processFixQueue()}async applyQuickfix(e,n){let i=this.getDiagnosticsForUri(e).find(T=>T.data?.matchId===n);if(!i){this.connection.window.showErrorMessage("Could not apply fix"),this.connection.console.error(`Diagnostic not found for matchId: ${n}`);return}let o=i.data?.match,s=i.data?.rule;if(!o?.edits||o.edits.length===0){this.connection.window.showErrorMessage("No fix available"),this.connection.console.error(`No fix available for matchId ${n}, rule ${s?.id}`);return}let a=this.findContextForFile(e);if(!a){this.connection.window.showErrorMessage("File is not in any repository"),this.connection.console.error(`No repository context found for ${e}`);return}let c=Jo(e),u=this.toRelativePath(c,a);this.connection.console.log(`[${a.repoRoot}] Applying fix for matchId ${n}, rule ${s?.id}`);let l=await this.computeFixForMatch(o,a);if(!l){this.connection.window.showErrorMessage("Failed to compute fix"),this.connection.console.error(`[${a.repoRoot}] Failed to compute fix for matchId ${n}, rule ${s?.id}`);return}let E=Jo(e),d=[];for(let T of l.fileChanges){let S=T.filePath===E?e:T.fileUri,m=this.documentManager.getDocument(S),O=m?m.lineCount:T.oldContent.split(`
|
|
295
295
|
`).length;m||T.oldContent.length>0||d.push(_r.CreateFile.create(S,{overwrite:!1,ignoreIfExists:!0}));let C={textDocument:{uri:S,version:m?.version??null},edits:[_r.TextEdit.replace({start:{line:0,character:0},end:{line:O,character:0}},T.newContent)]};d.push(C)}let f=await this.connection.workspace.applyEdit({documentChanges:d});f.applied?this.connection.console.log(`[${a.repoRoot}] Applied fix successfully`):this.connection.console.log(`[${a.repoRoot}] Could not apply fix. Reason: ${f.failureReason}, Change: ${f.failedChange}`),await a.ruleProvider.createFix(s?.id,o).catch(T=>{this.connection.console.log(`[${a.repoRoot}] Failed to track fix: ${T.message}`)}),this.removeDiagnosticByMatchId(e,n),this.documentManager.clearFixes(u)}async handleDismiss(e){let{uri:n,matchId:r,ruleId:i,startLine:o,endLine:s}=e[0],a=this.findContextForFile(n);if(!a){this.connection.window.showErrorMessage("File is not in any repository"),this.connection.console.error(`No repository context found for ${n}`);return}let c=Jo(n),u=this.toRelativePath(c,a),l=this.getDiagnosticsForUri(n),E=l.find(S=>S.data?.matchId===r);if(!E&&i&&o!==void 0&&s!==void 0&&(E=l.find(S=>{let m=S.data?.rule?.id,O=S.range.start.line+1,h=S.range.end.line+1;return m===i&&O<=s&&h>=o})),!E){this.connection.window.showErrorMessage("Could not dismiss violation"),this.connection.console.error(`[${a.repoRoot}] Diagnostic not found for matchId: ${r}`);return}let d=E.data?.match,f=E.data?.rule?.id,T=E.data?.matchId;if(!d||!f||!T){this.connection.window.showErrorMessage("Could not dismiss violation"),this.connection.console.error(`[${a.repoRoot}] Match not found for matchId: ${r}`);return}this.addLocalDismissal({uri:n,ruleId:f,startLine:E.range.start.line+1,endLine:E.range.end.line+1,matchId:T,timestamp:Date.now()}),this.removeDiagnosticByMatchId(n,T),await a.ruleProvider.createDismissal(f,d).catch(S=>{this.connection.console.log(`[${a.repoRoot}] Failed to create dismissal: ${S.message}`)});let p=E.data?.rule?.displayId||f;this.connection.console.log(`[${a.repoRoot}] Dismissed violation: ${p} with matchId ${T}`),this.documentManager.clearDismissals(u)}async handleGetDismissals(e){let{uri:n}=e[0];if(!n||typeof n!="string")return this.connection.console.log(`Invalid URI provided to getDismissals: ${n}`),[];if(!n.startsWith("file://"))return this.connection.console.log(`URI must be a file:// URL, got: ${n}`),[];let r=this.findContextForFile(n);if(!r)return this.connection.console.log(`No repository context found for ${n}`),[];let i=Jo(n),o=this.toRelativePath(i,r);await this.loadDismissalsForFile(r,o);let s=this.documentManager.getDismissals(o),a=await this.loadRulesWithCache(r),c=this.documentManager.getDocument(n);if(!c){let u=qr(n),l=this.documentManager.getAllDocumentUris();for(let E of l)if(qr(E)===u){c=this.documentManager.getDocument(E);break}}return s.map(u=>{let l=a.find(f=>f.internalId===u.ruleId),E="";if(c){let f=c.getText({start:{line:u.startLine-1,character:0},end:{line:u.startLine-1,character:100}});E=f.trim().substring(0,60),f.trim().length>60&&(E+="...")}let d="";if(u.dismissedAt){let f=new Date,T=new Date(u.dismissedAt),p=f.getTime()-T.getTime(),S=Math.floor(p/6e4),m=Math.floor(S/60),O=Math.floor(m/24);S<1?d="just now":S<60?d=`${S} minute${S===1?"":"s"} ago`:m<24?d=`${m} hour${m===1?"":"s"} ago`:d=`${O} day${O===1?"":"s"} ago`}return{dismissalId:u.dismissalId,ruleId:u.ruleId,displayId:l?.id||u.ruleId,ruleName:l?.message||"Unknown rule",line:u.startLine,fingerprint:u.fingerprint,fileName:o,codeSnippet:E,timeAgo:d}})}async handleUndismiss(e){let{uri:n,dismissalId:r}=e[0],i=this.findContextForFile(n);if(!i){this.connection.window.showErrorMessage("File is not in any repository"),this.connection.console.error(`No repository context found for ${n}`);return}let o=Jo(n),s=this.toRelativePath(o,i),c=this.documentManager.getDismissals(s).find(f=>f.dismissalId===r);if(!c){this.connection.window.showErrorMessage("Dismissal not found"),this.connection.console.error(`[${i.repoRoot}] Dismissal not found with ID ${r}`);return}await i.ruleProvider.deleteDismissal(c.ruleId,c.file,c.fingerprint);let l=(await this.loadRulesWithCache(i)).find(f=>f.internalId===c.ruleId),E=l?.id||c.ruleId,d=l?.message||"Unknown rule";this.connection.console.log(`Undismissed violation: ${E} at line ${c.startLine}`),this.connection.window.showInformationMessage(`Undismissed violation: ${E} at line ${c.startLine} - ${d}`),this.documentManager.clearDismissals(s),this.triggerExecution()}async handleRemember(e){let{uri:n,range:r,selectedText:i,note:o}=e[0],s=this.findContextForFile(n);if(!s){this.connection.window.showErrorMessage("File is not in any repository"),this.connection.console.error(`No repository context found for ${n}`);return}let a=Jo(n),c=this.toRelativePath(a,s);if(!o||o.trim().length===0){this.connection.window.showErrorMessage("Note is required to remember a pattern");return}let l=this.getDiagnosticsForUri(n).filter(E=>E.source==="wispbit"&&E.data?.match).map(E=>({...E.data.match,ruleId:E.data.rule?.id}));this.connection.console.log(`[${s.repoRoot}] Remembering pattern with ${l.length} matches: ${i.substring(0,100)}...`),this.connection.console.log(`[${s.repoRoot}] Note: ${o}`);try{await s.ruleProvider.rememberPattern(c,i,{start:{line:r.start.line+1,column:r.start.character+1},end:{line:r.end.line+1,column:r.end.character+1}},o.trim(),l),this.connection.window.showInformationMessage(`Pattern remembered: ${o.trim()}`)}catch(E){this.connection.console.log(`Failed to remember: ${E.message}`),this.connection.window.showErrorMessage(`Failed to remember: ${E.message}`)}}truncateMessage(e,n=60){return e.length<=n?e:e.substring(0,n)+"..."}generateCodeActions(e,n){let r=[],i=n.filter(c=>c.source==="wispbit"),o=i.filter(c=>c.data?.fix),s=o.length>1&&o.some((c,u)=>o.slice(u+1).some(l=>c.range.start.line<=l.range.end.line&&c.range.end.line>=l.range.start.line)),a=!1;for(let c of i){let u=c.data?.fix,l=u?.autofix||!1,E=u&&(!s||!a);if(u){let f=this.truncateMessage(c.message);r.push({title:`Apply fix: ${f}`,kind:"quickfix",command:{title:"Apply Fix",command:"wispbit.quickfix",arguments:[{uri:e,matchId:c.data?.matchId}]},diagnostics:[c],isPreferred:E}),E&&(a=!0),l&&r.push({title:`Fix: ${f}`,kind:"source.fixAll",command:{title:"Apply Fix",command:"wispbit.quickfix",arguments:[{uri:e,matchId:c.data?.matchId}]},diagnostics:[c],isPreferred:!1})}let d=this.truncateMessage(c.message);r.push({title:`Dismiss: ${d}`,kind:"quickfix",command:{title:"Dismiss",command:"wispbit.dismiss",arguments:[{uri:e,matchId:c.data?.matchId}]},diagnostics:[c]})}return r}generateHover(e,n){let r=e.find(d=>n.line<d.range.start.line||n.line>d.range.end.line?!1:d.range.start.line===d.range.end.line?n.character>=d.range.start.character&&n.character<=d.range.end.character:n.line===d.range.start.line?n.character>=d.range.start.character:n.line===d.range.end.line?n.character<=d.range.end.character:!0);if(!r)return null;let i=String(r.code||""),o;for(let d of this.repositoryContextManager.getAllContexts())if(o=d.rulesById.get(i),o)break;let s=r.data?.fix,a=r.data?.match?.file?.path,c=r.data?.uri,l=(c?this.findContextForFile(c):null)?.repoRoot||this.workspacePath,E="";if(s?.diffs&&s.diffs.length>0)for(let{file:d,diff:f}of s.diffs){if(!(d.path===a)){let p=u_(l,d.path),S=this.pathToNormalizedUri(p);E+=`*[${d.path}](${S})*
|
|
296
296
|
`}E+="```diff\n",E+=f,E+="\n```\n\n"}return o?.summary&&(o.summary.content&&(E+=`**Summary:** ${o.summary.content}
|
|
297
297
|
|
|
@@ -397,7 +397,7 @@ Global options:
|
|
|
397
397
|
--repo-url <url> Override repository URL (default: from git remote)
|
|
398
398
|
-v, --version Show version number
|
|
399
399
|
-h, --help Show help
|
|
400
|
-
`,{importMeta:import.meta,flags:{rule:{type:"string"},file:{type:"string"},json:{type:"string"},include:{type:"string"},repoUrl:{type:"string"},workspace:{type:"string"},lspClientVersion:{type:"string"},lspClientPackage:{type:"string"},validate:{type:"boolean",default:!1},apiKey:{type:"string"},line:{type:"string"},fix:{type:"string"},dismiss:{type:"string"},version:{type:"boolean",shortFlag:"v"},help:{type:"boolean",shortFlag:"h"}},version:Ho()});async function XW(t){let e=new Kr({repositoryUrl:t.repoUrl}),n=await Fg(e),r=e.getWorkspaceRoot(),{ruleId:i,json:o,mode:s,filePath:a}=t,{commitSelector:c,diffInclude:u}=t;if(s==="diff"){let H=e.getWorkspaceRoot();if(c)u||(u=(await ga(H)).include);else{let oe=await ga(H);c=oe.commitSelector,u||(u=oe.include)}}if(s==="diff"&&c&&u){let H=e.getWorkspaceRoot(),oe=await nV(H),te=rV(c,u,oe);te&&(console.error(j.red(te)),process.exit(1))}let l=!1,E="pretty";o!==void 0?(l=!0,typeof o=="string"?o==="stream"?E="stream":o==="compact"?E="compact":E="pretty":E="pretty"):await UWe();let d,f=new $o(n,e);if(i?d=[await f.loadRuleById(i)]:d=await f.loadAllRules(),!l){let H=n.getContext(),oe=H?.organization_name||"",te=H?.repository_owner||"",Ee=H?.repository_name||"",Re=oe&&te&&Ee?j.dim(` {${oe}:${te}/${Ee}}`):"",Ce=j.bgHex("#4a90e2").black(" DIFF "),Be=(c||"").replace(/\b[0-9a-f]{30,}\b/gi,rt=>rt.substring(0,7)),Ze=a?j.dim(` (${a})`):"",xt=u?` ${Be} ${j.dim(`[${u.join("/")}]`)}`:` ${Be}`;console.log(`${Ce}${xt}${Ze}${Re}`)}let T=new zr,p=u?u.join(", "):"all";T.setExecutionMode("diff",{baseCommit:c||"",headCommit:p});let S=new Map(d.map(H=>[H.id,{message:H.message,severity:H.severity,internalId:H.internalId,execution:H.execution}])),m=process.env.CLAUDECODE==="1",O=s==="diff"&&!l&&!m,h=!t.json&&!l&&!m?O1(T,O,S,r):void 0,C=Date.now(),P=new La(n,e,T),G=0,Y=[];T.on("files:discovery:complete",H=>{G=H.totalFiles}),T.on("rules:rule-error",H=>{let oe=d.find(te=>te.id===H.ruleId);oe&&(Y.push({ruleId:H.ruleId,internalId:oe.internalId,message:H.message,severity:H.severity,error:H.error}),om()&&Gy().then(te=>{te.captureException(H.error,{tags:{source:"rule-execution",ruleId:H.ruleId,severity:H.severity},extra:{message:H.message,internalId:oe.internalId}})}))});let re;l||(re=(await wWe(f)).dismissedMatchesByRule);let W=await Pa.initialize(n,e,s,T,a,s==="diff"?{include:u,commitSelector:c,skipPreExistingViolations
|
|
400
|
+
`,{importMeta:import.meta,flags:{rule:{type:"string"},file:{type:"string"},json:{type:"string"},include:{type:"string"},repoUrl:{type:"string"},workspace:{type:"string"},lspClientVersion:{type:"string"},lspClientPackage:{type:"string"},validate:{type:"boolean",default:!1},apiKey:{type:"string"},line:{type:"string"},fix:{type:"string"},dismiss:{type:"string"},version:{type:"boolean",shortFlag:"v"},help:{type:"boolean",shortFlag:"h"}},version:Ho()});async function XW(t){let e=new Kr({repositoryUrl:t.repoUrl}),n=await Fg(e),r=e.getWorkspaceRoot(),{ruleId:i,json:o,mode:s,filePath:a}=t,{commitSelector:c,diffInclude:u}=t;if(s==="diff"){let H=e.getWorkspaceRoot();if(c)u||(u=(await ga(H)).include);else{let oe=await ga(H);c=oe.commitSelector,u||(u=oe.include)}}if(s==="diff"&&c&&u){let H=e.getWorkspaceRoot(),oe=await nV(H),te=rV(c,u,oe);te&&(console.error(j.red(te)),process.exit(1))}let l=!1,E="pretty";o!==void 0?(l=!0,typeof o=="string"?o==="stream"?E="stream":o==="compact"?E="compact":E="pretty":E="pretty"):await UWe();let d,f=new $o(n,e);if(i?d=[await f.loadRuleById(i)]:d=await f.loadAllRules(),!l){let H=n.getContext(),oe=H?.organization_name||"",te=H?.repository_owner||"",Ee=H?.repository_name||"",Re=oe&&te&&Ee?j.dim(` {${oe}:${te}/${Ee}}`):"",Ce=j.bgHex("#4a90e2").black(" DIFF "),Be=(c||"").replace(/\b[0-9a-f]{30,}\b/gi,rt=>rt.substring(0,7)),Ze=a?j.dim(` (${a})`):"",xt=u?` ${Be} ${j.dim(`[${u.join("/")}]`)}`:` ${Be}`;console.log(`${Ce}${xt}${Ze}${Re}`)}let T=new zr,p=u?u.join(", "):"all";T.setExecutionMode("diff",{baseCommit:c||"",headCommit:p});let S=new Map(d.map(H=>[H.id,{message:H.message,severity:H.severity,internalId:H.internalId,execution:H.execution}])),m=process.env.CLAUDECODE==="1",O=s==="diff"&&!l&&!m,h=!t.json&&!l&&!m?O1(T,O,S,r):void 0,C=Date.now(),P=new La(n,e,T),G=0,Y=[];T.on("files:discovery:complete",H=>{G=H.totalFiles}),T.on("rules:rule-error",H=>{let oe=d.find(te=>te.id===H.ruleId);oe&&(Y.push({ruleId:H.ruleId,internalId:oe.internalId,message:H.message,severity:H.severity,error:H.error}),om()&&Gy().then(te=>{te.captureException(H.error,{tags:{source:"rule-execution",ruleId:H.ruleId,severity:H.severity},extra:{message:H.message,internalId:oe.internalId}})}))});let re;l||(re=(await wWe(f)).dismissedMatchesByRule);let W=await Pa.initialize(n,e,s,T,a,s==="diff"?{include:u,commitSelector:c,skipPreExistingViolations:!0}:void 0),q=await P.execute(d,W,{dismissedMatchesByRule:re,emitErrors:!0}),Z=[];for(let H of q){let oe=d.find(te=>te.id===H.ruleId);if(oe){let Re={ruleId:H.ruleId,internalId:oe.internalId,message:oe.message,severity:oe.severity,execution:oe.execution,matches:H.matches,llmCost:void 0,llmTokens:void 0};Z.push(Re)}}if(t.fix!==void 0&&!l){let H=t.fix?t.fix.split(",").map(oe=>oe.trim()):void 0;await xWe(Z,d,f,r,H,j)}if(t.dismiss!==void 0&&!l){let H=t.dismiss?t.dismiss.split(",").map(oe=>oe.trim()):void 0;await VWe(Z,d,f,H,j)}if(h?.(),l)N1(Z,E,Y);else{let H=Z.filter(ft=>ft.severity==="violation"),oe=Z.filter(ft=>ft.severity==="suggestion"),te=H.reduce((ft,Ve)=>ft+Ve.matches.length,0),Ee=oe.reduce((ft,Ve)=>ft+Ve.matches.length,0),Re=te+Ee,Ce=Z.filter(ft=>ft.llmCost).reduce((ft,Ve)=>ft.plus(new sr(Ve.llmCost||0)),new sr(0)),Be=Z.filter(ft=>ft.llmTokens).reduce((ft,Ve)=>ft+(Ve.llmTokens||0),0),Ze=(c||"").replace(/\b[0-9a-f]{30,}\b/gi,ft=>ft.substring(0,7)),xt=u?u.join(", "):"all",rt={mode:"diff",baseCommit:Ze,headCommit:xt,filePath:a},At=Date.now()-C;R1(Z,{totalRules:d.length,violationCount:te,suggestionCount:Ee,totalMatches:Re,totalLLMCost:Ce.toString(),totalLLMTokens:Be,executionMode:rt,executionTime:At,totalFiles:G,ruleErrors:Y,debugMode:By,showCommandHints:!0})}return Z}async function LWe(t){let e=Date.now(),n=new Na;await n.loadSession(t.sessionId);let i=n.getSessionData().workspaceRoot,o=new Kr({repositoryUrl:t.repoUrl,workspaceRoot:i}),s=await Fg(o),{ruleId:a,json:c}=t,u=!1,l="pretty";c!==void 0?(u=!0,typeof c=="string"?c==="stream"?l="stream":c==="compact"?l="compact":l="pretty":l="pretty"):await UWe();let E,d=new $o(s,o);a?E=[await d.loadRuleById(a)]:E=await d.loadAllRules();let f=new zr;f.setExecutionMode("session",{});let T=new Map(E.map(W=>[W.id,{message:W.message,severity:W.severity,internalId:W.internalId,execution:W.execution}])),p=process.env.CLAUDECODE==="1",S=!t.json&&!u&&!p?O1(f,!0,T,i):void 0,m=n.getFileChanges(),O=m.length,h;u||(h=(await wWe(d)).dismissedMatchesByRule);let C=new La(s,o,f),P=[],G=await Pa.initialize(s,o,"session",f,void 0,void 0,{fileChanges:m}),Y=await C.execute(E,G,{dismissedMatchesByRule:h,emitErrors:!0});f.on("rules:rule-error",W=>{P.push({ruleId:W.ruleId,message:W.message,severity:W.severity,error:W.error})});let re=[];for(let W of Y){let q=E.find(H=>H.id===W.ruleId);if(!q)continue;let Z={ruleId:W.ruleId,message:q.message,severity:q.severity,execution:q.execution,matches:W.matches.map(H=>({file:H.file,range:H.range,language:H.language||"Unknown",text:H.text,fingerprint:H.fingerprint,description:H.description,evidence:H.evidence,edits:H.edits})),llmCost:W.cost,llmTokens:void 0};re.push(Z)}if(S?.(),u)N1(re,l,P);else{let q=process.env.CLAUDECODE==="1"?new Cl({level:3}):j,Z=re.reduce((rt,At)=>rt+At.matches.length,0);if(t.fix===void 0&&t.dismiss===void 0)if(Z>0){let rt=q.red("wispbit found ")+q.red.bold(`${Z}`)+q.red(` ${Z===1?"issue":"issues"}`);console.log(rt)}else console.log(q.hex("#ff69b4")("wispbit found no issues"));if(console.log(q.dim.italic("reviewing changes from current Claude Code session only, run `wispbit diff` to view changes for all sessions")),console.log(),t.fix!==void 0){let rt=t.fix?t.fix.split(",").map(At=>At.trim()):void 0;await xWe(re,E,d,i,rt,q)}if(t.dismiss!==void 0){let rt=t.dismiss?t.dismiss.split(",").map(At=>At.trim()):void 0;await VWe(re,E,d,rt,q)}if(re.length>0&&t.fix===void 0&&t.dismiss===void 0){let rt=await vh(re,E,i,q);console.log(rt)}let H=re.filter(rt=>rt.severity==="violation"),oe=re.filter(rt=>rt.severity==="suggestion"),te=H.reduce((rt,At)=>rt+At.matches.length,0),Ee=oe.reduce((rt,At)=>rt+At.matches.length,0),Re=te+Ee,Ce=re.filter(rt=>rt.llmCost).reduce((rt,At)=>rt.plus(new sr(At.llmCost||0)),new sr(0)),Be=re.filter(rt=>rt.llmTokens).reduce((rt,At)=>rt+(At.llmTokens||0),0),Ze={mode:"session"},xt=Date.now()-e;t.fix===void 0&&t.dismiss===void 0&&R1(re,{totalRules:E.length,violationCount:te,suggestionCount:Ee,totalMatches:Re,totalLLMCost:Ce.toString(),totalLLMTokens:Be,executionMode:Ze,executionTime:xt,totalFiles:O,ruleErrors:P,debugMode:By,showCommandHints:!0},q)}return re}async function PMt(t){let e=new Kr({repositoryUrl:t}),n=await Fg(e),i=await new $o(n,e).loadAllRules();UQ(i)}async function DMt(){let t=ot.flags.apiKey||process.env.WISPBIT_API_KEY;t||(console.error("WISPBIT_API_KEY environment variable or --api-key flag required"),process.exit(1));let e=ot.flags.workspace||process.cwd(),n=ot.flags.lspClientVersion,r=ot.flags.lspClientPackage,i=ot.flags.validate,o=n&&r?{version:n,package:r}:void 0;if(i){let s=await tO(e);s.length===0&&(console.log(JSON.stringify({valid:!1,error:"No git repository found"})),process.exit(1));let a=null,c=[];for(let d of s){let f=new Kr({workspaceRoot:d}),T=await Yo.initialize(f,{apiKey:t,lspClient:o});"failed"in T?c.push({repo:d,success:!1,error:T.error}):(c.push({repo:d,success:!0}),a||(a=T))}if(!a){let d=c.length===1?c[0].error:`No repositories validated successfully (tried ${c.length} repositories)`;console.log(JSON.stringify({valid:!1,error:d,validationResults:c})),process.exit(1)}let u=a.getContext(),l=c.filter(d=>d.success).length,E="https://app.wispbit.com/setup/cli";r&&r.includes("vscode")&&(E="https://app.wispbit.com/setup/vscode"),console.log(JSON.stringify({valid:!0,organizationId:u?.organization_id,organizationName:u?.organization_name,repositoryId:u?.repository_id,repositoryUrl:u?.repository_url,repositoryOwner:u?.repository_owner,repositoryName:u?.repository_name,setupUrl:E,discoveredRepositories:s.length,validRepositories:l,validationResults:c})),process.exit(0)}await Tre({workspacePath:e,apiKey:t,lspClient:o})}async function LMt(t){let e=new Kr({repositoryUrl:t});await Fg(e,{force:!0})}function yMt(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{n+=r}),process.stdin.on("end",()=>{t(n)}),process.stdin.on("error",e)})}async function bMt(t,e){let n=await e.loadAllRules(),r=n.find(i=>i.id===t||i.internalId===t);return r||(console.error(j.red(`Error: Rule not found: ${t}`)),console.error(j.dim(`Available rules: ${n.map(i=>i.id).join(", ")}`)),process.exit(1)),r}async function vMt(t,e){let n=Al.resolve(e,t);try{await Ss.access(n)}catch{console.error(j.red(`Error: File not found: ${t}`)),console.error(j.dim(`Workspace root: ${e}`)),process.exit(1)}return n}async function UMt(t){let{ruleId:e,filePath:n,lineNumbers:r,repoUrl:i}=t,o=new Kr({repositoryUrl:i}),s=await Fg(o),a=new $o(s,o),c=await bMt(e,a);n&&await vMt(n,o.getWorkspaceRoot());let u=await XW({ruleId:c.internalId,mode:"diff",filePath:n,repoUrl:i}),l=[];for(let f of u)for(let T of f.matches)if(r&&r.length>0){let p=T.range.start.line;r.includes(p)&&l.push(T)}else l.push(T);if(l.length===0){let f=n?` in ${n}`:"";console.log(j.yellow(`No violations found for rule ${c.id}${f}`));return}let E=0;for(let f of l)await a.createDismissal(c.internalId,f),E++;console.log(j.green(`\u2713 Dismissed ${E} violation(s) for rule ${c.id}`)),console.log(j.dim(`
|
|
401
401
|
Files affected:`));let d=new Map;for(let f of l)d.has(f.file.path)||d.set(f.file.path,[]),d.get(f.file.path).push(f.range.start.line);for(let[f,T]of d)console.log(j.dim(` \u2022 ${f} (line ${T.join(", ")})`))}async function wMt(){let t=ot.input[0],e=ot.input[1];switch(By&&Ae.enable(),t){case"diff":{let n;if(ot.flags.include){let o=ot.flags.include.split(",").map(c=>c.trim()),s=["committed","staged","unstaged","untracked"],a=o.filter(c=>!s.includes(c));a.length>0&&(console.error(j.red(`Invalid include(s): ${a.join(", ")}. Valid includes: ${s.join(", ")}`)),process.exit(1)),n=o}let r=ot.input[1];await XW({ruleId:ot.flags.rule,json:ot.flags.json,mode:"diff",filePath:ot.flags.file,diffInclude:n,commitSelector:r,repoUrl:ot.flags.repoUrl,fix:ot.flags.fix,dismiss:ot.flags.dismiss});break}case"session":{let n=ot.input[1]||process.env.WISPBIT_SESSION_ID;n||(console.error(j.red("Error: No session ID provided")),console.error(j.dim("Usage: wispbit session <session-id> or set WISPBIT_SESSION_ID environment variable")),process.exit(1)),await LWe({sessionId:n,ruleId:ot.flags.rule,json:ot.flags.json,repoUrl:ot.flags.repoUrl,fix:ot.flags.fix,dismiss:ot.flags.dismiss});break}case"list":{await PMt(ot.flags.repoUrl);break}case"setup":{await LMt(ot.flags.repoUrl);break}case"dismiss":{ot.flags.rule||(console.error(j.red("Error: --rule flag is required")),console.error(j.dim("Usage: wispbit dismiss --rule <ruleId> [--file <path>] [--line <numbers>]")),process.exit(1));let n;ot.flags.line&&(n=ot.flags.line.split(",").map(r=>parseInt(r.trim(),10)).filter(r=>!isNaN(r))),await UMt({ruleId:ot.flags.rule,filePath:ot.flags.file,lineNumbers:n,repoUrl:ot.flags.repoUrl});break}case"cache":{if(e==="purge"){let n=new Kr({repositoryUrl:ot.flags.repoUrl}),i=await new uO(n).purgeCache();console.log(`
|
|
402
402
|
${j.green("Cache purged successfully.")} Removed ${i.deletedCount} item(s).`)}else console.error(j.red("Unknown cache subcommand:"),e),ot.showHelp(),process.exit(1);break}case"handle-hooks":{let n=e;(!n||!n.includes("."))&&(console.error(j.red("Invalid format. Expected: provider.event (e.g., cursor.afterFileEdit)")),process.exit(1));let r=await yMt();Ae.log(`[handle-hooks] Input: ${r}`);let i=JSON.parse(r),o=await GQ(n,i);Ae.log(`[handle-hooks] Output: ${JSON.stringify(o)}`),console.log(JSON.stringify(o));break}case"server":{await DMt();break}default:{let n=process.env.WISPBIT_SESSION_ID;if(n){await LWe({sessionId:n,ruleId:ot.flags.rule,json:ot.flags.json,repoUrl:ot.flags.repoUrl,fix:ot.flags.fix,dismiss:ot.flags.dismiss});break}let r;if(ot.flags.include){let s=ot.flags.include.split(",").map(u=>u.trim()),a=["committed","staged","unstaged","untracked"],c=s.filter(u=>!a.includes(u));c.length>0&&(console.error(j.red(`Invalid include(s): ${c.join(", ")}. Valid includes: ${a.join(", ")}`)),process.exit(1)),r=s}let i=ot.input[0];await XW({ruleId:ot.flags.rule,json:ot.flags.json,mode:"diff",filePath:ot.flags.file,diffInclude:r,commitSelector:i,repoUrl:ot.flags.repoUrl,fix:ot.flags.fix,dismiss:ot.flags.dismiss});break}}}wMt().catch(async t=>{if(om()){let e=await Gy();e.captureException(t,{tags:{source:"cli"}}),await e.close(2e3)}By?console.error(t):console.error(j.red("Error:"),t.message||String(t)),process.exit(1)});export{UWe as checkForUpdates,mC as loadApiKey};
|
|
403
403
|
/*! Bundled license information:
|