@easbot/gateway 0.2.22 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,2 @@
1
- export{a as Gateway}from'./chunks/chunk-IOTK6QKN.mjs';import {j,k as k$1,c as c$1,r}from'./chunks/chunk-DJTIL3AB.mjs';export{q as ChannelPluginLoader,j as DEFAULT_AGENT_REGISTRY_CONFIG,l as DEFAULT_CONNECTION_POOL_CONFIG,k as DEFAULT_SYNC_CONFIG,i as DEFAULT_TOKEN_AUTH_CONFIG,h as DEFAULT_WEBSOCKET_SERVER_CONFIG,s as GatewayServer,p as GatewaySessionManager,a as MessageLockManager,b as MessageRetryManager,m as MessageRouter,n as MessageStore,o as SessionStore,f as createDefaultSessionState,c as createGatewayMessage,d as createTextMessage,e as generateSessionId,g as generateSubscriptionId}from'./chunks/chunk-DJTIL3AB.mjs';export{p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,j as AuthConfigSchema,h as ChannelConfigSchema,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,c as FeishuChannelConfigSchema,l as GatewayClusterConfigSchema,s as GatewayConfigSchema,r as GatewayServerConfigSchema,i as HTTPSConfigSchema,n as MessageQueueConfigSchema,g as NostrChannelConfigSchema,q as SessionConfigSchema,f as SignalChannelConfigSchema,b as SlackChannelConfigSchema,a as TelegramChannelConfigSchema,d as WeChatChannelConfigSchema,e as WebChatChannelConfigSchema,z as clearConfigCache,O as getAgentAdapter,G as getAgentRegistryConfig,J as getAuthConfig,C as getChannelConfig,F as getCircuitBreakerConfig,K as getClusterConfig,x as getConfig,A as getConfigDirectory,D as getConnectionPoolConfig,L as getDefaultAgent,I as getHTTPSConfig,M as getLogLevel,E as getMessageQueueConfig,B as getServerConfig,H as getSessionConfig,P as hasAgentAdapter,y as isConfigLoaded,w as loadConfig,u as parsePartialConfig,Q as requireAgentAdapter,N as setAgentAdapter,t as validateConfig}from'./chunks/chunk-77F43CRD.mjs';import {a}from'./chunks/chunk-6TRL3CVJ.mjs';import {a as a$1}from'./chunks/chunk-HAMGVOQD.mjs';var f=a.create({service:"gateway:agent-registry"}),k=class{constructor(n={}){a$1(this,"config");a$1(this,"agents",new Map);a$1(this,"heartbeatTimer",null);a$1(this,"roundRobinIndex",0);this.config={...j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),f.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){f.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),f.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw f.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),f.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(u=>o.capabilities.includes(u)))),i.length===0){f.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return f.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,f.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,f.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let u=n-o.lastHeartbeat;if(u>t){s.push(a);continue}u>e&&o.status==="healthy"&&(o.status="unhealthy",i++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:u,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};var g=a.create({service:"gateway:agent-sync-manager"}),T=class{constructor(n){a$1(this,"config");a$1(this,"registry");a$1(this,"localNodeId");a$1(this,"localNodeName");a$1(this,"remoteNodes",new Map);a$1(this,"remoteAgents",new Map);a$1(this,"syncTimer",null);a$1(this,"running",false);a$1(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...k$1,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){g.warn("Agent sync manager is already running");return}g.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,g.info("Agent sync manager started");}async stop(){if(!this.running){g.warn("Agent sync manager is not running");return}g.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,g.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){g.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);g.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let u of o)u.sourceGatewayId=n,this.remoteAgents.set(u.id,u);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,g.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",g.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){g.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);g.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){g.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(g.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:g.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);g.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);g.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),g.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),g.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),g.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),g.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);g.info("Remote node removed",{nodeId:n});}};var c=class{constructor(){a$1(this,"version","1.0.0");a$1(this,"log");a$1(this,"config",null);a$1(this,"messageHandler",null);a$1(this,"_status","stopped");a$1(this,"lastActivity",0);}initLog(){this.log=a.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};var x=class{constructor(n){a$1(this,"log");a$1(this,"config");a$1(this,"ws",null);a$1(this,"state","disconnected");a$1(this,"subscriptions",new Map);a$1(this,"messageCallbacks",new Set);a$1(this,"agentListCallbacks",new Set);a$1(this,"cachedAgentList",[]);a$1(this,"localAgentList",[]);a$1(this,"reconnectAttempts",0);a$1(this,"reconnectTimer",null);a$1(this,"heartbeatTimer",null);a$1(this,"agentListRequestId",null);a$1(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=a.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((n,e)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(u=>u.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};var y=class extends c{constructor(e="telegram-main"){super();a$1(this,"id");a$1(this,"platform","telegram");a$1(this,"name","Telegram Bot");a$1(this,"botConfig",null);a$1(this,"pollingInterval",null);a$1(this,"lastUpdateId",0);a$1(this,"baseUrl","");this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
2
-
3
- ${e.caption}`}:t.unshift({type:"text",text:e.caption});}return t}getSessionId(e){let t=e.chat.id.toString(),s=e.from?.id.toString();return e.chat.type==="private"?`telegram_${this.id}_${t}`:`telegram_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
4
- `)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,t,s){return (await this.request("getUpdates",{offset:e,limit:t,timeout:s})).result||[]}async sendMessage(e,t){return (await this.request("sendMessage",{chat_id:e,text:t,parse_mode:"Markdown"})).result}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Telegram API error: ${a.description}`);return a}};var b=class extends c{constructor(e="discord-main"){super();a$1(this,"id");a$1(this,"platform","discord");a$1(this,"name","Discord Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","https://discord.com/api/v10");a$1(this,"gatewayWs",null);a$1(this,"heartbeatInterval",null);a$1(this,"sessionId",null);a$1(this,"sequenceNumber",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.createMessage(t,s,e.metadata.context?.replyTo)).id}async startGateway(){let t=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(t),this.gatewayWs.onmessage=s=>{this.handleGatewayMessage(JSON.parse(s.data.toString()));},this.gatewayWs.onclose=()=>{this.log.info("Gateway disconnected"),setTimeout(()=>this.startGateway(),5e3);},this.gatewayWs.onerror=s=>{this.log.error("Gateway error",{error:String(s)});};}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,t){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(t);}async handleDiscordMessage(e){if(e.author.bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}parseContent(e){let t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.attachments)s.content_type?.startsWith("image/")?t.push({type:"image",image:s.url,mime:s.content_type}):t.push({type:"file",data:s.url,mime:s.content_type});return t}getSessionId(e){let t=e.channel_id,s=e.author.id;return `discord_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
5
- `)}async getCurrentUser(){return this.request("GET","/users/@me")}async getGatewayBot(){return this.request("GET","/gateway/bot")}async createMessage(e,t,s){let i={content:t};return s&&(i.message_reference={message_id:s}),this.request("POST",`/channels/${e}/messages`,i)}async request(e,t,s){let i=`${this.baseUrl}${t}`,a=await fetch(i,{method:e,headers:{Authorization:`Bot ${this.botConfig?.botToken}`,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!a.ok){let o=await a.text();throw new Error(`Discord API error: ${o}`)}return a.json()}};var C=class extends c{constructor(e="slack-main"){super();a$1(this,"id");a$1(this,"platform","slack");a$1(this,"name","Slack Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","");a$1(this,"socketModeClient",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl="https://slack.com/api";let e=await this.authTest();this.log.info("Slack bot connected",{user:e.user,team:e.team,bot_id:e.bot_id}),this.botConfig.socketMode&&this.botConfig.appToken&&await this.startSocketMode();}async doStop(){this.socketModeClient&&(this.socketModeClient.close(),this.socketModeClient=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.postMessage(t,s,e.metadata.context?.threadId)).ts}async startSocketMode(){if(!this.botConfig?.appToken)return;let e="wss://wss-primary.slack.com/socket";this.socketModeClient=new WebSocket(e),this.socketModeClient.onmessage=async t=>{try{let s=JSON.parse(t.data.toString());await this.handleSocketModeEvent(s);}catch(s){this.log.error("Socket mode event error",{error:String(s)});}},this.log.info("Socket mode started");}async handleSocketModeEvent(e){if(e.envelope_id&&this.socketModeClient?.send(JSON.stringify({envelope_id:e.envelope_id})),e.type==="events_api"&&e.payload?.event){let t=e.payload.event;t.type==="message"&&!t.subtype&&await this.handleSlackMessage(t);}}async handleSlackMessage(e){this.updateActivity();let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"slack",channelId:this.id,userId:e.user,chatId:e.channel,ts:e.ts,threadTs:e.thread_ts},context:{threadId:e.thread_ts,conversationId:e.channel}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.files)for(let s of e.files)t.push({type:"file",data:s.url_private,mime:s.mimetype});return t}getSessionId(e){let t=e.channel,s=e.user;return `slack_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
6
- `)}async authTest(){return await this.request("auth.test")}async postMessage(e,t,s){let i={channel:e,text:t};return s&&(i.thread_ts=s),await this.request("chat.postMessage",i)}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.botConfig?.botToken}`,"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`);return a}};var v=class extends c{constructor(e="feishu-main"){super();a$1(this,"id");a$1(this,"platform","feishu");a$1(this,"name","Feishu Bot");a$1(this,"botConfig",null);a$1(this,"baseUrl","https://open.feishu.cn/open-apis");a$1(this,"tenantAccessToken",null);a$1(this,"tokenExpireTime",0);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");await this.refreshTenantAccessToken(),this.log.info("Feishu bot connected",{app_id:this.botConfig.appId});}async doStop(){this.botConfig=null,this.tenantAccessToken=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");await this.ensureTokenValid();let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id}async handleWebhookEvent(e){if(this.updateActivity(),this.botConfig?.verificationToken,e.event?.message){let t=this.toGatewayMessage(e);await this.handleMessage(t);}}toGatewayMessage(e){let t=e.event.message,s=this.getSessionId(e);return c$1(s,"input",this.parseContent(t),{channel:{platform:"feishu",channelId:this.id,userId:t.sender.sender_id.open_id,chatId:t.chat_id,messageId:t.message_id,rootId:t.root_id,parentId:t.parent_id,tenantKey:e.tenant_key},context:{threadId:t.root_id,conversationId:t.chat_id}})}parseContent(e){let t=[];try{let s=JSON.parse(e.content);switch(e.message_type){case "text":s.text&&t.push({type:"text",text:s.text});break;case "post":if(s.content){let i=this.extractPostContent(s.content);t.push({type:"text",text:i});}break;case "image":s.image_key&&t.push({type:"image",image:s.image_key,mime:"image/jpeg"});break;case "file":s.file_key&&t.push({type:"file",data:s.file_key,mime:s.file_type});break;default:t.push({type:"text",text:JSON.stringify(s)});}}catch{t.push({type:"text",text:e.content});}return t}extractPostContent(e){let t=[];for(let s of e)if(typeof s=="object"&&s!==null){let i=s;i.text&&t.push(String(i.text)),Array.isArray(i.children)&&t.push(this.extractPostContent(i.children));}return t.join(`
7
- `)}getSessionId(e){let t=e.event.message,s=t.chat_id,i=t.sender.sender_id.open_id;return `feishu_${this.id}_${s}_${i}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
8
- `)}async refreshTenantAccessToken(){let t=await(await fetch(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret})})).json();if(t.code!==0)throw new Error(`Feishu API error: ${t.msg}`);this.tenantAccessToken=t.tenant_access_token,this.tokenExpireTime=Date.now()+t.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,t){let i=await(await fetch(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{method:"POST",headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:e,msg_type:"text",content:JSON.stringify({text:t})})})).json();if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};var w=class extends c{constructor(e="wechat-main"){super();a$1(this,"id");a$1(this,"platform","wechat");a$1(this,"name","WeChat Bot");a$1(this,"botConfig",null);a$1(this,"accessToken",null);a$1(this,"tokenExpireTime",0);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.botConfig=null,this.accessToken=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("User ID is required");await this.ensureTokenValid();let s=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(t,s):await this.sendOfficialMessage(t,s)}async handleWebhookMessage(e){this.updateActivity();let t=this.parseXmlMessage(e);if(t){let s=this.toGatewayMessage(t);await this.handleMessage(s);}}parseXmlMessage(e){let t=a=>e.match(new RegExp(`<${a}><!\\[CDATA\\[(.*?)\\]\\]></${a}>`))?.[1],s=a=>{let o=e.match(new RegExp(`<${a}>(\\d+)</${a}>`));return o?.[1]?parseInt(o[1],10):void 0},i=t("MsgType");return i?{ToUserName:t("ToUserName")??"",FromUserName:t("FromUserName")??"",CreateTime:s("CreateTime")??0,MsgType:i,Content:t("Content"),MsgId:s("MsgId"),PicUrl:t("PicUrl"),MediaId:t("MediaId")}:null}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"wechat",channelId:this.id,userId:e.FromUserName,chatId:e.FromUserName,toUser:e.ToUserName,msgId:e.MsgId?.toString(),mode:this.botConfig?.mode},context:{conversationId:e.FromUserName}})}parseContent(e){let t=[];switch(e.MsgType){case "text":e.Content&&t.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&t.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&t.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&t.push({type:"text",text:e.Content});}return t}getSessionId(e){let t=e.FromUserName;return `wechat_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
9
- `)}async refreshAccessToken(){let e;this.botConfig?.mode==="wecom"?e=`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${this.botConfig.appId}&corpsecret=${this.botConfig.appSecret}`:e=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.botConfig?.appId}&secret=${this.botConfig?.appSecret}`;let s=await(await fetch(e)).json();if(s.errcode&&s.errcode!==0)throw new Error(`WeChat API error: ${s.errmsg}`);this.accessToken=s.access_token,this.tokenExpireTime=Date.now()+s.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,t){let i=await(await fetch(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,t){let i=await(await fetch(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};var S=class extends c{constructor(e="webchat-main"){super();a$1(this,"id");a$1(this,"platform","webchat");a$1(this,"name","WebChat");a$1(this,"webChatConfig",null);a$1(this,"connections",new Map);a$1(this,"heartbeatInterval",null);a$1(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");this.webChatConfig=this.config.platform,await this.startWebSocketServer(),this.startHeartbeat(),this.log.info("WebChat plugin started",{port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections});}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new r(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async doStop(){this.wsServer&&(await this.wsServer.stop(),this.wsServer=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.webChatConfig=null;}async send(e){let t=e.sessionId,s=e.metadata.channel.userId;if(this.wsServer&&t){let o={type:"message",sessionId:t,properties:{sessionID:t,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(t,o),e.id}if(!s)throw new Error("User ID is required");let i=this.findConnectionByUser(s);if(!i)throw new Error("User not connected");let a={type:"message",sessionId:t,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(a)),i.lastActivity=Date.now(),e.id}pushEvent(e,t){this.wsServer&&this.wsServer.broadcastToSession(e,t);}getWebSocketServer(){return this.wsServer}async handleConnection(e,t){let s=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:s,ws:e,userId:t,lastActivity:Date.now()};this.connections.set(s,i),e.onmessage=a=>{this.handleWebSocketMessage(i,a.data.toString());},e.onclose=()=>{this.connections.delete(s),this.log.debug("WebSocket closed",{connId:s,userId:t});},e.onerror=a=>{this.log.error("WebSocket error",{connId:s,userId:t,error:String(a)});},this.log.info("WebSocket connected",{connId:s,userId:t});}async handleWebSocketMessage(e,t){this.updateActivity(),e.lastActivity=Date.now();try{let s=JSON.parse(t);switch(s.type){case "message":await this.handleChatMessage(e,s);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":s.sessionId&&(e.sessionId=s.sessionId);break;case "unsubscribe":e.sessionId=void 0;break}}catch(s){this.log.error("Failed to handle WebSocket message",{error:String(s)});}}async handleChatMessage(e,t){if(!t.content||!t.sessionId)return;let s=c$1(t.sessionId,"input",t.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:t.sessionId,connectionId:e.id},context:{conversationId:t.sessionId},...t.metadata});await this.handleMessage(s);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let t=Date.now(),s=this.webChatConfig?.connectionTimeout??6e4;for(let[i,a]of this.connections)t-a.lastActivity>s&&(this.log.info("Closing inactive connection",{connId:i}),a.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let t of this.connections.values())if(t.userId===e)return t}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};var A=class extends c{constructor(e="signal-main"){super();a$1(this,"id");a$1(this,"platform","signal");a$1(this,"name","Signal Bot");a$1(this,"botConfig",null);a$1(this,"pollingInterval",null);a$1(this,"lastTimestamp",0);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw new Error("Phone number is required");let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("Recipient is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).timestamp.toString()}startPolling(){this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},5e3),this.log.info("Polling started",{interval:5e3});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let t of e)this.lastTimestamp=t.envelope.timestamp,t.envelope.dataMessage&&await this.handleSignalMessage(t);}async handleSignalMessage(e){this.updateActivity();let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e),s=e.envelope.dataMessage;return c$1(t,"input",this.parseContent(s),{channel:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,sourceUuid:e.envelope.sourceUuid,timestamp:e.envelope.timestamp},context:{conversationId:e.envelope.sourceNumber}})}parseContent(e){let t=[];if(!e)return t;if(e.message&&t.push({type:"text",text:e.message}),e.attachments)for(let s of e.attachments)s.contentType.startsWith("image/")?t.push({type:"image",image:s.id,mime:s.contentType}):t.push({type:"file",data:s.id,mime:s.contentType});return t}getSessionId(e){let t=e.envelope.sourceNumber;return `signal_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
10
- `)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let t=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${t}`)||[]}async sendMessage(e,t){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:t})}async request(e,t,s){let i=`${this.botConfig?.serviceUrl}${t}`,a={"Content-Type":"application/json"};this.botConfig?.password&&(a.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let o=await fetch(i,{method:e,headers:a,body:s?JSON.stringify(s):void 0});if(!o.ok){let u=await o.text();throw new Error(`Signal API error: ${u}`)}return o.json()}};var M=class extends c{constructor(e="nostr-main"){super();a$1(this,"id");a$1(this,"platform","nostr");a$1(this,"name","Nostr Bot");a$1(this,"botConfig",null);a$1(this,"relayConnections",new Map);a$1(this,"subscriptions",new Map);a$1(this,"eventHandlers",new Map);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw new Error("At least one relay is required");for(let e of this.botConfig.relays)await this.connectToRelay(e);this.log.info("Nostr bot connected",{relays:this.botConfig.relays,pubkey:this.botConfig.publicKey?.substring(0,16)+"..."});}async doStop(){for(let[e,t]of this.relayConnections)t.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.botConfig=null;}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let t=this.extractText(e),s=await this.createEvent(t,e.metadata.context?.replyTo);return await this.publishEvent(s),s.id}async connectToRelay(e){let t=new WebSocket(e);t.onopen=()=>{this.log.info("Connected to relay",{relay:e});for(let[s,i]of this.subscriptions)this.subscribeToRelay(t,s,i);},t.onmessage=s=>{this.handleRelayMessage(e,s.data.toString());},t.onclose=()=>{this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e),setTimeout(()=>this.connectToRelay(e),5e3);},t.onerror=s=>{this.log.error("Relay error",{relay:e,error:String(s)});},this.relayConnections.set(e,t);}handleRelayMessage(e,t){this.updateActivity();try{let s=JSON.parse(t);if(s[0]==="EVENT"&&s[2]){let i=s[2];this.handleNostrEvent(i);}if(s[0]==="OK"){let i=s[1],a=s[2];this.log.debug("Event published",{eventId:i,success:a});}}catch(s){this.log.error("Failed to handle relay message",{error:String(s)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||e.pubkey===this.botConfig?.publicKey)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.tags)if(s[0]==="url"&&s[1]){let i=s[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&t.push({type:"image",image:i});}return t}findReplyTo(e){for(let t of e)if(t[0]==="e"&&t[1])return t[1]}getSessionId(e){return `nostr_${this.id}_${e.pubkey}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
11
- `)}subscribeToRelay(e,t,s){let i=["REQ",t,s];e.send(JSON.stringify(i));}async createEvent(e,t){let s=[];t&&s.push(["e",t]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:s,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let t=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(a)).map(u=>u.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let t=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(t));}};var _=class extends c{constructor(e){super();a$1(this,"id");a$1(this,"platform");a$1(this,"name");a$1(this,"version");a$1(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let t=e;this.options.actions?.beforeSend&&(t=await this.options.actions.beforeSend(e));let s=await this.options.messaging.send(t);return this.options.actions?.afterSend&&await this.options.actions.afterSend(t,s),s}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function N(l){return new _(l)}var E={telegram:y,discord:b,slack:C,feishu:v,wechat:w,webchat:S,signal:A,nostr:M};function $e(){return Object.keys(E)}async function kn(l){let{Log:n}=await import('./chunks/log-K67H67P2.mjs'),e=false;await n.init({logDir:l.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:l.print??false,dev:l.dev??e,level:l.level??("INFO")});}export{k as AgentRegistry,T as AgentSyncManager,c as BaseChannelPlugin,E as ChannelPluginRegistry,b as DiscordPlugin,v as FeishuPlugin,x as GatewayClient,M as NostrPlugin,A as SignalPlugin,C as SlackPlugin,y as TelegramPlugin,w as WeChatPlugin,S as WebChatPlugin,N as createChannelPlugin,$e as getSupportedPlatforms,kn as initLog};
1
+ import {v,Q,_,$}from'./chunks/chunk-GQFBXITJ.mjs';export{p as AgentRegistryConfigSchema,k as AgentSyncConfigSchema,j as AuthConfigSchema,ha as BaseChannelPlugin,h as ChannelConfigSchema,fa as ChannelPluginLoader,ra as ChannelPluginRegistry,o as CircuitBreakerConfigSchema,m as ConnectionPoolConfigSchema,_ as DEFAULT_AGENT_REGISTRY_CONFIG,aa as DEFAULT_CONNECTION_POOL_CONFIG,$ as DEFAULT_SYNC_CONFIG,Z as DEFAULT_TOKEN_AUTH_CONFIG,Y as DEFAULT_WEBSOCKET_SERVER_CONFIG,ja as DiscordPlugin,c as FeishuChannelConfigSchema,la as FeishuPlugin,l as GatewayClusterConfigSchema,s as GatewayConfigSchema,ta as GatewayServer,r as GatewayServerConfigSchema,ea as GatewaySessionManager,i as HTTPSConfigSchema,R as MessageLockManager,n as MessageQueueConfigSchema,S as MessageRetryManager,ba as MessageRouter,ca as MessageStore,g as NostrChannelConfigSchema,pa as NostrPlugin,q as SessionConfigSchema,da as SessionStore,f as SignalChannelConfigSchema,oa as SignalPlugin,b as SlackChannelConfigSchema,ka as SlackPlugin,a as TelegramChannelConfigSchema,ia as TelegramPlugin,d as WeChatChannelConfigSchema,ma as WeChatPlugin,e as WebChatChannelConfigSchema,na as WebChatPlugin,y as clearConfigCache,qa as createChannelPlugin,W as createDefaultSessionState,T as createGatewayMessage,U as createTextMessage,V as generateSessionId,X as generateSubscriptionId,N as getAgentAdapter,F as getAgentRegistryConfig,I as getAuthConfig,B as getChannelConfig,E as getCircuitBreakerConfig,J as getClusterConfig,w as getConfig,z as getConfigDirectory,C as getConnectionPoolConfig,K as getDefaultAgent,H as getHTTPSConfig,L as getLogLevel,D as getMessageQueueConfig,A as getServerConfig,G as getSessionConfig,sa as getSupportedPlatforms,O as hasAgentAdapter,x as isConfigLoaded,v as loadConfig,u as parsePartialConfig,P as requireAgentAdapter,M as setAgentAdapter,t as validateConfig}from'./chunks/chunk-GQFBXITJ.mjs';import {a as a$1}from'./chunks/chunk-OBW6CNOG.mjs';import {a as a$2}from'./chunks/chunk-HAMGVOQD.mjs';import {Fetch}from'@easbot/utils';var a=a$1.create({service:"gateway"}),m=class i extends Error{constructor(t,n,s){super(t);a$2(this,"type");a$2(this,"stage");a$2(this,"cause");this.type="GatewayInitializationError",this.stage=n,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,i);}};function G(i){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=i.code;return e.includes(t??"")}function et(){process.on("unhandledRejection",i=>{let e=i instanceof Error?i:new Error(String(i));G(e)||a.error("unhandled promise rejection",{error:e.message,stack:e.stack});}),process.on("uncaughtException",i=>{G(i)||(a.error("uncaught exception",{error:i.message,stack:i.stack}),process.exit(1));});}var x;(at=>{let i={initialized:false,initPromise:null,directory:".easbot",config:null},e,t={server:null,config:null,initialized:false,status:"stopped"};async function n(u={}){if(i.initialized)return;if(i.initPromise)return i.initPromise;let d={directory:u.directory??".easbot",printLogs:u.printLogs??false,logLevel:u.logLevel??"INFO"};return i.directory=d.directory,i.initPromise=(async()=>{let{Global:b}=await import('./chunks/global-DVGSJ3V3.mjs');try{await b.init();}catch(g){throw new m("Failed to initialize global directories","global",g instanceof Error?g:void 0)}try{await a$1.init({logDir:b.Path.log,print:d.printLogs,level:d.logLevel});}catch(g){throw new m("Failed to initialize log infrastructure","log",g instanceof Error?g:void 0)}try{et();}catch(g){throw new m("Failed to install unhandled exception handlers","server",g instanceof Error?g:void 0)}Fetch.hasProxyConfigured()&&(Fetch.enableProxy({connectTimeout:1e4,keepAliveTimeout:3e4}),a.info("global proxy enabled",{proxyUrl:Fetch.getProxyUrl()}));try{i.config=await v(d.directory);}catch(g){throw new m("Failed to load gateway configuration","config",g instanceof Error?g:void 0)}i.initialized=true,a.info("gateway runtime initialized",{directory:d.directory,logLevel:d.logLevel});})(),i.initPromise}at.init=n;function s(){return i.initialized}at.isInitialized=s;function r(){return e||(e=async()=>{if(!i.initialized)throw new m("Gateway not initialized. Call init() first.","server");let u=Q(),d=await v(u.directory);return d.server?.enabled?(t={server:null,config:d,initialized:true,status:"stopped"},a.info("gateway initialized",{port:d.server?.port,hostname:d.server?.hostname}),t):(a.debug("gateway server disabled or not configured"),{server:null,config:d,initialized:true,status:"stopped"})}),e}function c(){return r()()}at.state=c;async function l(){return (await c()).server}at.get=l;async function y(){return (await c()).config?.server?.enabled??false}at.isEnabled=y;async function tt(){return (await c()).config}at.config=tt;function nt(){return t.status}at.getStatus=nt;async function _(u){a.debug("Gateway.start: called"),i.initialized||(a.debug("Gateway.start: calling init()"),await n(),a.debug("Gateway.start: init() completed")),a.debug("Gateway.start: calling state()");let d=await c();if(a.debug("Gateway.start: state() completed",{status:d.status}),!(d.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(t.status==="running"){a.info("gateway server is already running");return}if(t.status==="starting"){a.info("gateway server is starting");return}t.status="starting",a.debug("Gateway.start: status set to starting");try{let g={...d.config?.server,...u};a.debug("gateway start: creating server with config",{port:g.port,hostname:g.hostname,path:g.path,https:g.https?.enabled}),a.debug("Gateway.start: calling createGatewayServer");let R=await O(g);a.debug("Gateway.start: createGatewayServer completed"),a.debug("gateway start: server created, updating state"),t.server=R,t.status="running",t.error=void 0,a.info("gateway server started",{port:g.port,hostname:g.hostname});}catch(g){throw t.status="error",t.error=g instanceof Error?g.message:String(g),a.error("failed to start gateway server",{error:t.error}),g}}at.start=_;async function F(){if(t.status==="stopped"){a.info("gateway server is already stopped");return}if(t.status==="stopping"){a.info("gateway server is stopping");return}t.status="stopping";try{t.server&&await t.server.stop(),t.server=null,t.status="stopped",t.error=void 0,a.info("gateway server stopped");}catch(u){throw t.status="error",t.error=u instanceof Error?u.message:String(u),a.error("failed to stop gateway server",{error:t.error}),u}}at.stop=F;async function st(u){a.info("restarting gateway server"),(t.status==="running"||t.status==="starting")&&await F(),await _(u);}at.restart=st;async function rt(){let u=Q(),d=await v(u.directory);return t.config=d,i.config=d,a.info("gateway config reloaded"),d}at.reloadConfig=rt;async function O(u,d){a.debug("createGatewayServer: starting");let{GatewayServer:b}=await import('./chunks/server-HGRZI7JT.mjs');a.debug("createGatewayServer: GatewayServer imported");let g=new b(u);a.debug("createGatewayServer: server instance created"),a.debug("createGatewayServer: created server instance, calling start()");let R=d?.startupTimeout??3e4;if(await(async()=>{let A=new Promise((v,D)=>{setTimeout(()=>{D(new Error(`Gateway server startup timeout after ${R}ms`));},R);});try{a.debug("createGatewayServer: calling server.start()"),await Promise.race([g.start(),A]),a.debug("createGatewayServer: server.start() completed");}catch(v){a.error("gateway server start failed, attempting cleanup",{error:v instanceof Error?v.message:String(v)});try{await g.stop();}catch{}throw v}})(),d?.onStarted)try{await d.onStarted(g);}catch(A){a.warn("server started but onStarted callback failed",{error:A instanceof Error?A.message:String(A)});}return a.info("gateway server created and started",{port:u.port,hostname:u.hostname}),g}at.createGatewayServer=O;})(x||(x={}));var f=a$1.create({service:"gateway:agent-registry"}),M=class{constructor(e={}){a$2(this,"config");a$2(this,"agents",new Map);a$2(this,"heartbeatTimer",null);a$2(this,"roundRobinIndex",0);this.config={..._,...e};}async register(e){if(this.agents.has(e.id))throw new Error(`Agent with ID "${e.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let t=Date.now(),n={...e,status:"healthy",lastHeartbeat:t,registeredAt:t,connectionCount:0};this.agents.set(e.id,n),f.info("Agent registered",{agentId:e.id,name:e.name,capabilities:e.capabilities,address:e.address,totalAgents:this.agents.size});}async deregister(e){let t=this.agents.get(e);if(!t){f.warn("Attempted to deregister unknown agent",{agentId:e});return}this.agents.delete(e),f.info("Agent deregistered",{agentId:e,name:t.name,totalAgents:this.agents.size});}async heartbeat(e,t){let n=this.agents.get(e);if(!n)throw f.warn("Heartbeat received from unknown agent",{agentId:e}),new Error(`Agent "${e}" is not registered`);n.lastHeartbeat=Date.now(),n.status="healthy",t&&(n.metadata={...n.metadata,...t}),f.debug("Agent heartbeat received",{agentId:e,lastHeartbeat:n.lastHeartbeat});}getAgent(e){return this.agents.get(e)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(e=>e.status==="healthy")}selectAgent(e){let{strategy:t,capabilities:n,healthyOnly:s=true}=e,r=s?this.getHealthyAgents():this.getAllAgents();if(n&&n.length>0&&(r=r.filter(l=>n.every(y=>l.capabilities.includes(y)))),r.length===0){f.warn("No agents available for selection",{strategy:t,capabilities:n,healthyOnly:s,totalAgents:this.agents.size});return}let c;switch(t){case "random":c=this.selectRandom(r);break;case "round-robin":c=this.selectRoundRobin(r);break;case "least-connections":c=this.selectLeastConnections(r);break;default:c=this.selectRandom(r);}return f.debug("Agent selected",{agentId:c.id,strategy:t,connectionCount:c.connectionCount}),c}incrementConnection(e){let t=this.agents.get(e);t&&(t.connectionCount++,f.debug("Agent connection incremented",{agentId:e,connectionCount:t.connectionCount}));}decrementConnection(e){let t=this.agents.get(e);t&&t.connectionCount>0&&(t.connectionCount--,f.debug("Agent connection decremented",{agentId:e,connectionCount:t.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let e=Date.now(),{heartbeatTimeout:t,autoDeregisterTimeout:n}=this.config,s=[],r=0;for(let[c,l]of this.agents.entries()){let y=e-l.lastHeartbeat;if(y>n){s.push(c);continue}y>t&&l.status==="healthy"&&(l.status="unhealthy",r++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:c,lastHeartbeat:l.lastHeartbeat,timeSinceLastHeartbeat:y,timeout:t}));}for(let c of s){let l=this.agents.get(c);l&&(f.info("Auto-deregistering agent due to timeout",{agentId:c,name:l.name,lastHeartbeat:l.lastHeartbeat,timeout:n}),this.agents.delete(c));}(r>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:r,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(e){let t=Math.floor(Math.random()*e.length);return e[t]}selectRoundRobin(e){this.roundRobinIndex=this.roundRobinIndex%e.length;let t=e[this.roundRobinIndex];return this.roundRobinIndex++,t}selectLeastConnections(e){return e.reduce((t,n)=>n.connectionCount<t.connectionCount?n:t)}getStats(){let e=this.getAllAgents();return {totalAgents:e.length,healthyAgents:e.filter(t=>t.status==="healthy").length,unhealthyAgents:e.filter(t=>t.status==="unhealthy").length,offlineAgents:e.filter(t=>t.status==="offline").length,totalConnections:e.reduce((t,n)=>t+n.connectionCount,0)}}setAgentStatus(e,t){let n=this.agents.get(e);n&&(n.status=t);}setLastHeartbeat(e,t){let n=this.agents.get(e);n&&(n.lastHeartbeat=t);}};var h=a$1.create({service:"gateway:agent-sync-manager"}),T=class{constructor(e){a$2(this,"config");a$2(this,"registry");a$2(this,"localNodeId");a$2(this,"localNodeName");a$2(this,"remoteNodes",new Map);a$2(this,"remoteAgents",new Map);a$2(this,"syncTimer",null);a$2(this,"running",false);this.registry=e.registry,this.localNodeId=e.localNodeId,this.localNodeName=e.localNodeName,this.config={...$,...e.config};}async start(){if(this.running){h.warn("Agent sync manager is already running");return}h.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let e of this.config.remoteNodes)this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,h.info("Agent sync manager started");}async stop(){if(!this.running){h.warn("Agent sync manager is not running");return}h.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,h.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[e]of this.remoteNodes.entries())try{await this.pullFromNode(e);}catch(t){h.error("Failed to pull from node",{nodeId:e,error:t.message});}}async pullFromNode(e){let t=this.remoteNodes.get(e);if(!t)throw new Error(`Unknown remote node: ${e}`);t.status="syncing";let n=this.config.remoteNodes.find(s=>s.id===e);if(!n)throw new Error(`Remote node not found in config: ${e}`);h.debug("Pulling agent list from node",{nodeId:e,address:n.address});try{let s=`http://${n.address}:${n.port}/sync/agents`,r=await Fetch.get(s,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);let c=r.data.agents||[];for(let l of c)l.sourceGatewayId=e,this.remoteAgents.set(l.id,l);return t.lastSyncAt=Date.now(),t.status="synced",t.info.lastSyncAt=t.lastSyncAt,t.info.status="online",delete t.error,h.info("Pulled agent list from node",{nodeId:e,agentCount:c.length,lastSyncAt:t.lastSyncAt}),c}catch(s){throw t.status="error",t.error=s.message,t.info.status="offline",h.error("Failed to pull from node",{nodeId:e,error:s.message}),s}}async pushEvent(e){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let t=[];for(let[n]of this.remoteNodes.entries())t.push(this.pushToNode(n,e));await Promise.allSettled(t);}async pushToNode(e,t){let n=this.config.remoteNodes.find(s=>s.id===e);if(!n){h.warn("Unknown remote node for push",{nodeId:e});return}try{let s=`http://${n.address}:${n.port}/sync/events`,r=await Fetch.post(s,t,{headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!r.ok)throw new Error(`HTTP ${r.status}`);h.debug("Pushed event to node",{nodeId:e,eventType:t.type});}catch(s){h.error("Failed to push to node",{nodeId:e,eventType:t.type,error:s.message});}}async handleSyncMessage(e){switch(h.debug("Received sync message",{type:e.type,sourceNodeId:e.sourceNodeId}),e.type){case "agent_list_request":await this.handleAgentListRequest(e);break;case "agent_list_response":await this.handleAgentListResponse(e);break;case "agent_register":await this.handleAgentRegister(e);break;case "agent_deregister":await this.handleAgentDeregister(e);break;case "agent_heartbeat":await this.handleAgentHeartbeat(e);break;case "agent_status_change":await this.handleAgentStatusChange(e);break;default:h.warn("Unknown sync message type",{type:e.type});}}async handleAgentListRequest(e){let t=this.getLocalAgentsForSync(),n={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:e.requestId,agents:t,fullList:true,syncAt:Date.now()};await this.pushToNode(e.sourceNodeId,n);}async handleAgentListResponse(e){for(let t of e.agents)this.remoteAgents.set(t.id,t);h.info("Received agent list response",{sourceNodeId:e.sourceNodeId,agentCount:e.agents.length});}async handleAgentRegister(e){let{agent:t}=e,n=this.remoteAgents.get(t.id);if(n){let s=this.resolveConflict(n,t);this.remoteAgents.set(t.id,s);}else this.remoteAgents.set(t.id,t);h.info("Remote agent registered",{agentId:t.id,name:t.name,sourceNodeId:e.sourceNodeId});}async handleAgentDeregister(e){let{agentId:t}=e;this.remoteAgents.delete(t),h.info("Remote agent deregistered",{agentId:t,sourceNodeId:e.sourceNodeId});}async handleAgentHeartbeat(e){let{agentId:t,heartbeatAt:n,status:s}=e,r=this.remoteAgents.get(t);r&&(r.updatedAt=n,r.status=s),h.debug("Remote agent heartbeat received",{agentId:t,status:s,sourceNodeId:e.sourceNodeId});}async handleAgentStatusChange(e){let{agentId:t,newStatus:n,changedAt:s}=e,r=this.remoteAgents.get(t);r&&(r.status=n,r.updatedAt=s),h.info("Remote agent status changed",{agentId:t,newStatus:n,sourceNodeId:e.sourceNodeId});}resolveConflict(e,t){switch(this.config.conflictResolution){case "latest":return t.updatedAt>e.updatedAt?t:e;case "local":return e;case "remote":return t;default:return t.updatedAt>e.updatedAt?t:e}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(t=>({id:t.id,name:t.name,sourceGatewayId:this.localNodeId,address:t.address,capabilities:t.capabilities,status:t.status,updatedAt:t.lastHeartbeat,metadata:t.metadata}))}getMergedAgentList(){let e=new Map;for(let t of this.getLocalAgentsForSync())e.set(t.id,t);for(let[t,n]of this.remoteAgents.entries())e.has(t)||e.set(t,n);return Array.from(e.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let e=this.registry.getAllAgents(),t=0,n=0;for(let r of this.remoteNodes.values())r.info.status==="online"?t++:n++;let s=null;for(let r of this.remoteNodes.values())r.lastSyncAt>(s||0)&&(s=r.lastSyncAt);return {localAgentCount:e.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:e.length+this.remoteAgents.size,onlineNodeCount:t,offlineNodeCount:n,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(e){this.remoteNodes.set(e.id,{info:{id:e.id,name:e.id,address:e.address,port:e.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),h.info("Remote node added",{nodeId:e.id,address:e.address});}removeRemoteNode(e){this.remoteNodes.delete(e);for(let[t,n]of this.remoteAgents.entries())n.sourceGatewayId===e&&this.remoteAgents.delete(t);h.info("Remote node removed",{nodeId:e});}};var N=class{constructor(e){a$2(this,"log");a$2(this,"config");a$2(this,"ws",null);a$2(this,"state","disconnected");a$2(this,"subscriptions",new Map);a$2(this,"messageCallbacks",new Set);a$2(this,"agentListCallbacks",new Set);a$2(this,"cachedAgentList",[]);a$2(this,"localAgentList",[]);a$2(this,"reconnectAttempts",0);a$2(this,"reconnectTimer",null);a$2(this,"heartbeatTimer",null);a$2(this,"agentListRequestId",null);a$2(this,"agentListRequestResolve",null);this.config={url:e.url,type:e.type,id:e.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:e.reconnect?.enabled??true,maxAttempts:e.reconnect?.maxAttempts??5,delay:e.reconnect?.delay??3e3},heartbeat:{enabled:e.heartbeat?.enabled??true,interval:e.heartbeat?.interval??3e4}},this.log=a$1.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((e,t)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),e();},this.ws.onmessage=n=>{this.handleMessage(n.data);},this.ws.onclose=n=>{this.handleClose(n.code,n.reason);},this.ws.onerror=n=>{this.log.error("WebSocket error",{error:String(n)}),this.state==="connecting"&&t(new Error("Connection failed"));};}catch(n){this.state="disconnected",t(n);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(e,t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:e,backendSessionId:t,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:e,backendSessionId:t});}async unsubscribe(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:e,clientId:this.config.id}),this.subscriptions.delete(e),this.log.info("unsubscribed from session",{sessionId:e});}async send(e){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:e});}onMessage(e){this.messageCallbacks.add(e);}offMessage(e){this.messageCallbacks.delete(e);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(e){this.localAgentList=e,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((e,t)=>{let n=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=n,this.agentListRequestResolve=e,this.sendData({type:"agent_list_request",requestId:n}),setTimeout(()=>{this.agentListRequestId===n&&(this.agentListRequestId=null,this.agentListRequestResolve=null,t(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(e={}){let{localAgents:t,preferLocal:n=true,filterOffline:s=true}=e,r=t||this.localAgentList,c=this.cachedAgentList,l=this.mergeAgentLists(r,c,n);return s?l.filter(y=>y.status!=="offline"):l}onAgentListChange(e){this.agentListCallbacks.add(e);}offAgentListChange(e){this.agentListCallbacks.delete(e);}mergeAgentLists(e,t,n){let s=new Map,r=n?t:e,c=n?e:t;for(let l of r)s.set(l.id,l);for(let l of c)s.set(l.id,l);return Array.from(s.values())}updateMergedAgentList(){let e=this.getConnectableAgents({filterOffline:false});for(let t of this.agentListCallbacks)try{t(e);}catch(n){this.log.error("agent list callback error",{error:String(n)});}}handleAgentListResponse(e,t){t&&this.agentListRequestId===t&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(e),this.agentListRequestResolve=null),this.cachedAgentList=e,this.updateMergedAgentList(),this.log.debug("received agent list",{count:e.length});}sendData(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(e));}handleMessage(e){try{let t=JSON.parse(e);switch(t.type){case "message":this.handleGatewayMessage(t.message);break;case "subscribed":this.subscriptions.set(t.sessionId,t.subscription);break;case "unsubscribed":this.subscriptions.delete(t.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(t.agents||[],t.requestId);break;case "agent_update":this.handleAgentUpdate(t.agent,t.action);break;default:this.log.debug("unknown message type",{type:t.type});}}catch(t){this.log.error("failed to parse message",{error:String(t)});}}handleAgentUpdate(e,t){switch(t){case "add":case "update":{let n=this.cachedAgentList.findIndex(s=>s.id===e.id);n>=0?this.cachedAgentList[n]=e:this.cachedAgentList.push(e);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(n=>n.id!==e.id);break}this.updateMergedAgentList();}handleGatewayMessage(e){for(let t of this.messageCallbacks)try{t(e);}catch(n){this.log.error("message callback error",{error:String(n)});}}handleClose(e,t){this.log.info("connection closed",{code:e,reason:t}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let e=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:e}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(t){this.log.error("reconnect failed",{error:String(t)});}},e);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let e of this.subscriptions.keys())try{await this.subscribe(e);}catch(t){this.log.error("failed to resubscribe",{sessionId:e,error:String(t)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}async httpRequest(e,t={}){let n=`${this.getHttpUrl()}${e}`,s=await fetch(n,{...t,headers:{"Content-Type":"application/json",...t.headers}});if(!s.ok){let r=await s.text().catch(()=>"Unknown error");throw new Error(`HTTP ${s.status}: ${r}`)}return s.json()}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listContacts(e,t={}){let n=new URLSearchParams({platform:e,limit:String(t.limit??100),offset:String(t.offset??0)});return this.httpRequest(`/contacts?${n}`)}async getContact(e){return this.httpRequest(`/contacts/${encodeURIComponent(e)}`)}async listSessions(e={}){let t=new URLSearchParams({limit:String(e.limit??100),offset:String(e.offset??0)});return this.httpRequest(`/sessions?${t}`)}async getSession(e){return this.httpRequest(`/sessions/${encodeURIComponent(e)}`)}async createSession(e){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(e??{})})}async sendMessage(e,t){return this.httpRequest(`/session/${encodeURIComponent(e)}/prompt`,{method:"POST",body:JSON.stringify(t)})}};async function Ut(i){let{Log:e}=await import('./chunks/log-MKRLBH4R.mjs'),t=false;await e.init({logDir:i.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:i.print??false,dev:i.dev??t,level:i.level??("INFO")});}
2
+ export{M as AgentRegistry,T as AgentSyncManager,x as Gateway,N as GatewayClient,Ut as initLog};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.2.22",
3
+ "version": "0.2.24",
4
4
  "description": "EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - 支持 WebSocket、HTTP、Discord、Telegram、Slack 等多渠道集成",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -48,34 +48,35 @@
48
48
  "LICENSE"
49
49
  ],
50
50
  "dependencies": {
51
+ "@ai-sdk/anthropic": "^3.0.76",
52
+ "@ai-sdk/openai-compatible": "^2.0.47",
51
53
  "@ai-sdk/provider": "^3.0.10",
52
54
  "@ai-sdk/provider-utils": "^4.0.27",
53
- "@ai-sdk/openai-compatible": "^2.0.47",
54
- "@ai-sdk/anthropic": "^3.0.76",
55
55
  "@hono/node-server": "^2.0.2",
56
56
  "@hono/node-ws": "^1.3.0",
57
57
  "@hono/standard-validator": "^0.2.2",
58
58
  "@hono/zod-validator": "^0.7.6",
59
+ "ai": "^6.0.176",
60
+ "better-sqlite3": "^12.9.0",
59
61
  "commander": "^14.0.3",
60
- "zod": "^4.4.3",
61
62
  "hono": "^4.12.18",
62
63
  "hono-openapi": "^1.3.0",
63
- "ws": "^8.20.0",
64
- "ai": "^6.0.176",
65
- "better-sqlite3": "^12.9.0",
66
64
  "jieba-wasm": "^2.4.0",
67
- "xdg-basedir": "^5.1.0",
68
65
  "minimatch": "^10.2.5",
69
- "@easbot/plugin": "0.2.22",
70
- "@easbot/sdk": "0.2.22",
71
- "@easbot/types": "0.2.22",
72
- "@easbot/utils": "0.2.22"
66
+ "undici": "^8.3.0",
67
+ "ws": "^8.20.0",
68
+ "xdg-basedir": "^5.1.0",
69
+ "zod": "^4.4.3",
70
+ "@easbot/plugin": "0.2.24",
71
+ "@easbot/sdk": "0.2.24",
72
+ "@easbot/types": "0.2.24",
73
+ "@easbot/utils": "0.2.24"
73
74
  },
74
75
  "devDependencies": {
75
76
  "@biomejs/biome": "^2.4.14",
76
77
  "@types/better-sqlite3": "^7.6.13",
77
- "@types/ws": "^8.18.1",
78
78
  "@types/node": "^25.6.2",
79
+ "@types/ws": "^8.18.1",
79
80
  "@vitest/coverage-v8": "^4.1.5",
80
81
  "dotenv": "^17.4.2",
81
82
  "tsup": "^8.5.1",
@@ -1,7 +0,0 @@
1
- 'use strict';var chunkGY3SWWW3_cjs=require('./chunk-GY3SWWW3.cjs'),qi=require('path'),oh=require('fs/promises'),Rn=require('fs'),lo=require('zod'),url=require('url'),events=require('events'),Pr=require('stream'),string_decoder=require('string_decoder'),utils=require('@easbot/utils');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var qi__default=/*#__PURE__*/_interopDefault(qi);var oh__default=/*#__PURE__*/_interopDefault(oh);var Rn__namespace=/*#__PURE__*/_interopNamespace(Rn);var lo__default=/*#__PURE__*/_interopDefault(lo);var Pr__default=/*#__PURE__*/_interopDefault(Pr);var mr=(e,t,i)=>{let s=e instanceof RegExp?ks(e,i):e,h=t instanceof RegExp?ks(t,i):t,n=s!==null&&h!=null&&uh(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},ks=(e,t)=>{let i=t.match(e);return i?i[0]:null},uh=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},wr="\0SLASH"+Math.random()+"\0",yr="\0OPEN"+Math.random()+"\0",ys="\0CLOSE"+Math.random()+"\0",br="\0COMMA"+Math.random()+"\0",Sr="\0PERIOD"+Math.random()+"\0",ph=new RegExp(wr,"g"),fh=new RegExp(yr,"g"),dh=new RegExp(ys,"g"),gh=new RegExp(br,"g"),mh=new RegExp(Sr,"g"),wh=/\\\\/g,yh=/\\{/g,bh=/\\}/g,Sh=/\\,/g,vh=/\\./g,Eh=1e5;function Ki(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function xh(e){return e.replace(wh,wr).replace(yh,yr).replace(bh,ys).replace(Sh,br).replace(vh,Sr)}function kh(e){return e.replace(ph,"\\").replace(fh,"{").replace(dh,"}").replace(gh,",").replace(mh,".")}function vr(e){if(!e)return [""];let t=[],i=mr("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=vr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Rh(e,t={}){if(!e)return [];let{max:i=Eh}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Je(xh(e),i,true).map(kh)}function Ch(e){return "{"+e+"}"}function Oh(e){return /^-?0\d/.test(e)}function Ah(e,t){return e<=t}function Fh(e,t){return e>=t}function Je(e,t,i){let s=[],h=mr("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?Je(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+ys+h.post,Je(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=vr(h.body),f.length===1&&f[0]!==void 0&&(f=Je(f[0],t,false).map(Ch),f.length===1))return o.map(S=>h.pre+f[0]+S);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let S=Ki(f[0]),E=Ki(f[1]),b=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Ki(f[2])):1,v=Ah;E<S&&(x*=-1,v=Fh);let R=f.some(Oh);w=[];for(let A=S;v(A,E);A+=x){let T;if(l)T=String.fromCharCode(A),T==="\\"&&(T="");else if(T=String(A),R){let L=b-T.length;if(L>0){let F=new Array(L+1).join("0");A<0?T="-"+F+T.slice(1):T=F+T;}}w.push(T);}}else {w=[];for(let S=0;S<f.length;S++)w.push.apply(w,Je(f[S],t,false));}for(let S=0;S<w.length;S++)for(let E=0;E<o.length&&s.length<t;E++){let b=n+w[S]+o[E];(!i||u||b)&&s.push(b);}}return s}var $i=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Th={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},$e=e=>e.replace(/[[\]\\-]/g,"\\$&"),Lh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Rs=e=>e.join(""),Mh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let E=e.charAt(n);if((E==="!"||E==="^")&&n===i+1){u=true,n++;continue}if(E==="]"&&o&&!l){d=n+1;break}if(o=true,E==="\\"&&!l){l=true,n++;continue}if(E==="["&&!l){for(let[b,[x,v,R]]of Object.entries(Th))if(e.startsWith(b,n)){if(f)return ["$.",false,e.length-i,true];n+=b.length,R?h.push(x):s.push(x),a=a||v;continue t}}if(l=false,f){E>f?s.push($e(f)+"-"+$e(E)):E===f&&s.push($e(E)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push($e(E+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=E,n+=2;continue}s.push($e(E)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let E=s[0].length===2?s[0].slice(-1):s[0];return [Lh(E),false,d-i,false]}let w="["+(u?"^":"")+Rs(s)+"]",S="["+(u?"":"^")+Rs(h)+"]";return [s.length&&h.length?"("+w+"|"+S+")":s.length?w:S,a,d-i,true]},Ce=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),Wh=new Set(["!","?","+","*","@"]),Cs=e=>Wh.has(e),Ph="(?!(?:^|/)\\.\\.?(?:$|/))",ki="(?!\\.)",Dh=new Set(["[","."]),jh=new Set(["..","."]),Nh=new Set("().*{}+?[]^$\\!"),zh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bs="[^/]",Os=bs+"*?",As=bs+"+?",U,V,$t,P,_,Qt,ue,te,Pt,pe,Qe,ve,xr,ne,X,Mi,rs,kr,Er=(X=class{constructor(t,i,s={}){chunkGY3SWWW3_cjs.c(this,ve);chunkGY3SWWW3_cjs.a(this,"type");chunkGY3SWWW3_cjs.c(this,U);chunkGY3SWWW3_cjs.c(this,V);chunkGY3SWWW3_cjs.c(this,$t,false);chunkGY3SWWW3_cjs.c(this,P,[]);chunkGY3SWWW3_cjs.c(this,_);chunkGY3SWWW3_cjs.c(this,Qt);chunkGY3SWWW3_cjs.c(this,ue);chunkGY3SWWW3_cjs.c(this,te,false);chunkGY3SWWW3_cjs.c(this,Pt);chunkGY3SWWW3_cjs.c(this,pe);chunkGY3SWWW3_cjs.c(this,Qe,false);this.type=t,t&&chunkGY3SWWW3_cjs.d(this,V,true),chunkGY3SWWW3_cjs.d(this,_,i),chunkGY3SWWW3_cjs.d(this,U,chunkGY3SWWW3_cjs.b(this,_)?chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,_),U):this),chunkGY3SWWW3_cjs.d(this,Pt,chunkGY3SWWW3_cjs.b(this,U)===this?s:chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,U),Pt)),chunkGY3SWWW3_cjs.d(this,ue,chunkGY3SWWW3_cjs.b(this,U)===this?[]:chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,U),ue)),t==="!"&&!chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,U),te)&&chunkGY3SWWW3_cjs.b(this,ue).push(this),chunkGY3SWWW3_cjs.d(this,Qt,chunkGY3SWWW3_cjs.b(this,_)?chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,_),P).length:0);}get hasMagic(){if(chunkGY3SWWW3_cjs.b(this,V)!==void 0)return chunkGY3SWWW3_cjs.b(this,V);for(let t of chunkGY3SWWW3_cjs.b(this,P))if(typeof t!="string"&&(t.type||t.hasMagic))return chunkGY3SWWW3_cjs.d(this,V,true);return chunkGY3SWWW3_cjs.b(this,V)}toString(){return chunkGY3SWWW3_cjs.b(this,pe)!==void 0?chunkGY3SWWW3_cjs.b(this,pe):this.type?chunkGY3SWWW3_cjs.d(this,pe,this.type+"("+chunkGY3SWWW3_cjs.b(this,P).map(t=>String(t)).join("|")+")"):chunkGY3SWWW3_cjs.d(this,pe,chunkGY3SWWW3_cjs.b(this,P).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof X&&chunkGY3SWWW3_cjs.b(i,_)===this))throw new Error("invalid part: "+i);chunkGY3SWWW3_cjs.b(this,P).push(i);}}toJSON(){let t=this.type===null?chunkGY3SWWW3_cjs.b(this,P).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...chunkGY3SWWW3_cjs.b(this,P).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===chunkGY3SWWW3_cjs.b(this,U)||chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,U),te)&&chunkGY3SWWW3_cjs.b(this,_)?.type==="!")&&t.push({}),t}isStart(){if(chunkGY3SWWW3_cjs.b(this,U)===this)return true;if(!chunkGY3SWWW3_cjs.b(this,_)?.isStart())return false;if(chunkGY3SWWW3_cjs.b(this,Qt)===0)return true;let t=chunkGY3SWWW3_cjs.b(this,_);for(let i=0;i<chunkGY3SWWW3_cjs.b(this,Qt);i++){let s=chunkGY3SWWW3_cjs.b(t,P)[i];if(!(s instanceof X&&s.type==="!"))return false}return true}isEnd(){if(chunkGY3SWWW3_cjs.b(this,U)===this||chunkGY3SWWW3_cjs.b(this,_)?.type==="!")return true;if(!chunkGY3SWWW3_cjs.b(this,_)?.isEnd())return false;if(!this.type)return chunkGY3SWWW3_cjs.b(this,_)?.isEnd();let t=chunkGY3SWWW3_cjs.b(this,_)?chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,_),P).length:0;return chunkGY3SWWW3_cjs.b(this,Qt)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new X(this.type,t);for(let s of chunkGY3SWWW3_cjs.b(this,P))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new X(null,void 0,i);return chunkGY3SWWW3_cjs.e(h=X,ne,Mi).call(h,t,s,0,i),s}toMMPattern(){if(this!==chunkGY3SWWW3_cjs.b(this,U))return chunkGY3SWWW3_cjs.b(this,U).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||chunkGY3SWWW3_cjs.b(this,V)||chunkGY3SWWW3_cjs.b(this,Pt).nocase&&!chunkGY3SWWW3_cjs.b(this,Pt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(chunkGY3SWWW3_cjs.b(this,Pt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return chunkGY3SWWW3_cjs.b(this,Pt)}toRegExpSource(t){let i=t??!!chunkGY3SWWW3_cjs.b(this,Pt).dot;if(chunkGY3SWWW3_cjs.b(this,U)===this&&chunkGY3SWWW3_cjs.e(this,ve,xr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!chunkGY3SWWW3_cjs.b(this,P).some(w=>typeof w!="string"),u=chunkGY3SWWW3_cjs.b(this,P).map(w=>{var v;let[S,E,b,x]=typeof w=="string"?chunkGY3SWWW3_cjs.e(v=X,ne,kr).call(v,w,chunkGY3SWWW3_cjs.b(this,V),l):w.toRegExpSource(t);return chunkGY3SWWW3_cjs.d(this,V,chunkGY3SWWW3_cjs.b(this,V)||b),chunkGY3SWWW3_cjs.d(this,$t,chunkGY3SWWW3_cjs.b(this,$t)||x),S}).join(""),d="";if(this.isStart()&&typeof chunkGY3SWWW3_cjs.b(this,P)[0]=="string"&&!(chunkGY3SWWW3_cjs.b(this,P).length===1&&jh.has(chunkGY3SWWW3_cjs.b(this,P)[0]))){let w=Dh,S=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),E=!i&&!t&&w.has(u.charAt(0));d=S?Ph:E?ki:"";}let f="";return this.isEnd()&&chunkGY3SWWW3_cjs.b(chunkGY3SWWW3_cjs.b(this,U),te)&&chunkGY3SWWW3_cjs.b(this,_)?.type==="!"&&(f="(?:$|\\/)"),[d+u+f,Ce(u),chunkGY3SWWW3_cjs.d(this,V,!!chunkGY3SWWW3_cjs.b(this,V)),chunkGY3SWWW3_cjs.b(this,$t)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=chunkGY3SWWW3_cjs.e(this,ve,rs).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return chunkGY3SWWW3_cjs.d(this,P,[l]),this.type=null,chunkGY3SWWW3_cjs.d(this,V,void 0),[l,Ce(this.toString()),false,false]}let o=!s||t||i||!ki?"":chunkGY3SWWW3_cjs.e(this,ve,rs).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&chunkGY3SWWW3_cjs.b(this,Qe))a=(this.isStart()&&!i?ki:"")+As;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?ki:"")+Os+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Ce(n),chunkGY3SWWW3_cjs.d(this,V,!!chunkGY3SWWW3_cjs.b(this,V)),chunkGY3SWWW3_cjs.b(this,$t)]}},U=new WeakMap,V=new WeakMap,$t=new WeakMap,P=new WeakMap,_=new WeakMap,Qt=new WeakMap,ue=new WeakMap,te=new WeakMap,Pt=new WeakMap,pe=new WeakMap,Qe=new WeakMap,ve=new WeakSet,xr=function(){if(this!==chunkGY3SWWW3_cjs.b(this,U))throw new Error("should only call on root");if(chunkGY3SWWW3_cjs.b(this,te))return this;this.toString(),chunkGY3SWWW3_cjs.d(this,te,true);let t;for(;t=chunkGY3SWWW3_cjs.b(this,ue).pop();){if(t.type!=="!")continue;let i=t,s=chunkGY3SWWW3_cjs.b(i,_);for(;s;){for(let h=chunkGY3SWWW3_cjs.b(i,Qt)+1;!s.type&&h<chunkGY3SWWW3_cjs.b(s,P).length;h++)for(let n of chunkGY3SWWW3_cjs.b(t,P)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(chunkGY3SWWW3_cjs.b(s,P)[h]);}i=s,s=chunkGY3SWWW3_cjs.b(i,_);}}return this},ne=new WeakSet,Mi=function(t,i,s,h){var S,E;let n=false,o=false,a=-1,l=false;if(i.type===null){let b=s,x="";for(;b<t.length;){let v=t.charAt(b++);if(n||v==="\\"){n=!n,x+=v;continue}if(o){b===a+1?(v==="^"||v==="!")&&(l=true):v==="]"&&!(b===a+2&&l)&&(o=false),x+=v;continue}else if(v==="["){o=true,a=b,l=false,x+=v;continue}if(!h.noext&&Cs(v)&&t.charAt(b)==="("){i.push(x),x="";let R=new X(v,i);b=chunkGY3SWWW3_cjs.e(S=X,ne,Mi).call(S,t,R,b,h),i.push(R);continue}x+=v;}return i.push(x),b}let u=s+1,d=new X(null,i),f=[],w="";for(;u<t.length;){let b=t.charAt(u++);if(n||b==="\\"){n=!n,w+=b;continue}if(o){u===a+1?(b==="^"||b==="!")&&(l=true):b==="]"&&!(u===a+2&&l)&&(o=false),w+=b;continue}else if(b==="["){o=true,a=u,l=false,w+=b;continue}if(Cs(b)&&t.charAt(u)==="("){d.push(w),w="";let x=new X(b,d);d.push(x),u=chunkGY3SWWW3_cjs.e(E=X,ne,Mi).call(E,t,x,u,h);continue}if(b==="|"){d.push(w),w="",f.push(d),d=new X(null,i);continue}if(b===")")return w===""&&chunkGY3SWWW3_cjs.b(i,P).length===0&&chunkGY3SWWW3_cjs.d(i,Qe,true),d.push(w),w="",i.push(...f,d),u;w+=b;}return i.type=null,chunkGY3SWWW3_cjs.d(i,V,void 0),chunkGY3SWWW3_cjs.d(i,P,[t.substring(s-1)]),u},rs=function(t){return chunkGY3SWWW3_cjs.b(this,P).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return chunkGY3SWWW3_cjs.d(this,$t,chunkGY3SWWW3_cjs.b(this,$t)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},kr=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(Nh.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?As:Os,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,S]=Mh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||S;continue}}if(u==="?"){n+=bs,i=true;continue}n+=zh(u);}return [n,Ce(t),!!i,o]},chunkGY3SWWW3_cjs.c(X,ne),X),Rr=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),nt=(e,t,i={})=>($i(t),!i.nocomment&&t.charAt(0)==="#"?false:new oe(t,i).match(e)),_h=/^\*+([^+@!?\*\[\(]*)$/,$h=e=>t=>!t.startsWith(".")&&t.endsWith(e),Bh=e=>t=>t.endsWith(e),Uh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),Gh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Ih=/^\*+\.\*+$/,Hh=e=>!e.startsWith(".")&&e.includes("."),Jh=e=>e!=="."&&e!==".."&&e.includes("."),qh=/^\.\*+$/,Zh=e=>e!=="."&&e!==".."&&e.startsWith("."),Vh=/^\*+$/,Kh=e=>e.length!==0&&!e.startsWith("."),Yh=e=>e.length!==0&&e!=="."&&e!=="..",Xh=/^\?+([^+@!?\*\[\(]*)?$/,Qh=([e,t=""])=>{let i=Cr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},tn=([e,t=""])=>{let i=Or([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},en=([e,t=""])=>{let i=Or([e]);return t?s=>i(s)&&s.endsWith(t):i},sn=([e,t=""])=>{let i=Cr([e]);return t?s=>i(s)&&s.endsWith(t):i},Cr=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Or=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Ar=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Fs={win32:{sep:"\\"},posix:{sep:"/"}},rn=Ar==="win32"?Fs.win32.sep:Fs.posix.sep;nt.sep=rn;var ht=Symbol("globstar **");nt.GLOBSTAR=ht;var hn="[^/]",nn=hn+"*?",on="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",an="(?:(?!(?:\\/|^)\\.).)*?",ln=(e,t={})=>i=>nt(i,e,t);nt.filter=ln;var mt=(e,t={})=>Object.assign({},e,t),cn=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return nt;let t=nt;return Object.assign((i,s,h={})=>t(i,s,mt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,mt(e,s));}static defaults(i){return t.defaults(mt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,mt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,mt(e,s))}},unescape:(i,s={})=>t.unescape(i,mt(e,s)),escape:(i,s={})=>t.escape(i,mt(e,s)),filter:(i,s={})=>t.filter(i,mt(e,s)),defaults:i=>t.defaults(mt(e,i)),makeRe:(i,s={})=>t.makeRe(i,mt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,mt(e,s)),match:(i,s,h={})=>t.match(i,s,mt(e,h)),sep:t.sep,GLOBSTAR:ht})};nt.defaults=cn;var Fr=(e,t={})=>($i(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Rh(e,{max:t.braceExpandMax}));nt.braceExpand=Fr;var un=(e,t={})=>new oe(e,t).makeRe();nt.makeRe=un;var pn=(e,t,i={})=>{let s=new oe(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};nt.match=pn;var Ts=/[?*]|[+@!]\(.*?\)|\[|\]/,fn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),oe=class{constructor(e,t={}){chunkGY3SWWW3_cjs.a(this,"options");chunkGY3SWWW3_cjs.a(this,"set");chunkGY3SWWW3_cjs.a(this,"pattern");chunkGY3SWWW3_cjs.a(this,"windowsPathsNoEscape");chunkGY3SWWW3_cjs.a(this,"nonegate");chunkGY3SWWW3_cjs.a(this,"negate");chunkGY3SWWW3_cjs.a(this,"comment");chunkGY3SWWW3_cjs.a(this,"empty");chunkGY3SWWW3_cjs.a(this,"preserveMultipleSlashes");chunkGY3SWWW3_cjs.a(this,"partial");chunkGY3SWWW3_cjs.a(this,"globSet");chunkGY3SWWW3_cjs.a(this,"globParts");chunkGY3SWWW3_cjs.a(this,"nocase");chunkGY3SWWW3_cjs.a(this,"isWindows");chunkGY3SWWW3_cjs.a(this,"platform");chunkGY3SWWW3_cjs.a(this,"windowsNoMagicRoot");chunkGY3SWWW3_cjs.a(this,"regexp");$i(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Ar,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ts.test(h[2]))&&!Ts.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let E=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!E&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),v=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),R=b?3:E?0:void 0,A=v?3:x?0:void 0;if(typeof R=="number"&&typeof A=="number"){let[T,L]=[e[R],t[A]];T.toLowerCase()===L.toLowerCase()&&(t[A]=T,A>R?t=t.slice(A):R>A&&(e=e.slice(R)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===ht){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var S=e[f];if(this.debug(`
2
- globstar while`,e,f,t,w,S),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,S),true;if(S==="."||S===".."||!s.dot&&S.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
3
- >>> no match, partial?`,e,f,t,w),f===a))}let E;if(typeof u=="string"?(E=d===u,this.debug("string match",u,d,E)):(E=u.test(d),this.debug("pattern match",u,d,E)),!E)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Fr(this.pattern,this.options)}parse(e){$i(e);let t=this.options;if(e==="**")return ht;if(e==="")return "";let i,s=null;(i=e.match(Vh))?s=t.dot?Yh:Kh:(i=e.match(_h))?s=(t.nocase?t.dot?Gh:Uh:t.dot?Bh:$h)(i[1]):(i=e.match(Xh))?s=(t.nocase?t.dot?tn:Qh:t.dot?en:sn)(i):(i=e.match(Ih))?s=t.dot?Jh:Hh:(i=e.match(qh))&&(s=Zh);let h=Er.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?nn:t.dot?on:an,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?fn(d):d===ht?ht:d._src});l.forEach((d,f)=>{let w=l[f+1],S=l[f-1];d!==ht||S===ht||(S===void 0?w!==void 0&&w!==ht?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=S+"(?:\\/|\\/"+i+")?":w!==ht&&(l[f-1]=S+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=ht));});let u=l.filter(d=>d!==ht);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return nt.defaults(e).Minimatch}};nt.AST=Er;nt.Minimatch=oe;nt.escape=Rr;nt.unescape=Ce;var gn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Tr=new Set,hs=typeof process=="object"&&process?process:{},Lr=(e,t,i,s)=>{typeof hs.emitWarning=="function"?hs.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Bi=globalThis.AbortController,Ls=globalThis.AbortSignal;if(typeof Bi>"u"){Ls=class{constructor(){chunkGY3SWWW3_cjs.a(this,"onabort");chunkGY3SWWW3_cjs.a(this,"_onabort",[]);chunkGY3SWWW3_cjs.a(this,"reason");chunkGY3SWWW3_cjs.a(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Bi=class{constructor(){chunkGY3SWWW3_cjs.a(this,"signal",new Ls);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e=hs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Lr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var mn=e=>!Tr.has(e),Vt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Mr=e=>Vt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Wi:null:null,Wi=class extends Array{constructor(e){super(e),this.fill(0);}},Nt,Oe,wn=(Nt=class{constructor(t,i){chunkGY3SWWW3_cjs.a(this,"heap");chunkGY3SWWW3_cjs.a(this,"length");if(!chunkGY3SWWW3_cjs.b(Nt,Oe))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=Mr(t);if(!i)return [];chunkGY3SWWW3_cjs.d(Nt,Oe,true);let s=new Nt(t,i);return chunkGY3SWWW3_cjs.d(Nt,Oe,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Oe=new WeakMap,chunkGY3SWWW3_cjs.c(Nt,Oe,false),Nt),Js,qs,yt,ut,xt,fe,kt,Ae,Fe,Rt,G,Ct,$,D,O,it,pt,tt,K,Ot,Y,At,Ft,ft,dt,Tt,ee,st,Te,y,ns,de,Bt,ti,gt,Wr,ge,Le,ei,Kt,Yt,os,Pi,Di,W,as,qe,Xt,ls,Me,Ii=(Me=class{constructor(t){chunkGY3SWWW3_cjs.c(this,y);chunkGY3SWWW3_cjs.c(this,yt);chunkGY3SWWW3_cjs.c(this,ut);chunkGY3SWWW3_cjs.c(this,xt);chunkGY3SWWW3_cjs.c(this,fe);chunkGY3SWWW3_cjs.c(this,kt);chunkGY3SWWW3_cjs.c(this,Ae);chunkGY3SWWW3_cjs.c(this,Fe);chunkGY3SWWW3_cjs.c(this,Rt);chunkGY3SWWW3_cjs.a(this,"ttl");chunkGY3SWWW3_cjs.a(this,"ttlResolution");chunkGY3SWWW3_cjs.a(this,"ttlAutopurge");chunkGY3SWWW3_cjs.a(this,"updateAgeOnGet");chunkGY3SWWW3_cjs.a(this,"updateAgeOnHas");chunkGY3SWWW3_cjs.a(this,"allowStale");chunkGY3SWWW3_cjs.a(this,"noDisposeOnSet");chunkGY3SWWW3_cjs.a(this,"noUpdateTTL");chunkGY3SWWW3_cjs.a(this,"maxEntrySize");chunkGY3SWWW3_cjs.a(this,"sizeCalculation");chunkGY3SWWW3_cjs.a(this,"noDeleteOnFetchRejection");chunkGY3SWWW3_cjs.a(this,"noDeleteOnStaleGet");chunkGY3SWWW3_cjs.a(this,"allowStaleOnFetchAbort");chunkGY3SWWW3_cjs.a(this,"allowStaleOnFetchRejection");chunkGY3SWWW3_cjs.a(this,"ignoreFetchAbort");chunkGY3SWWW3_cjs.c(this,G);chunkGY3SWWW3_cjs.c(this,Ct);chunkGY3SWWW3_cjs.c(this,$);chunkGY3SWWW3_cjs.c(this,D);chunkGY3SWWW3_cjs.c(this,O);chunkGY3SWWW3_cjs.c(this,it);chunkGY3SWWW3_cjs.c(this,pt);chunkGY3SWWW3_cjs.c(this,tt);chunkGY3SWWW3_cjs.c(this,K);chunkGY3SWWW3_cjs.c(this,Ot);chunkGY3SWWW3_cjs.c(this,Y);chunkGY3SWWW3_cjs.c(this,At);chunkGY3SWWW3_cjs.c(this,Ft);chunkGY3SWWW3_cjs.c(this,ft);chunkGY3SWWW3_cjs.c(this,dt);chunkGY3SWWW3_cjs.c(this,Tt);chunkGY3SWWW3_cjs.c(this,ee);chunkGY3SWWW3_cjs.c(this,st);chunkGY3SWWW3_cjs.c(this,Te);chunkGY3SWWW3_cjs.c(this,de,()=>{});chunkGY3SWWW3_cjs.c(this,Bt,()=>{});chunkGY3SWWW3_cjs.c(this,ti,()=>{});chunkGY3SWWW3_cjs.c(this,gt,()=>false);chunkGY3SWWW3_cjs.c(this,ge,t=>{});chunkGY3SWWW3_cjs.c(this,Le,(t,i,s)=>{});chunkGY3SWWW3_cjs.c(this,ei,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});chunkGY3SWWW3_cjs.a(this,Js,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:u,onInsert:d,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:S,maxSize:E=0,maxEntrySize:b=0,sizeCalculation:x,fetchMethod:v,memoMethod:R,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:F,ignoreFetchAbort:j,perf:N}=t;if(N!==void 0&&typeof N?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(chunkGY3SWWW3_cjs.d(this,Rt,N??gn),i!==0&&!Vt(i))throw new TypeError("max option must be a nonnegative integer");let B=i?Mr(i):Array;if(!B)throw new Error("invalid max value: "+i);if(chunkGY3SWWW3_cjs.d(this,yt,i),chunkGY3SWWW3_cjs.d(this,ut,E),this.maxEntrySize=b||chunkGY3SWWW3_cjs.b(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!chunkGY3SWWW3_cjs.b(this,ut)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(R!==void 0&&typeof R!="function")throw new TypeError("memoMethod must be a function if defined");if(chunkGY3SWWW3_cjs.d(this,Fe,R),v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(chunkGY3SWWW3_cjs.d(this,Ae,v),chunkGY3SWWW3_cjs.d(this,ee,!!v),chunkGY3SWWW3_cjs.d(this,$,new Map),chunkGY3SWWW3_cjs.d(this,D,new Array(i).fill(void 0)),chunkGY3SWWW3_cjs.d(this,O,new Array(i).fill(void 0)),chunkGY3SWWW3_cjs.d(this,it,new B(i)),chunkGY3SWWW3_cjs.d(this,pt,new B(i)),chunkGY3SWWW3_cjs.d(this,tt,0),chunkGY3SWWW3_cjs.d(this,K,0),chunkGY3SWWW3_cjs.d(this,Ot,wn.create(i)),chunkGY3SWWW3_cjs.d(this,G,0),chunkGY3SWWW3_cjs.d(this,Ct,0),typeof u=="function"&&chunkGY3SWWW3_cjs.d(this,xt,u),typeof d=="function"&&chunkGY3SWWW3_cjs.d(this,fe,d),typeof f=="function"?(chunkGY3SWWW3_cjs.d(this,kt,f),chunkGY3SWWW3_cjs.d(this,Y,[])):(chunkGY3SWWW3_cjs.d(this,kt,void 0),chunkGY3SWWW3_cjs.d(this,Y,void 0)),chunkGY3SWWW3_cjs.d(this,Tt,!!chunkGY3SWWW3_cjs.b(this,xt)),chunkGY3SWWW3_cjs.d(this,Te,!!chunkGY3SWWW3_cjs.b(this,fe)),chunkGY3SWWW3_cjs.d(this,st,!!chunkGY3SWWW3_cjs.b(this,kt)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!F,this.ignoreFetchAbort=!!j,this.maxEntrySize!==0){if(chunkGY3SWWW3_cjs.b(this,ut)!==0&&!Vt(chunkGY3SWWW3_cjs.b(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Vt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");chunkGY3SWWW3_cjs.e(this,y,Wr).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Vt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Vt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");chunkGY3SWWW3_cjs.e(this,y,ns).call(this);}if(chunkGY3SWWW3_cjs.b(this,yt)===0&&this.ttl===0&&chunkGY3SWWW3_cjs.b(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!chunkGY3SWWW3_cjs.b(this,yt)&&!chunkGY3SWWW3_cjs.b(this,ut)){let M="LRU_CACHE_UNBOUNDED";mn(M)&&(Tr.add(M),Lr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",M,Me));}}get perf(){return chunkGY3SWWW3_cjs.b(this,Rt)}static unsafeExposeInternals(t){return {starts:chunkGY3SWWW3_cjs.b(t,Ft),ttls:chunkGY3SWWW3_cjs.b(t,ft),autopurgeTimers:chunkGY3SWWW3_cjs.b(t,dt),sizes:chunkGY3SWWW3_cjs.b(t,At),keyMap:chunkGY3SWWW3_cjs.b(t,$),keyList:chunkGY3SWWW3_cjs.b(t,D),valList:chunkGY3SWWW3_cjs.b(t,O),next:chunkGY3SWWW3_cjs.b(t,it),prev:chunkGY3SWWW3_cjs.b(t,pt),get head(){return chunkGY3SWWW3_cjs.b(t,tt)},get tail(){return chunkGY3SWWW3_cjs.b(t,K)},free:chunkGY3SWWW3_cjs.b(t,Ot),isBackgroundFetch:i=>{var s;return chunkGY3SWWW3_cjs.e(s=t,y,W).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return chunkGY3SWWW3_cjs.e(o=t,y,Di).call(o,i,s,h,n)},moveToTail:i=>{var s;return chunkGY3SWWW3_cjs.e(s=t,y,qe).call(s,i)},indexes:i=>{var s;return chunkGY3SWWW3_cjs.e(s=t,y,Kt).call(s,i)},rindexes:i=>{var s;return chunkGY3SWWW3_cjs.e(s=t,y,Yt).call(s,i)},isStale:i=>{var s;return chunkGY3SWWW3_cjs.b(s=t,gt).call(s,i)}}}get max(){return chunkGY3SWWW3_cjs.b(this,yt)}get maxSize(){return chunkGY3SWWW3_cjs.b(this,ut)}get calculatedSize(){return chunkGY3SWWW3_cjs.b(this,Ct)}get size(){return chunkGY3SWWW3_cjs.b(this,G)}get fetchMethod(){return chunkGY3SWWW3_cjs.b(this,Ae)}get memoMethod(){return chunkGY3SWWW3_cjs.b(this,Fe)}get dispose(){return chunkGY3SWWW3_cjs.b(this,xt)}get onInsert(){return chunkGY3SWWW3_cjs.b(this,fe)}get disposeAfter(){return chunkGY3SWWW3_cjs.b(this,kt)}getRemainingTTL(t){return chunkGY3SWWW3_cjs.b(this,$).has(t)?1/0:0}*entries(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this))chunkGY3SWWW3_cjs.b(this,O)[t]!==void 0&&chunkGY3SWWW3_cjs.b(this,D)[t]!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield [chunkGY3SWWW3_cjs.b(this,D)[t],chunkGY3SWWW3_cjs.b(this,O)[t]]);}*rentries(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this))chunkGY3SWWW3_cjs.b(this,O)[t]!==void 0&&chunkGY3SWWW3_cjs.b(this,D)[t]!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield [chunkGY3SWWW3_cjs.b(this,D)[t],chunkGY3SWWW3_cjs.b(this,O)[t]]);}*keys(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this)){let i=chunkGY3SWWW3_cjs.b(this,D)[t];i!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield i);}}*rkeys(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this)){let i=chunkGY3SWWW3_cjs.b(this,D)[t];i!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield i);}}*values(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this))chunkGY3SWWW3_cjs.b(this,O)[t]!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield chunkGY3SWWW3_cjs.b(this,O)[t]);}*rvalues(){for(let t of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this))chunkGY3SWWW3_cjs.b(this,O)[t]!==void 0&&!chunkGY3SWWW3_cjs.e(this,y,W).call(this,chunkGY3SWWW3_cjs.b(this,O)[t])&&(yield chunkGY3SWWW3_cjs.b(this,O)[t]);}[(qs=Symbol.iterator,Js=Symbol.toStringTag,qs)](){return this.entries()}find(t,i={}){for(let s of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this)){let h=chunkGY3SWWW3_cjs.b(this,O)[s],n=chunkGY3SWWW3_cjs.e(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,chunkGY3SWWW3_cjs.b(this,D)[s],this))return this.get(chunkGY3SWWW3_cjs.b(this,D)[s],i)}}forEach(t,i=this){for(let s of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this)){let h=chunkGY3SWWW3_cjs.b(this,O)[s],n=chunkGY3SWWW3_cjs.e(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,chunkGY3SWWW3_cjs.b(this,D)[s],this);}}rforEach(t,i=this){for(let s of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this)){let h=chunkGY3SWWW3_cjs.b(this,O)[s],n=chunkGY3SWWW3_cjs.e(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,chunkGY3SWWW3_cjs.b(this,D)[s],this);}}purgeStale(){let t=false;for(let i of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this,{allowStale:true}))chunkGY3SWWW3_cjs.b(this,gt).call(this,i)&&(chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,chunkGY3SWWW3_cjs.b(this,D)[i],"expire"),t=true);return t}info(t){let i=chunkGY3SWWW3_cjs.b(this,$).get(t);if(i===void 0)return;let s=chunkGY3SWWW3_cjs.b(this,O)[i],h=chunkGY3SWWW3_cjs.e(this,y,W).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(chunkGY3SWWW3_cjs.b(this,ft)&&chunkGY3SWWW3_cjs.b(this,Ft)){let o=chunkGY3SWWW3_cjs.b(this,ft)[i],a=chunkGY3SWWW3_cjs.b(this,Ft)[i];if(o&&a){let l=o-(chunkGY3SWWW3_cjs.b(this,Rt).now()-a);n.ttl=l,n.start=Date.now();}}return chunkGY3SWWW3_cjs.b(this,At)&&(n.size=chunkGY3SWWW3_cjs.b(this,At)[i]),n}dump(){let t=[];for(let i of chunkGY3SWWW3_cjs.e(this,y,Kt).call(this,{allowStale:true})){let s=chunkGY3SWWW3_cjs.b(this,D)[i],h=chunkGY3SWWW3_cjs.b(this,O)[i],n=chunkGY3SWWW3_cjs.e(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(chunkGY3SWWW3_cjs.b(this,ft)&&chunkGY3SWWW3_cjs.b(this,Ft)){o.ttl=chunkGY3SWWW3_cjs.b(this,ft)[i];let a=chunkGY3SWWW3_cjs.b(this,Rt).now()-chunkGY3SWWW3_cjs.b(this,Ft)[i];o.start=Math.floor(Date.now()-a);}chunkGY3SWWW3_cjs.b(this,At)&&(o.size=chunkGY3SWWW3_cjs.b(this,At)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=chunkGY3SWWW3_cjs.b(this,Rt).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,S,E,b;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d=chunkGY3SWWW3_cjs.b(this,ei).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,t,"set"),this;let f=chunkGY3SWWW3_cjs.b(this,G)===0?void 0:chunkGY3SWWW3_cjs.b(this,$).get(t);if(f===void 0)f=chunkGY3SWWW3_cjs.b(this,G)===0?chunkGY3SWWW3_cjs.b(this,K):chunkGY3SWWW3_cjs.b(this,Ot).length!==0?chunkGY3SWWW3_cjs.b(this,Ot).pop():chunkGY3SWWW3_cjs.b(this,G)===chunkGY3SWWW3_cjs.b(this,yt)?chunkGY3SWWW3_cjs.e(this,y,Pi).call(this,false):chunkGY3SWWW3_cjs.b(this,G),chunkGY3SWWW3_cjs.b(this,D)[f]=t,chunkGY3SWWW3_cjs.b(this,O)[f]=i,chunkGY3SWWW3_cjs.b(this,$).set(t,f),chunkGY3SWWW3_cjs.b(this,it)[chunkGY3SWWW3_cjs.b(this,K)]=f,chunkGY3SWWW3_cjs.b(this,pt)[f]=chunkGY3SWWW3_cjs.b(this,K),chunkGY3SWWW3_cjs.d(this,K,f),chunkGY3SWWW3_cjs.f(this,G)._++,chunkGY3SWWW3_cjs.b(this,Le).call(this,f,d,l),l&&(l.set="add"),u=false,chunkGY3SWWW3_cjs.b(this,Te)&&((w=chunkGY3SWWW3_cjs.b(this,fe))==null||w.call(this,i,t,"add"));else {chunkGY3SWWW3_cjs.e(this,y,qe).call(this,f);let x=chunkGY3SWWW3_cjs.b(this,O)[f];if(i!==x){if(chunkGY3SWWW3_cjs.b(this,ee)&&chunkGY3SWWW3_cjs.e(this,y,W).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:v}=x;v!==void 0&&!o&&(chunkGY3SWWW3_cjs.b(this,Tt)&&((S=chunkGY3SWWW3_cjs.b(this,xt))==null||S.call(this,v,t,"set")),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.push([v,t,"set"]));}else o||(chunkGY3SWWW3_cjs.b(this,Tt)&&((E=chunkGY3SWWW3_cjs.b(this,xt))==null||E.call(this,x,t,"set")),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.push([x,t,"set"]));if(chunkGY3SWWW3_cjs.b(this,ge).call(this,f),chunkGY3SWWW3_cjs.b(this,Le).call(this,f,d,l),chunkGY3SWWW3_cjs.b(this,O)[f]=i,l){l.set="replace";let v=x&&chunkGY3SWWW3_cjs.e(this,y,W).call(this,x)?x.__staleWhileFetching:x;v!==void 0&&(l.oldValue=v);}}else l&&(l.set="update");chunkGY3SWWW3_cjs.b(this,Te)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!chunkGY3SWWW3_cjs.b(this,ft)&&chunkGY3SWWW3_cjs.e(this,y,ns).call(this),chunkGY3SWWW3_cjs.b(this,ft)&&(u||chunkGY3SWWW3_cjs.b(this,ti).call(this,f,h,n),l&&chunkGY3SWWW3_cjs.b(this,Bt).call(this,l,f)),!o&&chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)){let x=chunkGY3SWWW3_cjs.b(this,Y),v;for(;v=x?.shift();)(b=chunkGY3SWWW3_cjs.b(this,kt))==null||b.call(this,...v);}return this}pop(){var t;try{for(;chunkGY3SWWW3_cjs.b(this,G);){let i=chunkGY3SWWW3_cjs.b(this,O)[chunkGY3SWWW3_cjs.b(this,tt)];if(chunkGY3SWWW3_cjs.e(this,y,Pi).call(this,!0),chunkGY3SWWW3_cjs.e(this,y,W).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)){let i=chunkGY3SWWW3_cjs.b(this,Y),s;for(;s=i?.shift();)(t=chunkGY3SWWW3_cjs.b(this,kt))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=chunkGY3SWWW3_cjs.b(this,$).get(t);if(n!==void 0){let o=chunkGY3SWWW3_cjs.b(this,O)[n];if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(chunkGY3SWWW3_cjs.b(this,gt).call(this,n))h&&(h.has="stale",chunkGY3SWWW3_cjs.b(this,Bt).call(this,h,n));else return s&&chunkGY3SWWW3_cjs.b(this,de).call(this,n),h&&(h.has="hit",chunkGY3SWWW3_cjs.b(this,Bt).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=chunkGY3SWWW3_cjs.b(this,$).get(t);if(h===void 0||!s&&chunkGY3SWWW3_cjs.b(this,gt).call(this,h))return;let n=chunkGY3SWWW3_cjs.b(this,O)[h];return chunkGY3SWWW3_cjs.e(this,y,W).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:E=this.allowStaleOnFetchAbort,context:b,forceRefresh:x=false,status:v,signal:R}=i;if(!chunkGY3SWWW3_cjs.b(this,ee))return v&&(v.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:v});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:E,ignoreFetchAbort:S,status:v,signal:R},T=chunkGY3SWWW3_cjs.b(this,$).get(t);if(T===void 0){v&&(v.fetch="miss");let L=chunkGY3SWWW3_cjs.e(this,y,Di).call(this,t,T,A,b);return L.__returned=L}else {let L=chunkGY3SWWW3_cjs.b(this,O)[T];if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,L)){let B=s&&L.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",B&&(v.returnedStale=true)),B?L.__staleWhileFetching:L.__returned=L}let F=chunkGY3SWWW3_cjs.b(this,gt).call(this,T);if(!x&&!F)return v&&(v.fetch="hit"),chunkGY3SWWW3_cjs.e(this,y,qe).call(this,T),h&&chunkGY3SWWW3_cjs.b(this,de).call(this,T),v&&chunkGY3SWWW3_cjs.b(this,Bt).call(this,v,T),L;let j=chunkGY3SWWW3_cjs.e(this,y,Di).call(this,t,T,A,b),N=j.__staleWhileFetching!==void 0&&s;return v&&(v.fetch=F?"stale":"refresh",N&&F&&(v.returnedStale=true)),N?j.__staleWhileFetching:j.__returned=j}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=chunkGY3SWWW3_cjs.b(this,Fe);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=chunkGY3SWWW3_cjs.b(this,$).get(t);if(a!==void 0){let l=chunkGY3SWWW3_cjs.b(this,O)[a],u=chunkGY3SWWW3_cjs.e(this,y,W).call(this,l);return o&&chunkGY3SWWW3_cjs.b(this,Bt).call(this,o,a),chunkGY3SWWW3_cjs.b(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(chunkGY3SWWW3_cjs.e(this,y,qe).call(this,a),h&&chunkGY3SWWW3_cjs.b(this,de).call(this,a),l))}else o&&(o.get="miss");}delete(t){return chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,t,"delete")}clear(){return chunkGY3SWWW3_cjs.e(this,y,ls).call(this,"delete")}},yt=new WeakMap,ut=new WeakMap,xt=new WeakMap,fe=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Fe=new WeakMap,Rt=new WeakMap,G=new WeakMap,Ct=new WeakMap,$=new WeakMap,D=new WeakMap,O=new WeakMap,it=new WeakMap,pt=new WeakMap,tt=new WeakMap,K=new WeakMap,Ot=new WeakMap,Y=new WeakMap,At=new WeakMap,Ft=new WeakMap,ft=new WeakMap,dt=new WeakMap,Tt=new WeakMap,ee=new WeakMap,st=new WeakMap,Te=new WeakMap,y=new WeakSet,ns=function(){let t=new Wi(chunkGY3SWWW3_cjs.b(this,yt)),i=new Wi(chunkGY3SWWW3_cjs.b(this,yt));chunkGY3SWWW3_cjs.d(this,ft,t),chunkGY3SWWW3_cjs.d(this,Ft,i);let s=this.ttlAutopurge?new Array(chunkGY3SWWW3_cjs.b(this,yt)):void 0;chunkGY3SWWW3_cjs.d(this,dt,s),chunkGY3SWWW3_cjs.d(this,ti,(o,a,l=chunkGY3SWWW3_cjs.b(this,Rt).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{chunkGY3SWWW3_cjs.b(this,gt).call(this,o)&&chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,chunkGY3SWWW3_cjs.b(this,D)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),chunkGY3SWWW3_cjs.d(this,de,o=>{i[o]=t[o]!==0?chunkGY3SWWW3_cjs.b(this,Rt).now():0;}),chunkGY3SWWW3_cjs.d(this,Bt,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=chunkGY3SWWW3_cjs.b(this,Rt).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=chunkGY3SWWW3_cjs.b(this,$).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},chunkGY3SWWW3_cjs.d(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},de=new WeakMap,Bt=new WeakMap,ti=new WeakMap,gt=new WeakMap,Wr=function(){let t=new Wi(chunkGY3SWWW3_cjs.b(this,yt));chunkGY3SWWW3_cjs.d(this,Ct,0),chunkGY3SWWW3_cjs.d(this,At,t),chunkGY3SWWW3_cjs.d(this,ge,i=>{chunkGY3SWWW3_cjs.d(this,Ct,chunkGY3SWWW3_cjs.b(this,Ct)-t[i]),t[i]=0;}),chunkGY3SWWW3_cjs.d(this,ei,(i,s,h,n)=>{if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,s))return 0;if(!Vt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Vt(h))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return h}),chunkGY3SWWW3_cjs.d(this,Le,(i,s,h)=>{if(t[i]=s,chunkGY3SWWW3_cjs.b(this,ut)){let n=chunkGY3SWWW3_cjs.b(this,ut)-t[i];for(;chunkGY3SWWW3_cjs.b(this,Ct)>n;)chunkGY3SWWW3_cjs.e(this,y,Pi).call(this,true);}chunkGY3SWWW3_cjs.d(this,Ct,chunkGY3SWWW3_cjs.b(this,Ct)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=chunkGY3SWWW3_cjs.b(this,Ct));});},ge=new WeakMap,Le=new WeakMap,ei=new WeakMap,Kt=function*({allowStale:t=this.allowStale}={}){if(chunkGY3SWWW3_cjs.b(this,G))for(let i=chunkGY3SWWW3_cjs.b(this,K);!(!chunkGY3SWWW3_cjs.e(this,y,os).call(this,i)||((t||!chunkGY3SWWW3_cjs.b(this,gt).call(this,i))&&(yield i),i===chunkGY3SWWW3_cjs.b(this,tt)));)i=chunkGY3SWWW3_cjs.b(this,pt)[i];},Yt=function*({allowStale:t=this.allowStale}={}){if(chunkGY3SWWW3_cjs.b(this,G))for(let i=chunkGY3SWWW3_cjs.b(this,tt);!(!chunkGY3SWWW3_cjs.e(this,y,os).call(this,i)||((t||!chunkGY3SWWW3_cjs.b(this,gt).call(this,i))&&(yield i),i===chunkGY3SWWW3_cjs.b(this,K)));)i=chunkGY3SWWW3_cjs.b(this,it)[i];},os=function(t){return t!==void 0&&chunkGY3SWWW3_cjs.b(this,$).get(chunkGY3SWWW3_cjs.b(this,D)[t])===t},Pi=function(t){var n;let i=chunkGY3SWWW3_cjs.b(this,tt),s=chunkGY3SWWW3_cjs.b(this,D)[i],h=chunkGY3SWWW3_cjs.b(this,O)[i];return chunkGY3SWWW3_cjs.b(this,ee)&&chunkGY3SWWW3_cjs.e(this,y,W).call(this,h)?h.__abortController.abort(new Error("evicted")):(chunkGY3SWWW3_cjs.b(this,Tt)||chunkGY3SWWW3_cjs.b(this,st))&&(chunkGY3SWWW3_cjs.b(this,Tt)&&((n=chunkGY3SWWW3_cjs.b(this,xt))==null||n.call(this,h,s,"evict")),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.push([h,s,"evict"])),chunkGY3SWWW3_cjs.b(this,ge).call(this,i),chunkGY3SWWW3_cjs.b(this,dt)?.[i]&&(clearTimeout(chunkGY3SWWW3_cjs.b(this,dt)[i]),chunkGY3SWWW3_cjs.b(this,dt)[i]=void 0),t&&(chunkGY3SWWW3_cjs.b(this,D)[i]=void 0,chunkGY3SWWW3_cjs.b(this,O)[i]=void 0,chunkGY3SWWW3_cjs.b(this,Ot).push(i)),chunkGY3SWWW3_cjs.b(this,G)===1?(chunkGY3SWWW3_cjs.d(this,tt,chunkGY3SWWW3_cjs.d(this,K,0)),chunkGY3SWWW3_cjs.b(this,Ot).length=0):chunkGY3SWWW3_cjs.d(this,tt,chunkGY3SWWW3_cjs.b(this,it)[i]),chunkGY3SWWW3_cjs.b(this,$).delete(s),chunkGY3SWWW3_cjs.f(this,G)._--,i},Di=function(t,i,s,h){let n=i===void 0?void 0:chunkGY3SWWW3_cjs.b(this,O)[i];if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,n))return n;let o=new Bi,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(b,x=false)=>{let{aborted:v}=o.signal,R=s.ignoreFetchAbort&&b!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&b!==void 0);if(s.status&&(v&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,R&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),v&&!R&&!x)return f(o.signal.reason,A);let T=S,L=chunkGY3SWWW3_cjs.b(this,O)[i];return (L===S||R&&x&&L===void 0)&&(b===void 0?T.__staleWhileFetching!==void 0?chunkGY3SWWW3_cjs.b(this,O)[i]=T.__staleWhileFetching:chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,b,l.options))),b},d=b=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=b),f(b,false)),f=(b,x)=>{let{aborted:v}=o.signal,R=v&&s.allowStaleOnFetchAbort,A=R||s.allowStaleOnFetchRejection,T=A||s.noDeleteOnFetchRejection,L=S;if(chunkGY3SWWW3_cjs.b(this,O)[i]===S&&(!T||!x&&L.__staleWhileFetching===void 0?chunkGY3SWWW3_cjs.e(this,y,Xt).call(this,t,"fetch"):R||(chunkGY3SWWW3_cjs.b(this,O)[i]=L.__staleWhileFetching)),A)return s.status&&L.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),L.__staleWhileFetching;if(L.__returned===L)throw b},w=(b,x)=>{var R;let v=(R=chunkGY3SWWW3_cjs.b(this,Ae))==null?void 0:R.call(this,t,n,l);v&&v instanceof Promise&&v.then(A=>b(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(b(void 0),s.allowStaleOnFetchAbort&&(b=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let S=new Promise(w).then(u,d),E=Object.assign(S,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,E,{...l.options,status:void 0}),i=chunkGY3SWWW3_cjs.b(this,$).get(t)):chunkGY3SWWW3_cjs.b(this,O)[i]=E,E},W=function(t){if(!chunkGY3SWWW3_cjs.b(this,ee))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Bi},as=function(t,i){chunkGY3SWWW3_cjs.b(this,pt)[i]=t,chunkGY3SWWW3_cjs.b(this,it)[t]=i;},qe=function(t){t!==chunkGY3SWWW3_cjs.b(this,K)&&(t===chunkGY3SWWW3_cjs.b(this,tt)?chunkGY3SWWW3_cjs.d(this,tt,chunkGY3SWWW3_cjs.b(this,it)[t]):chunkGY3SWWW3_cjs.e(this,y,as).call(this,chunkGY3SWWW3_cjs.b(this,pt)[t],chunkGY3SWWW3_cjs.b(this,it)[t]),chunkGY3SWWW3_cjs.e(this,y,as).call(this,chunkGY3SWWW3_cjs.b(this,K),t),chunkGY3SWWW3_cjs.d(this,K,t));},Xt=function(t,i){var h,n;let s=false;if(chunkGY3SWWW3_cjs.b(this,G)!==0){let o=chunkGY3SWWW3_cjs.b(this,$).get(t);if(o!==void 0)if(chunkGY3SWWW3_cjs.b(this,dt)?.[o]&&(clearTimeout(chunkGY3SWWW3_cjs.b(this,dt)?.[o]),chunkGY3SWWW3_cjs.b(this,dt)[o]=void 0),s=true,chunkGY3SWWW3_cjs.b(this,G)===1)chunkGY3SWWW3_cjs.e(this,y,ls).call(this,i);else {chunkGY3SWWW3_cjs.b(this,ge).call(this,o);let a=chunkGY3SWWW3_cjs.b(this,O)[o];if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,a)?a.__abortController.abort(new Error("deleted")):(chunkGY3SWWW3_cjs.b(this,Tt)||chunkGY3SWWW3_cjs.b(this,st))&&(chunkGY3SWWW3_cjs.b(this,Tt)&&((h=chunkGY3SWWW3_cjs.b(this,xt))==null||h.call(this,a,t,i)),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.push([a,t,i])),chunkGY3SWWW3_cjs.b(this,$).delete(t),chunkGY3SWWW3_cjs.b(this,D)[o]=void 0,chunkGY3SWWW3_cjs.b(this,O)[o]=void 0,o===chunkGY3SWWW3_cjs.b(this,K))chunkGY3SWWW3_cjs.d(this,K,chunkGY3SWWW3_cjs.b(this,pt)[o]);else if(o===chunkGY3SWWW3_cjs.b(this,tt))chunkGY3SWWW3_cjs.d(this,tt,chunkGY3SWWW3_cjs.b(this,it)[o]);else {let l=chunkGY3SWWW3_cjs.b(this,pt)[o];chunkGY3SWWW3_cjs.b(this,it)[l]=chunkGY3SWWW3_cjs.b(this,it)[o];let u=chunkGY3SWWW3_cjs.b(this,it)[o];chunkGY3SWWW3_cjs.b(this,pt)[u]=chunkGY3SWWW3_cjs.b(this,pt)[o];}chunkGY3SWWW3_cjs.f(this,G)._--,chunkGY3SWWW3_cjs.b(this,Ot).push(o);}}if(chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.length){let o=chunkGY3SWWW3_cjs.b(this,Y),a;for(;a=o?.shift();)(n=chunkGY3SWWW3_cjs.b(this,kt))==null||n.call(this,...a);}return s},ls=function(t){var i,s;for(let h of chunkGY3SWWW3_cjs.e(this,y,Yt).call(this,{allowStale:true})){let n=chunkGY3SWWW3_cjs.b(this,O)[h];if(chunkGY3SWWW3_cjs.e(this,y,W).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=chunkGY3SWWW3_cjs.b(this,D)[h];chunkGY3SWWW3_cjs.b(this,Tt)&&((i=chunkGY3SWWW3_cjs.b(this,xt))==null||i.call(this,n,o,t)),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)?.push([n,o,t]);}}if(chunkGY3SWWW3_cjs.b(this,$).clear(),chunkGY3SWWW3_cjs.b(this,O).fill(void 0),chunkGY3SWWW3_cjs.b(this,D).fill(void 0),chunkGY3SWWW3_cjs.b(this,ft)&&chunkGY3SWWW3_cjs.b(this,Ft)){chunkGY3SWWW3_cjs.b(this,ft).fill(0),chunkGY3SWWW3_cjs.b(this,Ft).fill(0);for(let h of chunkGY3SWWW3_cjs.b(this,dt)??[])h!==void 0&&clearTimeout(h);chunkGY3SWWW3_cjs.b(this,dt)?.fill(void 0);}if(chunkGY3SWWW3_cjs.b(this,At)&&chunkGY3SWWW3_cjs.b(this,At).fill(0),chunkGY3SWWW3_cjs.d(this,tt,0),chunkGY3SWWW3_cjs.d(this,K,0),chunkGY3SWWW3_cjs.b(this,Ot).length=0,chunkGY3SWWW3_cjs.d(this,Ct,0),chunkGY3SWWW3_cjs.d(this,G,0),chunkGY3SWWW3_cjs.b(this,st)&&chunkGY3SWWW3_cjs.b(this,Y)){let h=chunkGY3SWWW3_cjs.b(this,Y),n;for(;n=h?.shift();)(s=chunkGY3SWWW3_cjs.b(this,kt))==null||s.call(this,...n);}},Me),Ms=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ln=e=>!!e&&typeof e=="object"&&(e instanceof Ui||e instanceof Pr__default.default||Mn(e)||Wn(e)),Mn=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==Pr__default.default.Writable.prototype.pipe,Wn=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",zt=Symbol("EOF"),_t=Symbol("maybeEmitEnd"),Zt=Symbol("emittedEnd"),Ri=Symbol("emittingEnd"),Be=Symbol("emittedError"),Ci=Symbol("closed"),Ws=Symbol("read"),Oi=Symbol("flush"),Ps=Symbol("flushChunk"),vt=Symbol("encoding"),ke=Symbol("decoder"),J=Symbol("flowing"),Ue=Symbol("paused"),Re=Symbol("resume"),q=Symbol("buffer"),et=Symbol("pipes"),Z=Symbol("bufferLength"),Yi=Symbol("bufferPush"),Ai=Symbol("bufferShift"),Q=Symbol("objectMode"),z=Symbol("destroyed"),Xi=Symbol("error"),Qi=Symbol("emitData"),Ds=Symbol("emitEnd"),ts=Symbol("emitEnd2"),Mt=Symbol("async"),es=Symbol("abort"),Fi=Symbol("aborted"),Ge=Symbol("signal"),ae=Symbol("dataListeners"),ct=Symbol("discarded"),Ie=e=>Promise.resolve().then(e),Pn=e=>e(),Dn=e=>e==="end"||e==="finish"||e==="prefinish",jn=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Nn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Dr=class{constructor(e,t,i){chunkGY3SWWW3_cjs.a(this,"src");chunkGY3SWWW3_cjs.a(this,"dest");chunkGY3SWWW3_cjs.a(this,"opts");chunkGY3SWWW3_cjs.a(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Re](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},zn=class extends Dr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},_n=e=>!!e.objectMode,$n=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Zs,Vs,Ks,Ys,Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,Ui=class extends events.EventEmitter{constructor(...t){let i=t[0]||{};super();chunkGY3SWWW3_cjs.a(this,pr,false);chunkGY3SWWW3_cjs.a(this,ur,false);chunkGY3SWWW3_cjs.a(this,cr,[]);chunkGY3SWWW3_cjs.a(this,lr,[]);chunkGY3SWWW3_cjs.a(this,ar);chunkGY3SWWW3_cjs.a(this,or);chunkGY3SWWW3_cjs.a(this,nr);chunkGY3SWWW3_cjs.a(this,hr);chunkGY3SWWW3_cjs.a(this,rr,false);chunkGY3SWWW3_cjs.a(this,sr,false);chunkGY3SWWW3_cjs.a(this,ir,false);chunkGY3SWWW3_cjs.a(this,er,false);chunkGY3SWWW3_cjs.a(this,tr,null);chunkGY3SWWW3_cjs.a(this,Qs,0);chunkGY3SWWW3_cjs.a(this,Xs,false);chunkGY3SWWW3_cjs.a(this,Ys);chunkGY3SWWW3_cjs.a(this,Ks,false);chunkGY3SWWW3_cjs.a(this,Vs,0);chunkGY3SWWW3_cjs.a(this,Zs,false);chunkGY3SWWW3_cjs.a(this,"writable",true);chunkGY3SWWW3_cjs.a(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");_n(i)?(this[Q]=true,this[vt]=null):$n(i)?(this[vt]=i.encoding,this[Q]=false):(this[Q]=false,this[vt]=null),this[Mt]=!!i.async,this[ke]=this[vt]?new string_decoder.StringDecoder(this[vt]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[q]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:s}=i;s&&(this[Ge]=s,s.aborted?this[es]():s.addEventListener("abort",()=>this[es]()));}get bufferLength(){return this[Z]}get encoding(){return this[vt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Q]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(t){this[Mt]=this[Mt]||!!t;}[(pr=J,ur=Ue,cr=et,lr=q,ar=Q,or=vt,nr=Mt,hr=ke,rr=zt,sr=Zt,ir=Ri,er=Ci,tr=Be,Qs=Z,Xs=z,Ys=Ge,Ks=Fi,Vs=ae,Zs=ct,es)](){this[Fi]=true,this.emit("abort",this[Ge]?.reason),this.destroy(this[Ge]?.reason);}get aborted(){return this[Fi]}set aborted(t){}write(t,i,s){if(this[Fi])return false;if(this[zt])throw new Error("write after end");if(this[z])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let h=this[Mt]?Ie:Pn;if(!this[Q]&&!Buffer.isBuffer(t)){if(Nn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(jn(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Q]?(this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Yi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):t.length?(typeof t=="string"&&!(i===this[vt]&&!this[ke]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[vt]&&(t=this[ke].write(t)),this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Yi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):(this[Z]!==0&&this.emit("readable"),s&&h(s),this[J])}read(t){if(this[z])return null;if(this[ct]=false,this[Z]===0||t===0||t&&t>this[Z])return this[_t](),null;this[Q]&&(t=null),this[q].length>1&&!this[Q]&&(this[q]=[this[vt]?this[q].join(""):Buffer.concat(this[q],this[Z])]);let i=this[Ws](t||null,this[q][0]);return this[_t](),i}[Ws](t,i){if(this[Q])this[Ai]();else {let s=i;t===s.length||t===null?this[Ai]():typeof s=="string"?(this[q][0]=s.slice(t),i=s.slice(0,t),this[Z]-=t):(this[q][0]=s.subarray(t),i=s.subarray(0,t),this[Z]-=t);}return this.emit("data",i),!this[q].length&&!this[zt]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[zt]=true,this.writable=false,(this[J]||!this[Ue])&&this[_t](),this}[Re](){this[z]||(!this[ae]&&!this[et].length&&(this[ct]=true),this[Ue]=false,this[J]=true,this.emit("resume"),this[q].length?this[Oi]():this[zt]?this[_t]():this.emit("drain"));}resume(){return this[Re]()}pause(){this[J]=false,this[Ue]=true,this[ct]=false;}get destroyed(){return this[z]}get flowing(){return this[J]}get paused(){return this[Ue]}[Yi](t){this[Q]?this[Z]+=1:this[Z]+=t.length,this[q].push(t);}[Ai](){return this[Q]?this[Z]-=1:this[Z]-=this[q][0].length,this[q].shift()}[Oi](t=false){do;while(this[Ps](this[Ai]())&&this[q].length);!t&&!this[q].length&&!this[zt]&&this.emit("drain");}[Ps](t){return this.emit("data",t),this[J]}pipe(t,i){if(this[z])return t;this[ct]=false;let s=this[Zt];return i=i||{},t===Ms.stdout||t===Ms.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[et].push(i.proxyErrors?new zn(this,t,i):new Dr(this,t,i)),this[Mt]?Ie(()=>this[Re]()):this[Re]()),t}unpipe(t){let i=this[et].find(s=>s.dest===t);i&&(this[et].length===1?(this[J]&&this[ae]===0&&(this[J]=false),this[et]=[]):this[et].splice(this[et].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[ae]++,!this[et].length&&!this[J]&&this[Re]();else if(t==="readable"&&this[Z]!==0)super.emit("readable");else if(Dn(t)&&this[Zt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Be]){let h=i;this[Mt]?Ie(()=>h.call(this,this[Be])):h.call(this,this[Be]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[ae]=this.listeners("data").length,this[ae]===0&&!this[ct]&&!this[et].length&&(this[J]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[ae]=0,!this[ct]&&!this[et].length&&(this[J]=false)),i}get emittedEnd(){return this[Zt]}[_t](){!this[Ri]&&!this[Zt]&&!this[z]&&this[q].length===0&&this[zt]&&(this[Ri]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ci]&&this.emit("close"),this[Ri]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return false;if(t==="data")return !this[Q]&&!s?false:this[Mt]?(Ie(()=>this[Qi](s)),true):this[Qi](s);if(t==="end")return this[Ds]();if(t==="close"){if(this[Ci]=true,!this[Zt]&&!this[z])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Be]=s,super.emit(Xi,s);let n=!this[Ge]||this.listeners("error").length?super.emit("error",s):false;return this[_t](),n}else if(t==="resume"){let n=super.emit("resume");return this[_t](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[_t](),h}[Qi](t){for(let s of this[et])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[_t](),i}[Ds](){return this[Zt]?false:(this[Zt]=true,this.readable=false,this[Mt]?(Ie(()=>this[ts]()),true):this[ts]())}[ts](){if(this[ke]){let i=this[ke].end();if(i){for(let s of this[et])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[et])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Q]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[Q]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[Q])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[vt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(z,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[zt])return i();let h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(z,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(z,u),this.pause(),h({value:d,done:!!this[zt]});},l=()=>{this.off("error",o),this.off("data",a),this.off(z,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(z,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(Xi,i),this.off(z,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(Xi,i),this.once(z,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=true,this[ct]=true,this[q].length=0,this[Z]=0;let i=this;return typeof i.close=="function"&&!this[Ci]&&i.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return Ln}},Bn=Rn.realpathSync.native,Ze={lstatSync:Rn.lstatSync,readdir:Rn.readdir,readdirSync:Rn.readdirSync,readlinkSync:Rn.readlinkSync,realpathSync:Bn,promises:{lstat:oh.lstat,readdir:oh.readdir,readlink:oh.readlink,realpath:oh.realpath}},jr=e=>!e||e===Ze||e===Rn__namespace?Ze:{...Ze,...e,promises:{...Ze.promises,...e.promises||{}}},Nr=/^\\\\\?\\([a-z]:)\\?$/i,Un=e=>e.replace(/\//g,"\\").replace(Nr,"$1\\"),Gn=/[\\\/]/,bt=0,zr=1,_r=2,Wt=4,$r=6,Br=8,le=10,Ur=12,wt=15,He=~wt,is=16,js=32,Ve=64,Et=128,Ti=256,ji=512,Ns=Ve|Et|ji,In=1023,ss=e=>e.isFile()?Br:e.isDirectory()?Wt:e.isSymbolicLink()?le:e.isCharacterDevice()?_r:e.isBlockDevice()?$r:e.isSocket()?Ur:e.isFIFO()?zr:bt,zs=new Ii({max:2**12}),Ke=e=>{let t=zs.get(e);if(t)return t;let i=e.normalize("NFKD");return zs.set(e,i),i},_s=new Ii({max:2**12}),Li=e=>{let t=_s.get(e);if(t)return t;let i=Ke(e.toLowerCase());return _s.set(e,i),i},$s=class extends Ii{constructor(){super({max:256});}},Hn=class extends Ii{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Gr=Symbol("PathScurry setAsCwd"),rt,ii,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,ie,me,Dt,Ut,Gt,It,C,we,Ht,jt,k,us,Ni,Ye,ps,fs,Xe,zi,ds,gs,_i,Ir,Hr,Jr,ms,We,Pe,qr,ye,fr,at=(fr=class{constructor(e,t=bt,i,s,h,n,o){chunkGY3SWWW3_cjs.c(this,k);chunkGY3SWWW3_cjs.a(this,"name");chunkGY3SWWW3_cjs.a(this,"root");chunkGY3SWWW3_cjs.a(this,"roots");chunkGY3SWWW3_cjs.a(this,"parent");chunkGY3SWWW3_cjs.a(this,"nocase");chunkGY3SWWW3_cjs.a(this,"isCWD",false);chunkGY3SWWW3_cjs.c(this,rt);chunkGY3SWWW3_cjs.c(this,ii);chunkGY3SWWW3_cjs.c(this,si);chunkGY3SWWW3_cjs.c(this,ri);chunkGY3SWWW3_cjs.c(this,hi);chunkGY3SWWW3_cjs.c(this,ni);chunkGY3SWWW3_cjs.c(this,oi);chunkGY3SWWW3_cjs.c(this,ai);chunkGY3SWWW3_cjs.c(this,li);chunkGY3SWWW3_cjs.c(this,ci);chunkGY3SWWW3_cjs.c(this,ui);chunkGY3SWWW3_cjs.c(this,pi);chunkGY3SWWW3_cjs.c(this,fi);chunkGY3SWWW3_cjs.c(this,di);chunkGY3SWWW3_cjs.c(this,gi);chunkGY3SWWW3_cjs.c(this,mi);chunkGY3SWWW3_cjs.c(this,wi);chunkGY3SWWW3_cjs.c(this,yi);chunkGY3SWWW3_cjs.c(this,bi);chunkGY3SWWW3_cjs.c(this,ie);chunkGY3SWWW3_cjs.c(this,me);chunkGY3SWWW3_cjs.c(this,Dt);chunkGY3SWWW3_cjs.c(this,Ut);chunkGY3SWWW3_cjs.c(this,Gt);chunkGY3SWWW3_cjs.c(this,It);chunkGY3SWWW3_cjs.c(this,C);chunkGY3SWWW3_cjs.c(this,we);chunkGY3SWWW3_cjs.c(this,Ht);chunkGY3SWWW3_cjs.c(this,jt);chunkGY3SWWW3_cjs.c(this,We,[]);chunkGY3SWWW3_cjs.c(this,Pe,false);chunkGY3SWWW3_cjs.c(this,ye);this.name=e,chunkGY3SWWW3_cjs.d(this,ie,h?Li(e):Ke(e)),chunkGY3SWWW3_cjs.d(this,C,t&In),this.nocase=h,this.roots=s,this.root=i||this,chunkGY3SWWW3_cjs.d(this,we,n),chunkGY3SWWW3_cjs.d(this,Dt,o.fullpath),chunkGY3SWWW3_cjs.d(this,Gt,o.relative),chunkGY3SWWW3_cjs.d(this,It,o.relativePosix),this.parent=o.parent,this.parent?chunkGY3SWWW3_cjs.d(this,rt,chunkGY3SWWW3_cjs.b(this.parent,rt)):chunkGY3SWWW3_cjs.d(this,rt,jr(o.fs));}get dev(){return chunkGY3SWWW3_cjs.b(this,ii)}get mode(){return chunkGY3SWWW3_cjs.b(this,si)}get nlink(){return chunkGY3SWWW3_cjs.b(this,ri)}get uid(){return chunkGY3SWWW3_cjs.b(this,hi)}get gid(){return chunkGY3SWWW3_cjs.b(this,ni)}get rdev(){return chunkGY3SWWW3_cjs.b(this,oi)}get blksize(){return chunkGY3SWWW3_cjs.b(this,ai)}get ino(){return chunkGY3SWWW3_cjs.b(this,li)}get size(){return chunkGY3SWWW3_cjs.b(this,ci)}get blocks(){return chunkGY3SWWW3_cjs.b(this,ui)}get atimeMs(){return chunkGY3SWWW3_cjs.b(this,pi)}get mtimeMs(){return chunkGY3SWWW3_cjs.b(this,fi)}get ctimeMs(){return chunkGY3SWWW3_cjs.b(this,di)}get birthtimeMs(){return chunkGY3SWWW3_cjs.b(this,gi)}get atime(){return chunkGY3SWWW3_cjs.b(this,mi)}get mtime(){return chunkGY3SWWW3_cjs.b(this,wi)}get ctime(){return chunkGY3SWWW3_cjs.b(this,yi)}get birthtime(){return chunkGY3SWWW3_cjs.b(this,bi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return chunkGY3SWWW3_cjs.b(this,me)!==void 0?chunkGY3SWWW3_cjs.b(this,me):this.parent?chunkGY3SWWW3_cjs.d(this,me,this.parent.depth()+1):chunkGY3SWWW3_cjs.d(this,me,0)}childrenCache(){return chunkGY3SWWW3_cjs.b(this,we)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i=e.substring(t.length).split(this.splitSep);return t?chunkGY3SWWW3_cjs.e(s=this.getRoot(t),k,us).call(s,i):chunkGY3SWWW3_cjs.e(this,k,us).call(this,i)}children(){let e=chunkGY3SWWW3_cjs.b(this,we).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return chunkGY3SWWW3_cjs.b(this,we).set(this,t),chunkGY3SWWW3_cjs.d(this,C,chunkGY3SWWW3_cjs.b(this,C)&~is),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Li(e):Ke(e);for(let a of i)if(chunkGY3SWWW3_cjs.b(a,ie)===s)return a;let h=this.parent?this.sep:"",n=chunkGY3SWWW3_cjs.b(this,Dt)?chunkGY3SWWW3_cjs.b(this,Dt)+h+e:void 0,o=this.newChild(e,bt,{...t,parent:this,fullpath:n});return this.canReaddir()||chunkGY3SWWW3_cjs.d(o,C,chunkGY3SWWW3_cjs.b(o,C)|Et),i.push(o),o}relative(){if(this.isCWD)return "";if(chunkGY3SWWW3_cjs.b(this,Gt)!==void 0)return chunkGY3SWWW3_cjs.b(this,Gt);let e=this.name,t=this.parent;if(!t)return chunkGY3SWWW3_cjs.d(this,Gt,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(chunkGY3SWWW3_cjs.b(this,It)!==void 0)return chunkGY3SWWW3_cjs.b(this,It);let e=this.name,t=this.parent;if(!t)return chunkGY3SWWW3_cjs.d(this,It,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(chunkGY3SWWW3_cjs.b(this,Dt)!==void 0)return chunkGY3SWWW3_cjs.b(this,Dt);let e=this.name,t=this.parent;if(!t)return chunkGY3SWWW3_cjs.d(this,Dt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return chunkGY3SWWW3_cjs.d(this,Dt,i)}fullpathPosix(){if(chunkGY3SWWW3_cjs.b(this,Ut)!==void 0)return chunkGY3SWWW3_cjs.b(this,Ut);if(this.sep==="/")return chunkGY3SWWW3_cjs.d(this,Ut,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?chunkGY3SWWW3_cjs.d(this,Ut,`//?/${s}`):chunkGY3SWWW3_cjs.d(this,Ut,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return chunkGY3SWWW3_cjs.d(this,Ut,i)}isUnknown(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===bt}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 (chunkGY3SWWW3_cjs.b(this,C)&wt)===Br}isDirectory(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===Wt}isCharacterDevice(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===_r}isBlockDevice(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===$r}isFIFO(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===zr}isSocket(){return (chunkGY3SWWW3_cjs.b(this,C)&wt)===Ur}isSymbolicLink(){return (chunkGY3SWWW3_cjs.b(this,C)&le)===le}lstatCached(){return chunkGY3SWWW3_cjs.b(this,C)&js?this:void 0}readlinkCached(){return chunkGY3SWWW3_cjs.b(this,Ht)}realpathCached(){return chunkGY3SWWW3_cjs.b(this,jt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(chunkGY3SWWW3_cjs.b(this,Ht))return true;if(!this.parent)return false;let e=chunkGY3SWWW3_cjs.b(this,C)&wt;return !(e!==bt&&e!==le||chunkGY3SWWW3_cjs.b(this,C)&Ti||chunkGY3SWWW3_cjs.b(this,C)&Et)}calledReaddir(){return !!(chunkGY3SWWW3_cjs.b(this,C)&is)}isENOENT(){return !!(chunkGY3SWWW3_cjs.b(this,C)&Et)}isNamed(e){return this.nocase?chunkGY3SWWW3_cjs.b(this,ie)===Li(e):chunkGY3SWWW3_cjs.b(this,ie)===Ke(e)}async readlink(){let e=chunkGY3SWWW3_cjs.b(this,Ht);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await chunkGY3SWWW3_cjs.b(this,rt).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return chunkGY3SWWW3_cjs.d(this,Ht,i)}catch(t){chunkGY3SWWW3_cjs.e(this,k,gs).call(this,t.code);return}}readlinkSync(){let e=chunkGY3SWWW3_cjs.b(this,Ht);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=chunkGY3SWWW3_cjs.b(this,rt).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return chunkGY3SWWW3_cjs.d(this,Ht,i)}catch(t){chunkGY3SWWW3_cjs.e(this,k,gs).call(this,t.code);return}}async lstat(){if((chunkGY3SWWW3_cjs.b(this,C)&Et)===0)try{return chunkGY3SWWW3_cjs.e(this,k,ms).call(this,await chunkGY3SWWW3_cjs.b(this,rt).promises.lstat(this.fullpath())),this}catch(e){chunkGY3SWWW3_cjs.e(this,k,ds).call(this,e.code);}}lstatSync(){if((chunkGY3SWWW3_cjs.b(this,C)&Et)===0)try{return chunkGY3SWWW3_cjs.e(this,k,ms).call(this,chunkGY3SWWW3_cjs.b(this,rt).lstatSync(this.fullpath())),this}catch(e){chunkGY3SWWW3_cjs.e(this,k,ds).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e(null,h):queueMicrotask(()=>e(null,h));return}if(chunkGY3SWWW3_cjs.b(this,We).push(e),chunkGY3SWWW3_cjs.b(this,Pe))return;chunkGY3SWWW3_cjs.d(this,Pe,true);let s=this.fullpath();chunkGY3SWWW3_cjs.b(this,rt).readdir(s,{withFileTypes:true},(h,n)=>{if(h)chunkGY3SWWW3_cjs.e(this,k,zi).call(this,h.code),i.provisional=0;else {for(let o of n)chunkGY3SWWW3_cjs.e(this,k,_i).call(this,o,i);chunkGY3SWWW3_cjs.e(this,k,Ni).call(this,i);}chunkGY3SWWW3_cjs.e(this,k,qr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(chunkGY3SWWW3_cjs.b(this,ye))await chunkGY3SWWW3_cjs.b(this,ye);else {let i=()=>{};chunkGY3SWWW3_cjs.d(this,ye,new Promise(s=>i=s));try{for(let s of await chunkGY3SWWW3_cjs.b(this,rt).promises.readdir(t,{withFileTypes:!0}))chunkGY3SWWW3_cjs.e(this,k,_i).call(this,s,e);chunkGY3SWWW3_cjs.e(this,k,Ni).call(this,e);}catch(s){chunkGY3SWWW3_cjs.e(this,k,zi).call(this,s.code),e.provisional=0;}chunkGY3SWWW3_cjs.d(this,ye,void 0),i();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i of chunkGY3SWWW3_cjs.b(this,rt).readdirSync(t,{withFileTypes:!0}))chunkGY3SWWW3_cjs.e(this,k,_i).call(this,i,e);chunkGY3SWWW3_cjs.e(this,k,Ni).call(this,e);}catch(i){chunkGY3SWWW3_cjs.e(this,k,zi).call(this,i.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(chunkGY3SWWW3_cjs.b(this,C)&Ns)return false;let e=wt&chunkGY3SWWW3_cjs.b(this,C);return e===bt||e===Wt||e===le}shouldWalk(e,t){return (chunkGY3SWWW3_cjs.b(this,C)&Wt)===Wt&&!(chunkGY3SWWW3_cjs.b(this,C)&Ns)&&!e.has(this)&&(!t||t(this))}async realpath(){if(chunkGY3SWWW3_cjs.b(this,jt))return chunkGY3SWWW3_cjs.b(this,jt);if(!((ji|Ti|Et)&chunkGY3SWWW3_cjs.b(this,C)))try{let e=await chunkGY3SWWW3_cjs.b(this,rt).promises.realpath(this.fullpath());return chunkGY3SWWW3_cjs.d(this,jt,this.resolve(e))}catch{chunkGY3SWWW3_cjs.e(this,k,fs).call(this);}}realpathSync(){if(chunkGY3SWWW3_cjs.b(this,jt))return chunkGY3SWWW3_cjs.b(this,jt);if(!((ji|Ti|Et)&chunkGY3SWWW3_cjs.b(this,C)))try{let e=chunkGY3SWWW3_cjs.b(this,rt).realpathSync(this.fullpath());return chunkGY3SWWW3_cjs.d(this,jt,this.resolve(e))}catch{chunkGY3SWWW3_cjs.e(this,k,fs).call(this);}}[Gr](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),chunkGY3SWWW3_cjs.d(s,Gt,i.join(this.sep)),chunkGY3SWWW3_cjs.d(s,It,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)chunkGY3SWWW3_cjs.d(s,Gt,void 0),chunkGY3SWWW3_cjs.d(s,It,void 0),s=s.parent;}},rt=new WeakMap,ii=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,ie=new WeakMap,me=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Gt=new WeakMap,It=new WeakMap,C=new WeakMap,we=new WeakMap,Ht=new WeakMap,jt=new WeakMap,k=new WeakSet,us=function(e){let t=this;for(let i of e)t=t.child(i);return t},Ni=function(e){var t;chunkGY3SWWW3_cjs.d(this,C,chunkGY3SWWW3_cjs.b(this,C)|is);for(let i=e.provisional;i<e.length;i++){let s=e[i];s&&chunkGY3SWWW3_cjs.e(t=s,k,Ye).call(t);}},Ye=function(){chunkGY3SWWW3_cjs.b(this,C)&Et||(chunkGY3SWWW3_cjs.d(this,C,(chunkGY3SWWW3_cjs.b(this,C)|Et)&He),chunkGY3SWWW3_cjs.e(this,k,ps).call(this));},ps=function(){var t;let e=this.children();e.provisional=0;for(let i of e)chunkGY3SWWW3_cjs.e(t=i,k,Ye).call(t);},fs=function(){chunkGY3SWWW3_cjs.d(this,C,chunkGY3SWWW3_cjs.b(this,C)|ji),chunkGY3SWWW3_cjs.e(this,k,Xe).call(this);},Xe=function(){if(chunkGY3SWWW3_cjs.b(this,C)&Ve)return;let e=chunkGY3SWWW3_cjs.b(this,C);(e&wt)===Wt&&(e&=He),chunkGY3SWWW3_cjs.d(this,C,e|Ve),chunkGY3SWWW3_cjs.e(this,k,ps).call(this);},zi=function(e=""){e==="ENOTDIR"||e==="EPERM"?chunkGY3SWWW3_cjs.e(this,k,Xe).call(this):e==="ENOENT"?chunkGY3SWWW3_cjs.e(this,k,Ye).call(this):this.children().provisional=0;},ds=function(e=""){var t;e==="ENOTDIR"?chunkGY3SWWW3_cjs.e(t=this.parent,k,Xe).call(t):e==="ENOENT"&&chunkGY3SWWW3_cjs.e(this,k,Ye).call(this);},gs=function(e=""){var i;let t=chunkGY3SWWW3_cjs.b(this,C);t|=Ti,e==="ENOENT"&&(t|=Et),(e==="EINVAL"||e==="UNKNOWN")&&(t&=He),chunkGY3SWWW3_cjs.d(this,C,t),e==="ENOTDIR"&&this.parent&&chunkGY3SWWW3_cjs.e(i=this.parent,k,Xe).call(i);},_i=function(e,t){return chunkGY3SWWW3_cjs.e(this,k,Hr).call(this,e,t)||chunkGY3SWWW3_cjs.e(this,k,Ir).call(this,e,t)},Ir=function(e,t){let i=ss(e),s=this.newChild(e.name,i,{parent:this}),h=chunkGY3SWWW3_cjs.b(s,C)&wt;return h!==Wt&&h!==le&&h!==bt&&chunkGY3SWWW3_cjs.d(s,C,chunkGY3SWWW3_cjs.b(s,C)|Ve),t.unshift(s),t.provisional++,s},Hr=function(e,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Li(e.name):Ke(e.name))===chunkGY3SWWW3_cjs.b(s,ie))return chunkGY3SWWW3_cjs.e(this,k,Jr).call(this,e,s,i,t)}},Jr=function(e,t,i,s){let h=t.name;return chunkGY3SWWW3_cjs.d(t,C,chunkGY3SWWW3_cjs.b(t,C)&He|ss(e)),h!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},ms=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d,ino:f,mode:w,mtime:S,mtimeMs:E,nlink:b,rdev:x,size:v,uid:R}=e;chunkGY3SWWW3_cjs.d(this,mi,t),chunkGY3SWWW3_cjs.d(this,pi,i),chunkGY3SWWW3_cjs.d(this,bi,s),chunkGY3SWWW3_cjs.d(this,gi,h),chunkGY3SWWW3_cjs.d(this,ai,n),chunkGY3SWWW3_cjs.d(this,ui,o),chunkGY3SWWW3_cjs.d(this,yi,a),chunkGY3SWWW3_cjs.d(this,di,l),chunkGY3SWWW3_cjs.d(this,ii,u),chunkGY3SWWW3_cjs.d(this,ni,d),chunkGY3SWWW3_cjs.d(this,li,f),chunkGY3SWWW3_cjs.d(this,si,w),chunkGY3SWWW3_cjs.d(this,wi,S),chunkGY3SWWW3_cjs.d(this,fi,E),chunkGY3SWWW3_cjs.d(this,ri,b),chunkGY3SWWW3_cjs.d(this,oi,x),chunkGY3SWWW3_cjs.d(this,ci,v),chunkGY3SWWW3_cjs.d(this,hi,R);let A=ss(e);chunkGY3SWWW3_cjs.d(this,C,chunkGY3SWWW3_cjs.b(this,C)&He|A|js),A!==bt&&A!==Wt&&A!==le&&chunkGY3SWWW3_cjs.d(this,C,chunkGY3SWWW3_cjs.b(this,C)|Ve);},We=new WeakMap,Pe=new WeakMap,qr=function(e){chunkGY3SWWW3_cjs.d(this,Pe,false);let t=chunkGY3SWWW3_cjs.b(this,We).slice();chunkGY3SWWW3_cjs.b(this,We).length=0,t.forEach(i=>i(null,e));},ye=new WeakMap,fr),Zr=class Vr extends at{constructor(i,s=bt,h,n,o,a,l){super(i,s,h,n,o,a,l);chunkGY3SWWW3_cjs.a(this,"sep","\\");chunkGY3SWWW3_cjs.a(this,"splitSep",Gn);}newChild(i,s=bt,h={}){return new Vr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return qi.win32.parse(i).root}getRoot(i){if(i=Un(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new vs(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace(Nr,"$1\\"),i===s}},Kr=class Yr extends at{constructor(i,s=bt,h,n,o,a,l){super(i,s,h,n,o,a,l);chunkGY3SWWW3_cjs.a(this,"splitSep","/");chunkGY3SWWW3_cjs.a(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=bt,h={}){return new Yr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},De,je,Si,vi,dr,Xr=(dr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ze}={}){chunkGY3SWWW3_cjs.a(this,"root");chunkGY3SWWW3_cjs.a(this,"rootPath");chunkGY3SWWW3_cjs.a(this,"roots");chunkGY3SWWW3_cjs.a(this,"cwd");chunkGY3SWWW3_cjs.c(this,De);chunkGY3SWWW3_cjs.c(this,je);chunkGY3SWWW3_cjs.c(this,Si);chunkGY3SWWW3_cjs.a(this,"nocase");chunkGY3SWWW3_cjs.c(this,vi);chunkGY3SWWW3_cjs.d(this,vi,jr(n)),(e instanceof URL||e.startsWith("file://"))&&(e=url.fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),chunkGY3SWWW3_cjs.d(this,De,new $s),chunkGY3SWWW3_cjs.d(this,je,new $s),chunkGY3SWWW3_cjs.d(this,Si,new Hn(h));let a=o.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(chunkGY3SWWW3_cjs.b(this,vi)),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,d=t.sep,f=this.rootPath,w=false;for(let S of a){let E=u--;l=l.child(S,{relative:new Array(E).fill("..").join(d),relativePosix:new Array(E).fill("..").join("/"),fullpath:f+=(w?"":d)+S}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return chunkGY3SWWW3_cjs.b(this,Si)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=chunkGY3SWWW3_cjs.b(this,De).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return chunkGY3SWWW3_cjs.b(this,De).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=chunkGY3SWWW3_cjs.b(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return chunkGY3SWWW3_cjs.b(this,je).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,S)=>{if(w)return f(w);let E=S.length;if(!E)return f();let b=()=>{--E===0&&f();};for(let x of S)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,n)?l(v,b):b()):x.shouldWalk(a,n)?l(x,b):b();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=(b,x,v=false)=>{if(b)return o.emit("error",b);if(s&&!v){let R=[];for(let A of x)A.isSymbolicLink()&&R.push(A.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(R.length){Promise.all(R).then(()=>S(null,x,true));return}}for(let R of x)R&&(!h||h(R))&&(o.write(i?R:R.fullpath())||(f=true));u--;for(let R of x){let A=R.realpathCached()||R;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):E||d();},E=true;w.readdirCB(S,true),E=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=w.readdirSync();for(let E of S)(!h||h(E))&&(o.write(i?E:E.fullpath())||(f=true));u--;for(let E of S){let b=E;if(E.isSymbolicLink()){if(!(s&&(b=E.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(a,n)&&l.push(b);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Gr](t);}},De=new WeakMap,je=new WeakMap,Si=new WeakMap,vi=new WeakMap,dr),vs=class extends Xr{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,qi.win32,"\\",{...i,nocase:s});chunkGY3SWWW3_cjs.a(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return qi.win32.parse(t).root.toUpperCase()}newRoot(t){return new Zr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Es=class extends Xr{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,qi.posix,"/",{...i,nocase:s});chunkGY3SWWW3_cjs.a(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Kr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Qr=class extends Es{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Zr:Kr;var Jn=process.platform==="win32"?vs:process.platform==="darwin"?Qr:Es,qn=e=>e.length>=1,Zn=e=>e.length>=1,Vn=Symbol.for("nodejs.util.inspect.custom"),I,lt,H,be,Lt,Ei,se,re,he,Ne,ze,th=(ze=class{constructor(t,i,s,h){chunkGY3SWWW3_cjs.c(this,I);chunkGY3SWWW3_cjs.c(this,lt);chunkGY3SWWW3_cjs.c(this,H);chunkGY3SWWW3_cjs.a(this,"length");chunkGY3SWWW3_cjs.c(this,be);chunkGY3SWWW3_cjs.c(this,Lt);chunkGY3SWWW3_cjs.c(this,Ei);chunkGY3SWWW3_cjs.c(this,se);chunkGY3SWWW3_cjs.c(this,re);chunkGY3SWWW3_cjs.c(this,he);chunkGY3SWWW3_cjs.c(this,Ne,true);if(!qn(t))throw new TypeError("empty pattern list");if(!Zn(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(chunkGY3SWWW3_cjs.d(this,I,t),chunkGY3SWWW3_cjs.d(this,lt,i),chunkGY3SWWW3_cjs.d(this,H,s),chunkGY3SWWW3_cjs.d(this,be,h),chunkGY3SWWW3_cjs.b(this,H)===0){if(this.isUNC()){let[n,o,a,l,...u]=chunkGY3SWWW3_cjs.b(this,I),[d,f,w,S,...E]=chunkGY3SWWW3_cjs.b(this,lt);u[0]===""&&(u.shift(),E.shift());let b=[n,o,a,l,""].join("/"),x=[d,f,w,S,""].join("/");chunkGY3SWWW3_cjs.d(this,I,[b,...u]),chunkGY3SWWW3_cjs.d(this,lt,[x,...E]),this.length=chunkGY3SWWW3_cjs.b(this,I).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=chunkGY3SWWW3_cjs.b(this,I),[a,...l]=chunkGY3SWWW3_cjs.b(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d=a+"/";chunkGY3SWWW3_cjs.d(this,I,[u,...o]),chunkGY3SWWW3_cjs.d(this,lt,[d,...l]),this.length=chunkGY3SWWW3_cjs.b(this,I).length;}}}[Vn](){return "Pattern <"+chunkGY3SWWW3_cjs.b(this,lt).slice(chunkGY3SWWW3_cjs.b(this,H)).join("/")+">"}pattern(){return chunkGY3SWWW3_cjs.b(this,I)[chunkGY3SWWW3_cjs.b(this,H)]}isString(){return typeof chunkGY3SWWW3_cjs.b(this,I)[chunkGY3SWWW3_cjs.b(this,H)]=="string"}isGlobstar(){return chunkGY3SWWW3_cjs.b(this,I)[chunkGY3SWWW3_cjs.b(this,H)]===ht}isRegExp(){return chunkGY3SWWW3_cjs.b(this,I)[chunkGY3SWWW3_cjs.b(this,H)]instanceof RegExp}globString(){return chunkGY3SWWW3_cjs.d(this,Ei,chunkGY3SWWW3_cjs.b(this,Ei)||(chunkGY3SWWW3_cjs.b(this,H)===0?this.isAbsolute()?chunkGY3SWWW3_cjs.b(this,lt)[0]+chunkGY3SWWW3_cjs.b(this,lt).slice(1).join("/"):chunkGY3SWWW3_cjs.b(this,lt).join("/"):chunkGY3SWWW3_cjs.b(this,lt).slice(chunkGY3SWWW3_cjs.b(this,H)).join("/")))}hasMore(){return this.length>chunkGY3SWWW3_cjs.b(this,H)+1}rest(){return chunkGY3SWWW3_cjs.b(this,Lt)!==void 0?chunkGY3SWWW3_cjs.b(this,Lt):this.hasMore()?(chunkGY3SWWW3_cjs.d(this,Lt,new ze(chunkGY3SWWW3_cjs.b(this,I),chunkGY3SWWW3_cjs.b(this,lt),chunkGY3SWWW3_cjs.b(this,H)+1,chunkGY3SWWW3_cjs.b(this,be))),chunkGY3SWWW3_cjs.d(chunkGY3SWWW3_cjs.b(this,Lt),he,chunkGY3SWWW3_cjs.b(this,he)),chunkGY3SWWW3_cjs.d(chunkGY3SWWW3_cjs.b(this,Lt),re,chunkGY3SWWW3_cjs.b(this,re)),chunkGY3SWWW3_cjs.d(chunkGY3SWWW3_cjs.b(this,Lt),se,chunkGY3SWWW3_cjs.b(this,se)),chunkGY3SWWW3_cjs.b(this,Lt)):chunkGY3SWWW3_cjs.d(this,Lt,null)}isUNC(){let t=chunkGY3SWWW3_cjs.b(this,I);return chunkGY3SWWW3_cjs.b(this,re)!==void 0?chunkGY3SWWW3_cjs.b(this,re):chunkGY3SWWW3_cjs.d(this,re,chunkGY3SWWW3_cjs.b(this,be)==="win32"&&chunkGY3SWWW3_cjs.b(this,H)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=chunkGY3SWWW3_cjs.b(this,I);return chunkGY3SWWW3_cjs.b(this,se)!==void 0?chunkGY3SWWW3_cjs.b(this,se):chunkGY3SWWW3_cjs.d(this,se,chunkGY3SWWW3_cjs.b(this,be)==="win32"&&chunkGY3SWWW3_cjs.b(this,H)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=chunkGY3SWWW3_cjs.b(this,I);return chunkGY3SWWW3_cjs.b(this,he)!==void 0?chunkGY3SWWW3_cjs.b(this,he):chunkGY3SWWW3_cjs.d(this,he,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=chunkGY3SWWW3_cjs.b(this,I)[0];return typeof t=="string"&&this.isAbsolute()&&chunkGY3SWWW3_cjs.b(this,H)===0?t:""}checkFollowGlobstar(){return !(chunkGY3SWWW3_cjs.b(this,H)===0||!this.isGlobstar()||!chunkGY3SWWW3_cjs.b(this,Ne))}markFollowGlobstar(){return chunkGY3SWWW3_cjs.b(this,H)===0||!this.isGlobstar()||!chunkGY3SWWW3_cjs.b(this,Ne)?false:(chunkGY3SWWW3_cjs.d(this,Ne,false),true)}},I=new WeakMap,lt=new WeakMap,H=new WeakMap,be=new WeakMap,Lt=new WeakMap,Ei=new WeakMap,se=new WeakMap,re=new WeakMap,he=new WeakMap,Ne=new WeakMap,ze),Kn=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Bs=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=Kn}){chunkGY3SWWW3_cjs.a(this,"relative");chunkGY3SWWW3_cjs.a(this,"relativeChildren");chunkGY3SWWW3_cjs.a(this,"absolute");chunkGY3SWWW3_cjs.a(this,"absoluteChildren");chunkGY3SWWW3_cjs.a(this,"platform");chunkGY3SWWW3_cjs.a(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new oe(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new th(s,h,0,this.platform),o=new oe(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},Yn=class eh{constructor(t=new Map){chunkGY3SWWW3_cjs.a(this,"store");this.store=t;}copy(){return new eh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},Xn=class{constructor(){chunkGY3SWWW3_cjs.a(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Qn=class{constructor(){chunkGY3SWWW3_cjs.a(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Us=class ih{constructor(t,i){chunkGY3SWWW3_cjs.a(this,"hasWalkedCache");chunkGY3SWWW3_cjs.a(this,"matches",new Xn);chunkGY3SWWW3_cjs.a(this,"subwalks",new Qn);chunkGY3SWWW3_cjs.a(this,"patterns");chunkGY3SWWW3_cjs.a(this,"follow");chunkGY3SWWW3_cjs.a(this,"dot");chunkGY3SWWW3_cjs.a(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new Yn;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===ht){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let S=h.parent||h;w?this.hasWalkedCache.hasWalked(S,w)||this.subwalks.add(S,w):this.matches.add(S,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ih(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===ht?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},to=(e,t)=>typeof e=="string"?new Bs([e],t):Array.isArray(e)?new Bs(e,t):e,_e,Jt,Se,St,ce,ws,gr,sh=(gr=class{constructor(e,t,i){chunkGY3SWWW3_cjs.c(this,St);chunkGY3SWWW3_cjs.a(this,"path");chunkGY3SWWW3_cjs.a(this,"patterns");chunkGY3SWWW3_cjs.a(this,"opts");chunkGY3SWWW3_cjs.a(this,"seen",new Set);chunkGY3SWWW3_cjs.a(this,"paused",false);chunkGY3SWWW3_cjs.a(this,"aborted",false);chunkGY3SWWW3_cjs.c(this,_e,[]);chunkGY3SWWW3_cjs.c(this,Jt);chunkGY3SWWW3_cjs.c(this,Se);chunkGY3SWWW3_cjs.a(this,"signal");chunkGY3SWWW3_cjs.a(this,"maxDepth");chunkGY3SWWW3_cjs.a(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,chunkGY3SWWW3_cjs.d(this,Se,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(chunkGY3SWWW3_cjs.d(this,Jt,to(i.ignore??[],i)),!this.includeChildMatches&&typeof chunkGY3SWWW3_cjs.b(this,Jt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{chunkGY3SWWW3_cjs.b(this,_e).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=chunkGY3SWWW3_cjs.b(this,_e).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?chunkGY3SWWW3_cjs.b(this,_e).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!chunkGY3SWWW3_cjs.e(this,St,ce).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(chunkGY3SWWW3_cjs.e(this,St,ce).call(this,e))return;if(!this.includeChildMatches&&chunkGY3SWWW3_cjs.b(this,Jt)?.add){let h=`${e.relativePosix()}/**`;chunkGY3SWWW3_cjs.b(this,Jt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?chunkGY3SWWW3_cjs.b(this,Se):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i){let h=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+chunkGY3SWWW3_cjs.b(this,Se))?"."+chunkGY3SWWW3_cjs.b(this,Se):"";this.matchEmit(h?n+h+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new Us(this.opts),i);}walkCB2(e,t,i,s){if(chunkGY3SWWW3_cjs.e(this,St,ws).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())chunkGY3SWWW3_cjs.e(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())chunkGY3SWWW3_cjs.e(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Us(this.opts),i);}walkCB2Sync(e,t,i,s){if(chunkGY3SWWW3_cjs.e(this,St,ws).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())chunkGY3SWWW3_cjs.e(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())chunkGY3SWWW3_cjs.e(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},_e=new WeakMap,Jt=new WeakMap,Se=new WeakMap,St=new WeakSet,ce=function(e){return this.seen.has(e)||!!chunkGY3SWWW3_cjs.b(this,Jt)?.ignored?.(e)},ws=function(e){return !!chunkGY3SWWW3_cjs.b(this,Jt)?.childrenIgnored?.(e)},gr),Gs=class extends sh{constructor(t,i,s){super(t,i,s);chunkGY3SWWW3_cjs.a(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Is=class extends sh{constructor(t,i,s){super(t,i,s);chunkGY3SWWW3_cjs.a(this,"results");this.results=new Ui({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},eo=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ee=class{constructor(e,t){chunkGY3SWWW3_cjs.a(this,"absolute");chunkGY3SWWW3_cjs.a(this,"cwd");chunkGY3SWWW3_cjs.a(this,"root");chunkGY3SWWW3_cjs.a(this,"dot");chunkGY3SWWW3_cjs.a(this,"dotRelative");chunkGY3SWWW3_cjs.a(this,"follow");chunkGY3SWWW3_cjs.a(this,"ignore");chunkGY3SWWW3_cjs.a(this,"magicalBraces");chunkGY3SWWW3_cjs.a(this,"mark");chunkGY3SWWW3_cjs.a(this,"matchBase");chunkGY3SWWW3_cjs.a(this,"maxDepth");chunkGY3SWWW3_cjs.a(this,"nobrace");chunkGY3SWWW3_cjs.a(this,"nocase");chunkGY3SWWW3_cjs.a(this,"nodir");chunkGY3SWWW3_cjs.a(this,"noext");chunkGY3SWWW3_cjs.a(this,"noglobstar");chunkGY3SWWW3_cjs.a(this,"pattern");chunkGY3SWWW3_cjs.a(this,"platform");chunkGY3SWWW3_cjs.a(this,"realpath");chunkGY3SWWW3_cjs.a(this,"scurry");chunkGY3SWWW3_cjs.a(this,"stat");chunkGY3SWWW3_cjs.a(this,"signal");chunkGY3SWWW3_cjs.a(this,"windowsPathsNoEscape");chunkGY3SWWW3_cjs.a(this,"withFileTypes");chunkGY3SWWW3_cjs.a(this,"includeChildMatches");chunkGY3SWWW3_cjs.a(this,"opts");chunkGY3SWWW3_cjs.a(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=url.fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||eo,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=t.platform==="win32"?vs:t.platform==="darwin"?Qr:t.platform?Es:Jn;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},h=this.pattern.map(a=>new oe(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new th(a,u,0,this.platform)});}async walk(){return [...await new Gs(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 Gs(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 Is(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 Is(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()}},io=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new oe(i,t).hasMagic())return true;return false};function Hi(e,t={}){return new Ee(e,t).streamSync()}function rh(e,t={}){return new Ee(e,t).stream()}function hh(e,t={}){return new Ee(e,t).walkSync()}async function Hs(e,t={}){return new Ee(e,t).walk()}function Ji(e,t={}){return new Ee(e,t).iterateSync()}function nh(e,t={}){return new Ee(e,t).iterate()}var so=Hi,ro=Object.assign(rh,{sync:Hi}),ho=Ji,no=Object.assign(nh,{sync:Ji}),oo=Object.assign(hh,{stream:Hi,iterate:Ji}),Gi=Object.assign(Hs,{glob:Hs,globSync:hh,sync:oo,globStream:rh,stream:ro,globStreamSync:Hi,streamSync:so,globIterate:nh,iterate:no,globIterateSync:Ji,iterateSync:ho,Glob:Ee,hasMagic:io,escape:Rr,unescape:Ce});Gi.glob=Gi;exports.a=void 0;(L=>{L.Level=lo__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(F){return t[F]>=t[i]}function h(){return i}L.getLevel=h;let n=new Map;L.Default=T({service:"default"});let a="";function l(){return a}L.file=l;let u,d,f=false,w=()=>{},S=false,E=false;async function b(F){if(f)return;if(F.print){f=true;return}F.level&&(i=F.level);let j=F.logDir||qi__default.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");await utils.initLog(F),F.logFile?a=qi__default.default.join(j,F.logFile??"gateway.log"):a=qi__default.default.join(j,"gateway.log");try{await oh__default.default.mkdir(j,{recursive:!0}),u=await oh__default.default.open(a,"a"),d=Rn.createWriteStream("",{fd:u.fd,autoClose:!1}),w=N=>{if(!(S||E||!d||d.destroyed))try{if(!d.writable)return;d.write(N,B=>{if(B&&!S){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(B){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch(N){process.stderr.write(`[LOG ERROR] Failed to init log file: ${N}
4
- `),w=B=>{try{process.stderr.write(B);}catch{}},f=true;}}L.init=b;async function x(){f&&(d&&!d.destroyed&&(await new Promise((F,j)=>{d.end(N=>{N?j(N):F();});}).catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${F}
5
- `);}),d=void 0),u&&(await u.close().catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${F}
6
- `);}),u=void 0),w=F=>{try{process.stderr.write(F);}catch{}},f=false);}L.close=x;function R(F,j=0){let N=F.message;return F.cause instanceof Error&&j<10?N+" Caused by: "+R(F.cause,j+1):N}let A=Date.now();function T(F){F=F||{};let j=F.service;if(j&&typeof j=="string"){let M=n.get(j);if(M)return M}function N(M,ot){let Zi=Object.entries({...F,...ot}).filter(([xs,qt])=>qt!=null).map(([xs,qt])=>{let Vi=`${xs}=`;return qt instanceof Error?Vi+R(qt):typeof qt=="object"?Vi+JSON.stringify(qt):Vi+qt}).join(" "),xe=new Date,lh=xe.getTime()-A;return A=xe.getTime(),[utils.formatLogTime(xe),"+"+lh+"ms",Zi,M].filter(Boolean).join(" ")+`
7
- `}let B={debug(M,ot){s("DEBUG")&&w("DEBUG "+N(M,ot));},info(M,ot){s("INFO")&&w("INFO "+N(M,ot));},error(M,ot){s("ERROR")&&w("ERROR "+N(M,ot));},warn(M,ot){s("WARN")&&w("WARN "+N(M,ot));},tag(M,ot){return F&&(F[M]=ot),B},clone(){return L.create({...F})},time(M,ot){let Zi=Date.now();B.info(M,{status:"started",...ot});function xe(){B.info(M,{status:"completed",duration:Date.now()-Zi,...ot});}return {stop:xe,[Symbol.dispose](){xe();}}}};return j&&typeof j=="string"&&n.set(j,B),B}L.create=T;})(exports.a||(exports.a={}));