@aikaara/chat-sdk 1.5.4 → 1.5.6
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/{AikaaraLinkButton-CBAy6ItK.cjs → AikaaraLinkButton-D8a5BwyA.cjs} +1 -1
- package/dist/{AikaaraLinkButton-DsJc3CEK.mjs → AikaaraLinkButton-hgl2FaWZ.mjs} +1 -1
- package/dist/{MountTenant-DcEbdQPG.mjs → MountTenant-BlwQ1aa2.mjs} +686 -643
- package/dist/{MountTenant-BEaYaZMk.cjs → MountTenant-DKtrLElG.cjs} +37 -37
- package/dist/cdn/aikaara-chat.iife.js +39 -39
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var AikaaraChat=(function(Pe){"use strict";class Uo{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class nn{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Uo(t,o=>{this.send({command:"message",identifier:t,data:JSON.stringify(o)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((o,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>o(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class mr{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(o){console.error(`Error in event handler for "${e}":`,o)}})}removeAllListeners(){this.handlers.clear()}}const Sc=1e3,Ec=10,Ac=400,Ic=600,Bo="#6366f1",Tc=12,Cc="system-ui, -apple-system, sans-serif",Do="Type a message...",Pc="bottom-right",Oc="light",Mc={x:20,y:20},on="aikaara_conversation_id";class $o extends mr{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new nn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,o){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...o&&{source:o}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Ec;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Sc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const o=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new nn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Fo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(o,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const i=await n.json();if(i&&typeof i=="object"&&"success"in i){if(!i.success)throw new Error(`API error: ${i.message||"Request failed"}`);return i.data}return i}async fetchWithHeaders(e,t,r){const o={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(o["X-Api-Key"]=this.apiKey),this.authToken&&(o.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:o};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class qo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const o={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(o),o}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(o=>o.status==="sending"&&o.role===e.role&&o.content===e.content&&o.conversationId===e.conversationId&&Date.now()-new Date(o.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const o=Ho(this._messages,e);return o?(Object.assign(o,e,{id:o.id}),{message:o,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(o=>o.externalId===e||o.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){const t=[];for(const r of e){const o=Ho(t,r);if(o){const n=gr(o),i=gr(r);!n&&i&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function Ho(s,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const i=gr(e),a=Wo(e),l=zo(e);if(!i&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=s.length-1;u>=0;u--){const d=s[u],f=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!f||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=gr(d);if(i&&y&&i===y)return d;const w=Wo(d);if(a&&w&&a===w)return d;const m=zo(d);if(l&&m&&l===m)return d}return null}function Wo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Vo(s);if(t)return t}function zo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(s.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=s.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function gr(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(s.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Vo(s);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function Vo(s){const e=s.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Ko{_conversationId;persist;constructor(e,t=!0){this.persist=t,this._conversationId=e||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(e){this._conversationId=e,this.persist&&e&&this.saveToStorage(e)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(on)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(on)}catch{return null}}saveToStorage(e){try{localStorage.setItem(on,e)}catch{}}}var sn=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,Lc=Object.getOwnPropertyNames,Nc=Object.prototype.hasOwnProperty,Ye=(s,e)=>()=>(s&&(e=s(s=0)),e),pe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Bt=(s,e)=>{for(var t in e)sn(s,t,{get:e[t],enumerable:!0})},jc=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Lc(e))!Nc.call(s,o)&&o!==t&&sn(s,o,{get:()=>e[o],enumerable:!(r=Rc(e,o))||r.enumerable});return s},Re=s=>jc(sn({},"__esModule",{value:!0}),s),le=Ye(()=>{}),Ne={};Bt(Ne,{_debugEnd:()=>Fn,_debugProcess:()=>$n,_events:()=>ni,_eventsCount:()=>ii,_exiting:()=>An,_fatalExceptions:()=>Un,_getActiveHandles:()=>es,_getActiveRequests:()=>Zo,_kill:()=>Cn,_linkedBinding:()=>Qo,_maxListeners:()=>ri,_preload_modules:()=>Zn,_rawDebug:()=>xn,_startProfilerIdleNotifier:()=>qn,_stopProfilerIdleNotifier:()=>Hn,_tickCallback:()=>Dn,abort:()=>Kn,addListener:()=>oi,allowedNodeEnvironmentFlags:()=>Nn,arch:()=>cn,argv:()=>hn,argv0:()=>Xn,assert:()=>ts,binding:()=>bn,browser:()=>_n,chdir:()=>wn,config:()=>In,cpuUsage:()=>Zt,cwd:()=>vn,debugPort:()=>Qn,default:()=>fi,dlopen:()=>Xo,domain:()=>En,emit:()=>ui,emitWarning:()=>gn,env:()=>dn,execArgv:()=>fn,execPath:()=>Jn,exit:()=>Rn,features:()=>jn,hasUncaughtExceptionCaptureCallback:()=>rs,hrtime:()=>br,kill:()=>Mn,listeners:()=>is,memoryUsage:()=>On,moduleLoadList:()=>Sn,nextTick:()=>Yo,off:()=>ai,on:()=>ct,once:()=>si,openStdin:()=>Ln,pid:()=>Gn,platform:()=>un,ppid:()=>Yn,prependListener:()=>di,prependOnceListener:()=>hi,reallyExit:()=>Tn,release:()=>kn,removeAllListeners:()=>ci,removeListener:()=>li,resourceUsage:()=>Pn,setSourceMapsEnabled:()=>ei,setUncaughtExceptionCaptureCallback:()=>Bn,stderr:()=>zn,stdin:()=>Vn,stdout:()=>Wn,title:()=>ln,umask:()=>yn,uptime:()=>ns,version:()=>pn,versions:()=>mn});function an(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function Uc(){!It||!Tt||(It=!1,Tt.length?tt=Tt.concat(tt):Xt=-1,tt.length&&Go())}function Go(){if(!It){var s=setTimeout(Uc,0);It=!0;for(var e=tt.length;e;){for(Tt=tt,tt=[];++Xt<e;)Tt&&Tt[Xt].run();Xt=-1,e=tt.length}Tt=null,It=!1,clearTimeout(s)}}function Yo(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Jo(s,e)),tt.length===1&&!It&&setTimeout(Go,0)}function Jo(s,e){this.fun=s,this.array=e}function He(){}function Qo(s){an("_linkedBinding")}function Xo(s){an("dlopen")}function Zo(){return[]}function es(){return[]}function ts(s,e){if(!s)throw new Error(e||"assertion error")}function rs(){return!1}function ns(){return ut.now()/1e3}function br(s){var e=Math.floor((Date.now()-ut.now())*.001),t=ut.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=yr)),[r,o]}function ct(){return fi}function is(s){return[]}var tt,It,Tt,Xt,ln,cn,un,dn,hn,fn,pn,mn,gn,bn,yn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Zt,Pn,On,Mn,Rn,Ln,Nn,jn,Un,Bn,Dn,$n,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ut,ti,yr,ri,ni,ii,oi,si,ai,li,ci,ui,di,hi,fi,Bc=Ye(()=>{le(),ue(),ce(),tt=[],It=!1,Xt=-1,Jo.prototype.run=function(){this.fun.apply(null,this.array)},ln="browser",cn="x64",un="browser",dn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},hn=["/usr/bin/node"],fn=[],pn="v16.8.0",mn={},gn=function(s,e){console.warn((e?e+": ":"")+s)},bn=function(s){an("binding")},yn=function(s){return 0},vn=function(){return"/"},wn=function(s){},kn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},_n=!0,xn=He,Sn=[],En={},An=!1,In={},Tn=He,Cn=He,Zt=function(){return{}},Pn=Zt,On=Zt,Mn=He,Rn=He,Ln=He,Nn={},jn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Un=He,Bn=He,Dn=He,$n=He,Fn=He,qn=He,Hn=He,Wn=void 0,zn=void 0,Vn=void 0,Kn=He,Gn=2,Yn=1,Jn="/bin/usr/node",Qn=9229,Xn="node",Zn=[],ei=He,ut={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ut.now===void 0&&(ti=Date.now(),ut.timing&&ut.timing.navigationStart&&(ti=ut.timing.navigationStart),ut.now=()=>Date.now()-ti),yr=1e9,br.bigint=function(s){var e=br(s);return typeof BigInt>"u"?e[0]*yr+e[1]:BigInt(e[0]*yr)+BigInt(e[1])},ri=10,ni={},ii=0,oi=ct,si=ct,ai=ct,li=ct,ci=ct,ui=He,di=ct,hi=ct,fi={version:pn,versions:mn,arch:cn,platform:un,browser:_n,release:kn,_rawDebug:xn,moduleLoadList:Sn,binding:bn,_linkedBinding:Qo,_events:ni,_eventsCount:ii,_maxListeners:ri,on:ct,addListener:oi,once:si,off:ai,removeListener:li,removeAllListeners:ci,emit:ui,prependListener:di,prependOnceListener:hi,listeners:is,domain:En,_exiting:An,config:In,dlopen:Xo,uptime:ns,_getActiveRequests:Zo,_getActiveHandles:es,reallyExit:Tn,_kill:Cn,cpuUsage:Zt,resourceUsage:Pn,memoryUsage:On,kill:Mn,exit:Rn,openStdin:Ln,allowedNodeEnvironmentFlags:Nn,assert:ts,features:jn,_fatalExceptions:Un,setUncaughtExceptionCaptureCallback:Bn,hasUncaughtExceptionCaptureCallback:rs,emitWarning:gn,nextTick:Yo,_tickCallback:Dn,_debugProcess:$n,_debugEnd:Fn,_startProfilerIdleNotifier:qn,_stopProfilerIdleNotifier:Hn,stdout:Wn,stdin:Vn,stderr:zn,abort:Kn,umask:yn,chdir:wn,cwd:vn,env:dn,title:ln,argv:hn,execArgv:fn,pid:Gn,ppid:Yn,execPath:Jn,debugPort:Qn,hrtime:br,argv0:Xn,_preload_modules:Zn,setSourceMapsEnabled:ei}}),ce=Ye(()=>{Bc()});function Dc(){if(pi)return Dt;pi=!0,Dt.byteLength=a,Dt.toByteArray=c,Dt.fromByteArray=f;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,n=r.length;o<n;++o)s[o]=r[o],e[r.charCodeAt(o)]=o;e[45]=62,e[95]=63;function i(g){var h=g.length;if(h%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=h);var y=b===h?0:4-b%4;return[b,y]}function a(g){var h=i(g),b=h[0],y=h[1];return(b+y)*3/4-y}function l(g,h,b){return(h+b)*3/4-b}function c(g){var h,b=i(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)h=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=h>>16&255,m[k++]=h>>8&255,m[k++]=h&255;return w===2&&(h=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=h&255),w===1&&(h=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=h>>8&255,m[k++]=h&255),m}function u(g){return s[g>>18&63]+s[g>>12&63]+s[g>>6&63]+s[g&63]}function d(g,h,b){for(var y,w=[],m=h;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function f(g){for(var h,b=g.length,y=b%3,w=[],m=16383,k=0,x=b-y;k<x;k+=m)w.push(d(g,k,k+m>x?x:k+m));return y===1?(h=g[b-1],w.push(s[h>>2]+s[h<<4&63]+"==")):y===2&&(h=(g[b-2]<<8)+g[b-1],w.push(s[h>>10]+s[h>>4&63]+s[h<<2&63]+"=")),w.join("")}return Dt}function $c(){return mi?er:(mi=!0,er.read=function(s,e,t,r,o){var n,i,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?o-1:0,f=t?-1:1,g=s[e+d];for(d+=f,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+s[e+d],d+=f,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+s[e+d],d+=f,u-=8);if(n===0)n=1-c;else{if(n===l)return i?NaN:(g?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(g?-1:1)*i*Math.pow(2,n-r)},er.write=function(s,e,t,r,o,n){var i,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,h=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-i))<1&&(i--,l*=2),i+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(i++,l/=2),i+d>=u?(a=0,i=u):i+d>=1?(a=(e*l-1)*Math.pow(2,o),i=i+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),i=0));o>=8;s[t+g]=a&255,g+=h,a/=256,o-=8);for(i=i<<o|a,c+=o;c>0;s[t+g]=i&255,g+=h,i/=256,c-=8);s[t+g-h]|=b*128},er)}function Fc(){if(gi)return vt;gi=!0;let s=Dc(),e=$c(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;vt.Buffer=i,vt.SlowBuffer=w,vt.INSPECT_MAX_BYTES=50;let r=2147483647;vt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=o(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let p=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(p,_),p.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function n(p){if(p>r)throw new RangeError('The value "'+p+'" is invalid for option "size"');let _=new Uint8Array(p);return Object.setPrototypeOf(_,i.prototype),_}function i(p,_,A){if(typeof p=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(p)}return a(p,_,A)}i.poolSize=8192;function a(p,_,A){if(typeof p=="string")return d(p,_);if(ArrayBuffer.isView(p))return g(p);if(p==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p);if(H(p,ArrayBuffer)||p&&H(p.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(p,SharedArrayBuffer)||p&&H(p.buffer,SharedArrayBuffer)))return h(p,_,A);if(typeof p=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=p.valueOf&&p.valueOf();if(B!=null&&B!==p)return i.from(B,_,A);let X=b(p);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof p[Symbol.toPrimitive]=="function")return i.from(p[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p)}i.from=function(p,_,A){return a(p,_,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function l(p){if(typeof p!="number")throw new TypeError('"size" argument must be of type number');if(p<0)throw new RangeError('The value "'+p+'" is invalid for option "size"')}function c(p,_,A){return l(p),p<=0?n(p):_!==void 0?typeof A=="string"?n(p).fill(_,A):n(p).fill(_):n(p)}i.alloc=function(p,_,A){return c(p,_,A)};function u(p){return l(p),n(p<0?0:y(p)|0)}i.allocUnsafe=function(p){return u(p)},i.allocUnsafeSlow=function(p){return u(p)};function d(p,_){if((typeof _!="string"||_==="")&&(_="utf8"),!i.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(p,_)|0,B=n(A),X=B.write(p,_);return X!==A&&(B=B.slice(0,X)),B}function f(p){let _=p.length<0?0:y(p.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=p[B]&255;return A}function g(p){if(H(p,Uint8Array)){let _=new Uint8Array(p);return h(_.buffer,_.byteOffset,_.byteLength)}return f(p)}function h(p,_,A){if(_<0||p.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(p.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(p):A===void 0?B=new Uint8Array(p,_):B=new Uint8Array(p,_,A),Object.setPrototypeOf(B,i.prototype),B}function b(p){if(i.isBuffer(p)){let _=y(p.length)|0,A=n(_);return A.length===0||p.copy(A,0,0,_),A}if(p.length!==void 0)return typeof p.length!="number"||me(p.length)?n(0):f(p);if(p.type==="Buffer"&&Array.isArray(p.data))return f(p.data)}function y(p){if(p>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return p|0}function w(p){return+p!=p&&(p=0),i.alloc(+p)}i.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==i.prototype},i.compare=function(p,_){if(H(p,Uint8Array)&&(p=i.from(p,p.offset,p.byteLength)),H(_,Uint8Array)&&(_=i.from(_,_.offset,_.byteLength)),!i.isBuffer(p)||!i.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===_)return 0;let A=p.length,B=_.length;for(let X=0,de=Math.min(A,B);X<de;++X)if(p[X]!==_[X]){A=p[X],B=_[X];break}return A<B?-1:B<A?1:0},i.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(p,_){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return i.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<p.length;++A)_+=p[A].length;let B=i.allocUnsafe(_),X=0;for(A=0;A<p.length;++A){let de=p[A];if(H(de,Uint8Array))X+de.length>B.length?(i.isBuffer(de)||(de=i.from(de)),de.copy(B,X)):Uint8Array.prototype.set.call(B,de,X);else if(i.isBuffer(de))de.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return B};function m(p,_){if(i.isBuffer(p))return p.length;if(ArrayBuffer.isView(p)||H(p,ArrayBuffer))return p.byteLength;if(typeof p!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof p);let A=p.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return F(p).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(p).length;default:if(X)return B?-1:F(p).length;_=(""+_).toLowerCase(),X=!0}}i.byteLength=m;function k(p,_,A){let B=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(p||(p="utf8");;)switch(p){case"hex":return V(this,_,A);case"utf8":case"utf-8":return q(this,_,A);case"ascii":return ae(this,_,A);case"latin1":case"binary":return Y(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(B)throw new TypeError("Unknown encoding: "+p);p=(p+"").toLowerCase(),B=!0}}i.prototype._isBuffer=!0;function x(p,_,A){let B=p[_];p[_]=p[A],p[A]=B}i.prototype.swap16=function(){let p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<p;_+=2)x(this,_,_+1);return this},i.prototype.swap32=function(){let p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<p;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},i.prototype.swap64=function(){let p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<p;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},i.prototype.toString=function(){let p=this.length;return p===0?"":arguments.length===0?q(this,0,p):k.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(p){if(!i.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:i.compare(this,p)===0},i.prototype.inspect=function(){let p="",_=vt.INSPECT_MAX_BYTES;return p=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(p+=" ... "),"<Buffer "+p+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(p,_,A,B,X){if(H(p,Uint8Array)&&(p=i.from(p,p.offset,p.byteLength)),!i.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(_===void 0&&(_=0),A===void 0&&(A=p?p.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),_<0||A>p.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&_>=A)return 0;if(B>=X)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,X>>>=0,this===p)return 0;let de=X-B,_e=A-_,z=Math.min(de,_e),ie=this.slice(B,X),Ee=p.slice(_,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){de=ie[Ae],_e=Ee[Ae];break}return de<_e?-1:_e<de?1:0};function v(p,_,A,B,X){if(p.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:p.length-1),A<0&&(A=p.length+A),A>=p.length){if(X)return-1;A=p.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof _=="string"&&(_=i.from(_,B)),i.isBuffer(_))return _.length===0?-1:E(p,_,A,B,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(p,_,A):Uint8Array.prototype.lastIndexOf.call(p,_,A):E(p,[_],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(p,_,A,B,X){let de=1,_e=p.length,z=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(p.length<2||_.length<2)return-1;de=2,_e/=2,z/=2,A/=2}function ie(Ae,Te){return de===1?Ae[Te]:Ae.readUInt16BE(Te*de)}let Ee;if(X){let Ae=-1;for(Ee=A;Ee<_e;Ee++)if(ie(p,Ee)===ie(_,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*de}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>_e&&(A=_e-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Te=0;Te<z;Te++)if(ie(p,Ee+Te)!==ie(_,Te)){Ae=!1;break}if(Ae)return Ee}return-1}i.prototype.includes=function(p,_,A){return this.indexOf(p,_,A)!==-1},i.prototype.indexOf=function(p,_,A){return v(this,p,_,A,!0)},i.prototype.lastIndexOf=function(p,_,A){return v(this,p,_,A,!1)};function S(p,_,A,B){A=Number(A)||0;let X=p.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let de=_.length;B>de/2&&(B=de/2);let _e;for(_e=0;_e<B;++_e){let z=parseInt(_.substr(_e*2,2),16);if(me(z))return _e;p[A+_e]=z}return _e}function I(p,_,A,B){return ye(F(_,p.length-A),p,A,B)}function P(p,_,A,B){return ye(ee(_),p,A,B)}function O(p,_,A,B){return ye(fe(_),p,A,B)}function j(p,_,A,B){return ye(he(_,p.length-A),p,A,B)}i.prototype.write=function(p,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-_;if((A===void 0||A>X)&&(A=X),p.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return S(this,p,_,A);case"utf8":case"utf-8":return I(this,p,_,A);case"ascii":case"latin1":case"binary":return P(this,p,_,A);case"base64":return O(this,p,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,p,_,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(p,_,A){return _===0&&A===p.length?s.fromByteArray(p):s.fromByteArray(p.slice(_,A))}function q(p,_,A){A=Math.min(p.length,A);let B=[],X=_;for(;X<A;){let de=p[X],_e=null,z=de>239?4:de>223?3:de>191?2:1;if(X+z<=A){let ie,Ee,Ae,Te;switch(z){case 1:de<128&&(_e=de);break;case 2:ie=p[X+1],(ie&192)===128&&(Te=(de&31)<<6|ie&63,Te>127&&(_e=Te));break;case 3:ie=p[X+1],Ee=p[X+2],(ie&192)===128&&(Ee&192)===128&&(Te=(de&15)<<12|(ie&63)<<6|Ee&63,Te>2047&&(Te<55296||Te>57343)&&(_e=Te));break;case 4:ie=p[X+1],Ee=p[X+2],Ae=p[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Te=(de&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Te>65535&&Te<1114112&&(_e=Te))}}_e===null?(_e=65533,z=1):_e>65535&&(_e-=65536,B.push(_e>>>10&1023|55296),_e=56320|_e&1023),B.push(_e),X+=z}return U(B)}let D=4096;function U(p){let _=p.length;if(_<=D)return String.fromCharCode.apply(String,p);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,p.slice(B,B+=D));return A}function ae(p,_,A){let B="";A=Math.min(p.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(p[X]&127);return B}function Y(p,_,A){let B="";A=Math.min(p.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(p[X]);return B}function V(p,_,A){let B=p.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let X="";for(let de=_;de<A;++de)X+=ve[p[de]];return X}function re(p,_,A){let B=p.slice(_,A),X="";for(let de=0;de<B.length-1;de+=2)X+=String.fromCharCode(B[de]+B[de+1]*256);return X}i.prototype.slice=function(p,_){let A=this.length;p=~~p,_=_===void 0?A:~~_,p<0?(p+=A,p<0&&(p=0)):p>A&&(p=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<p&&(_=p);let B=this.subarray(p,_);return Object.setPrototypeOf(B,i.prototype),B};function $(p,_,A){if(p%1!==0||p<0)throw new RangeError("offset is not uint");if(p+_>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p],X=1,de=0;for(;++de<_&&(X*=256);)B+=this[p+de]*X;return B},i.prototype.readUintBE=i.prototype.readUIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p+--_],X=1;for(;_>0&&(X*=256);)B+=this[p+--_]*X;return B},i.prototype.readUint8=i.prototype.readUInt8=function(p,_){return p=p>>>0,_||$(p,1,this.length),this[p]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(p,_){return p=p>>>0,_||$(p,2,this.length),this[p]|this[p+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(p,_){return p=p>>>0,_||$(p,2,this.length),this[p]<<8|this[p+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(p,_){return p=p>>>0,_||$(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},i.prototype.readBigUInt64LE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=_+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,X=this[++p]+this[++p]*2**8+this[++p]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=_*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],X=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p],X=1,de=0;for(;++de<_&&(X*=256);)B+=this[p+de]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*_)),B},i.prototype.readIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=_,X=1,de=this[p+--B];for(;B>0&&(X*=256);)de+=this[p+--B]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*_)),de},i.prototype.readInt8=function(p,_){return p=p>>>0,_||$(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},i.prototype.readInt16LE=function(p,_){p=p>>>0,_||$(p,2,this.length);let A=this[p]|this[p+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(p,_){p=p>>>0,_||$(p,2,this.length);let A=this[p+1]|this[p]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},i.prototype.readInt32BE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},i.prototype.readBigInt64LE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++p]*256+this[++p]*65536+this[++p]*16777216)}),i.prototype.readBigInt64BE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=(_<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(B)<<BigInt(32))+BigInt(this[++p]*16777216+this[++p]*65536+this[++p]*256+A)}),i.prototype.readFloatLE=function(p,_){return p=p>>>0,_||$(p,4,this.length),e.read(this,p,!0,23,4)},i.prototype.readFloatBE=function(p,_){return p=p>>>0,_||$(p,4,this.length),e.read(this,p,!1,23,4)},i.prototype.readDoubleLE=function(p,_){return p=p>>>0,_||$(p,8,this.length),e.read(this,p,!0,52,8)},i.prototype.readDoubleBE=function(p,_){return p=p>>>0,_||$(p,8,this.length),e.read(this,p,!1,52,8)};function Z(p,_,A,B,X,de){if(!i.isBuffer(p))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<de)throw new RangeError('"value" argument is out of bounds');if(A+B>p.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Z(this,p,_,A,_e,0)}let X=1,de=0;for(this[_]=p&255;++de<A&&(X*=256);)this[_+de]=p/X&255;return _+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Z(this,p,_,A,_e,0)}let X=A-1,de=1;for(this[_+X]=p&255;--X>=0&&(de*=256);)this[_+X]=p/de&255;return _+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,1,255,0),this[_]=p&255,_+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,65535,0),this[_]=p&255,this[_+1]=p>>>8,_+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,65535,0),this[_]=p>>>8,this[_+1]=p&255,_+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,4294967295,0),this[_+3]=p>>>24,this[_+2]=p>>>16,this[_+1]=p>>>8,this[_]=p&255,_+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,4294967295,0),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4};function M(p,_,A,B,X){G(_,B,X,p,A,7);let de=Number(_&BigInt(4294967295));p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,A}function Q(p,_,A,B,X){G(_,B,X,p,A,7);let de=Number(_&BigInt(4294967295));p[A+7]=de,de=de>>8,p[A+6]=de,de=de>>8,p[A+5]=de,de=de>>8,p[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A+3]=_e,_e=_e>>8,p[A+2]=_e,_e=_e>>8,p[A+1]=_e,_e=_e>>8,p[A]=_e,A+8}i.prototype.writeBigUInt64LE=se(function(p,_=0){return M(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(p,_=0){return Q(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,p,_,A,z-1,-z)}let X=0,de=1,_e=0;for(this[_]=p&255;++X<A&&(de*=256);)p<0&&_e===0&&this[_+X-1]!==0&&(_e=1),this[_+X]=(p/de>>0)-_e&255;return _+A},i.prototype.writeIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,p,_,A,z-1,-z)}let X=A-1,de=1,_e=0;for(this[_+X]=p&255;--X>=0&&(de*=256);)p<0&&_e===0&&this[_+X+1]!==0&&(_e=1),this[_+X]=(p/de>>0)-_e&255;return _+A},i.prototype.writeInt8=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,1,127,-128),p<0&&(p=255+p+1),this[_]=p&255,_+1},i.prototype.writeInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,32767,-32768),this[_]=p&255,this[_+1]=p>>>8,_+2},i.prototype.writeInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,32767,-32768),this[_]=p>>>8,this[_+1]=p&255,_+2},i.prototype.writeInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,2147483647,-2147483648),this[_]=p&255,this[_+1]=p>>>8,this[_+2]=p>>>16,this[_+3]=p>>>24,_+4},i.prototype.writeInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4},i.prototype.writeBigInt64LE=se(function(p,_=0){return M(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(p,_=0){return Q(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(p,_,A,B,X,de){if(A+B>p.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(p,_,A,B,X){return _=+_,A=A>>>0,X||be(p,_,A,4),e.write(p,_,A,B,23,4),A+4}i.prototype.writeFloatLE=function(p,_,A){return te(this,p,_,!0,A)},i.prototype.writeFloatBE=function(p,_,A){return te(this,p,_,!1,A)};function we(p,_,A,B,X){return _=+_,A=A>>>0,X||be(p,_,A,8),e.write(p,_,A,B,52,8),A+8}i.prototype.writeDoubleLE=function(p,_,A){return we(this,p,_,!0,A)},i.prototype.writeDoubleBE=function(p,_,A){return we(this,p,_,!1,A)},i.prototype.copy=function(p,_,A,B){if(!i.isBuffer(p))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=p.length&&(_=p.length),_||(_=0),B>0&&B<A&&(B=A),B===A||p.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),p.length-_<B-A&&(B=p.length-_+A);let X=B-A;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(p,this.subarray(A,B),_),X},i.prototype.fill=function(p,_,A,B){if(typeof p=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!i.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(p.length===1){let de=p.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(p=de)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,p||(p=0);let X;if(typeof p=="number")for(X=_;X<A;++X)this[X]=p;else{let de=i.isBuffer(p)?p:i.from(p,B),_e=de.length;if(_e===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=de[X%_e]}return this};let K={};function N(p,_,A){K[p]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${p}]`,this.stack,delete this.name}get code(){return p}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${p}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(p){return p?`${p} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(p,_){return`The "${p}" argument must be of type number. Received type ${typeof _}`},TypeError),N("ERR_OUT_OF_RANGE",function(p,_,A){let B=`The value of "${p}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${_}. Received ${X}`,B},RangeError);function ne(p){let _="",A=p.length,B=p[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${p.slice(A-3,A)}${_}`;return`${p.slice(0,A)}${_}`}function W(p,_,A){J(_,"offset"),(p[_]===void 0||p[_+A]===void 0)&&ge(_,p.length-(A+1))}function G(p,_,A,B,X,de){if(p>A||p<_){let _e=typeof _=="bigint"?"n":"",z;throw _===0||_===BigInt(0)?z=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:z=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new K.ERR_OUT_OF_RANGE("value",z,p)}W(B,X,de)}function J(p,_){if(typeof p!="number")throw new K.ERR_INVALID_ARG_TYPE(_,"number",p)}function ge(p,_,A){throw Math.floor(p)!==p?(J(p,A),new K.ERR_OUT_OF_RANGE("offset","an integer",p)):_<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,p)}let oe=/[^+/0-9A-Za-z-_]/g;function R(p){if(p=p.split("=")[0],p=p.trim().replace(oe,""),p.length<2)return"";for(;p.length%4!==0;)p=p+"=";return p}function F(p,_){_=_||1/0;let A,B=p.length,X=null,de=[];for(let _e=0;_e<B;++_e){if(A=p.charCodeAt(_e),A>55295&&A<57344){if(!X){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===B){(_-=3)>-1&&de.push(239,191,189);continue}X=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(_-=3)>-1&&de.push(239,191,189);if(X=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function ee(p){let _=[];for(let A=0;A<p.length;++A)_.push(p.charCodeAt(A)&255);return _}function he(p,_){let A,B,X,de=[];for(let _e=0;_e<p.length&&!((_-=2)<0);++_e)A=p.charCodeAt(_e),B=A>>8,X=A%256,de.push(X),de.push(B);return de}function fe(p){return s.toByteArray(R(p))}function ye(p,_,A,B){let X;for(X=0;X<B&&!(X+A>=_.length||X>=p.length);++X)_[X+A]=p[X];return X}function H(p,_){return p instanceof _||p!=null&&p.constructor!=null&&p.constructor.name!=null&&p.constructor.name===_.name}function me(p){return p!==p}let ve=(function(){let p="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)_[B+X]=p[A]+p[X]}return _})();function se(p){return typeof BigInt>"u"?Ce:p}function Ce(){throw new Error("BigInt not supported")}return vt}var Dt,pi,er,mi,vt,gi,qc=Ye(()=>{le(),ue(),ce(),Dt={},pi=!1,er={},mi=!1,vt={},gi=!1}),$e={};Bt($e,{Buffer:()=>vr,INSPECT_MAX_BYTES:()=>os,default:()=>dt,kMaxLength:()=>ss});var dt,vr,os,ss,Fe=Ye(()=>{le(),ue(),ce(),qc(),dt=Fc(),dt.Buffer,dt.SlowBuffer,dt.INSPECT_MAX_BYTES,dt.kMaxLength,vr=dt.Buffer,os=dt.INSPECT_MAX_BYTES,ss=dt.kMaxLength}),ue=Ye(()=>{Fe()}),Be=pe((s,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let o="";for(let n=0;n<r.length;n++)o+=` ${r[n].stack}
|
|
2
|
-
`;super(o),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,o){return r.includes(o)},ArrayPrototypeIndexOf(r,o){return r.indexOf(o)},ArrayPrototypeJoin(r,o){return r.join(o)},ArrayPrototypeMap(r,o){return r.map(o)},ArrayPrototypePop(r,o){return r.pop(o)},ArrayPrototypePush(r,o){return r.push(o)},ArrayPrototypeSlice(r,o,n){return r.slice(o,n)},Error,FunctionPrototypeCall(r,o,...n){return r.call(o,...n)},FunctionPrototypeSymbolHasInstance(r,o){return Function.prototype[Symbol.hasInstance].call(r,o)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,o){return Object.defineProperties(r,o)},ObjectDefineProperty(r,o,n){return Object.defineProperty(r,o,n)},ObjectGetOwnPropertyDescriptor(r,o){return Object.getOwnPropertyDescriptor(r,o)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,o){return Object.setPrototypeOf(r,o)},Promise,PromisePrototypeCatch(r,o){return r.catch(o)},PromisePrototypeThen(r,o,n){return r.then(o,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,o){return r.test(o)},SafeSet:Set,String,StringPrototypeSlice(r,o,n){return r.slice(o,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,o,n){return r.set(o,n)},Boolean,Uint8Array}}),as=pe((s,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[o,n]){let i=r.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),Ke=pe((s,e)=>{le(),ue(),ce();var{format:t,inspect:r}=as(),{AggregateError:o}=Be(),n=globalThis.AggregateError||o,i=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function f(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function g(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function h(m,k,x){x||(x=Error);class v extends x{constructor(...S){super(g(m,k,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:x.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${m}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=m,v.prototype[i]=!0,u[m]=v}function b(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function y(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};h("ERR_ASSERTION","%s",Error),h("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],I=[];for(let O of k)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?E.push(O.toLowerCase()):l.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(S.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var P;if((P=x.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${x.constructor.name}`;else{let O=r(x,{depth:-1});v+=`. Received ${O}`}}else{let O=r(x,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof x} (${O})`}return v},TypeError),h("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),h("ERR_INVALID_RETURN_VALUE",(m,k,x)=>{var v;let E=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${k}" function but got ${E}.`},TypeError),h("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),h("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=f(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=f(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),h("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),h("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),h("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),h("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),h("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),h("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),h("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),h("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),h("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),h("ERR_STREAM_WRITE_AFTER_END","write after end",Error),h("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),tr=pe((s,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),wt={};Bt(wt,{EventEmitter:()=>ls,default:()=>$t,defaultMaxListeners:()=>cs,init:()=>us,listenerCount:()=>ds,on:()=>hs,once:()=>fs});function Hc(){if(bi)return rr;bi=!0;var s=typeof Reflect=="object"?Reflect:null,e=s&&typeof s.apply=="function"?s.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;s&&typeof s.ownKeys=="function"?t=s.ownKeys:Object.getOwnPropertySymbols?t=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:t=function(x){return Object.getOwnPropertyNames(x)};function r(x){console&&console.warn&&console.warn(x)}var o=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}rr=n,rr.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function a(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");i=x}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var j=I[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,q=h(j,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,P,O;if(a(E),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),P=x._events),O=P[v]),O===void 0)O=P[v]=E,++x._eventsCount;else if(typeof O=="function"?O=P[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),I=l(x),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=x,j.type=v,j.count=O.length,r(j)}return x}n.prototype.addListener=function(x,v){return c(this,x,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(x,v){return c(this,x,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(x,v){return a(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,P,O;if(a(v),S=this._events,S===void 0)return this;if(E=S[x],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[x],S.removeListener&&this.emit("removeListener",x,E.listener||v));else if(typeof E!="function"){for(I=-1,P=E.length-1;P>=0;P--)if(E[P]===v||E[P].listener===v){O=E[P].listener,I=P;break}if(I<0)return this;I===0?E.shift():b(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[x]),this;if(arguments.length===0){var I=Object.keys(E),P;for(S=0;S<I.length;++S)P=I[S],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(x,v[S]);return this};function f(x,v,E){var S=x._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?y(I):h(I,I.length)}n.prototype.listeners=function(x){return f(this,x,!0)},n.prototype.rawListeners=function(x){return f(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function h(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function b(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function w(x,v){return new Promise(function(E,S){function I(O){x.removeListener(v,P),S(O)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}k(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&k(x,"error",v,E)}function k(x,v,E,S){if(typeof x.on=="function")S.once?x.once(v,E):x.on(v,E);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(P){S.once&&x.removeEventListener(v,I),E(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return rr}var rr,bi,$t,ls,cs,us,ds,hs,fs,Ct=Ye(()=>{le(),ue(),ce(),rr={},bi=!1,$t=Hc(),$t.once,$t.once=function(s,e){return new Promise((t,r)=>{function o(...i){n!==void 0&&s.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{s.removeListener(name,o),r(i)},s.once("error",n)),s.once(e,o)})},$t.on=function(s,e){let t=[],r=[],o=null,n=!1,i={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(o){let u=Promise.reject(o);return o=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){s.removeListener(e,a),s.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){o=c,s.removeListener(e,a),s.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return s.on(e,a),s.on("error",l),i;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):o=c,i.return()}},{EventEmitter:ls,defaultMaxListeners:cs,init:us,listenerCount:ds,on:hs,once:fs}=$t}),Je=pe((s,e)=>{le(),ue(),ce();var t=(Fe(),Re($e)),{format:r,inspect:o}=as(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:i,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||tr().AbortSignal,u=globalThis.AbortController||tr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||t.Blob,g=typeof f<"u"?function(y){return y instanceof f}:function(y){return!1},h=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,k)=>{y=m,w=k}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((k,...x)=>k?m(k):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Ct(),Re(wt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);h(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[i]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(k=>{h(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),nr=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:f,String:g,StringPrototypeToUpperCase:h,StringPrototypeTrim:b}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:E}=Je(),{isAsyncFunction:S,isArrayBufferView:I}=Je().types,P={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(f(T,H)===null)throw new k(me,H,q);H=u(H,8)}return Y(H,me),H}var U=y((H,me,ve=c,se=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=y((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);let se=ve?1:0,Ce=4294967295;if(H<se||H>Ce)throw new x(me,`>= ${se} && <= ${Ce}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&a(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var $=y((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+o(n(ve,Ce=>typeof Ce=="string"?`'${Ce}'`:g(Ce)),", ");throw new k(me,H,se)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!d(H,me)?ve:H[me]}var Q=y((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Ce=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Ce||typeof H!="function"))throw new m(me,"Object",H)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new k(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function K(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function N(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Ce=`${me}[${ve}]`;if(se==null)throw new m(Ce,"AbortSignal",se);ge(se,Ce)}}function ne(H,me="signal"){if(V(H,me),P[H]===void 0)throw P[h(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=y((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function G(H,me){let ve=E(me),se=H.length;if(ve==="hex"&&se%2!==0)throw new k("encoding",me,`is invalid for data of length ${se}`)}function J(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&b(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),F=y((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${o(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!f(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let se=0;se<me;se++){let Ce=H[se];fe(Ce,"hints"),ve+=Ce,se!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:j,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:K,validateAbortSignalArray:N,validateBoolean:Z,validateBuffer:W,validateDictionary:be,validateEncoding:G,validateFunction:oe,validateInt32:ae,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:$,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:F,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Pt=pe((s,e)=>{le(),ue(),ce();var t=e.exports={},r,o;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?o=clearTimeout:o=i}catch{o=i}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(o===clearTimeout)return clearTimeout(w);if((o===i||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(w);try{return o(w)}catch{try{return o.call(null,w)}catch{return o.call(this,w)}}}var c=[],u=!1,d,f=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):f=-1,c.length&&h())}function h(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++f<m;)d&&d[f].run();f=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new b(w,m)),c.length===1&&!u&&a(h)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),ht=pe((s,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Be(),n=o("nodejs.stream.destroyed"),i=o("nodejs.stream.errored"),a=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),c=o("nodejs.stream.disturbed"),u=o("nodejs.webstream.isClosedPromise"),d=o("nodejs.webstream.controllerErrorFunction");function f(M,Q=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function g(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.writable)!==!1))}function h(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function b(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!b(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!b(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!b(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function k(M){return y(M)||w(M)||m(M)}function x(M,Q){return M==null?!1:Q===!0?typeof M[t]=="function":Q===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function S(M,Q){if(!g(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||Q===!1&&be.ended===!0&&be.length===0)}function I(M){if(!f(M))return null;if(M.readableEnded===!0)return!0;let Q=M._readableState;return!Q||Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function P(M,Q){if(!f(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||Q===!1&&be.ended===!0&&be.length===0)}function O(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:f(M)&&M.readable&&!P(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!E(M)}function T(M,Q){return b(M)?v(M)?!0:!(Q?.readable!==!1&&O(M)||Q?.writable!==!1&&j(M)):null}function q(M){var Q,be;return b(M)?M.writableErrored?M.writableErrored:(Q=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,be;return b(M)?M.readableErrored?M.readableErrored:(Q=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!b(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,be=M._readableState;return typeof Q?.closed=="boolean"||typeof be?.closed=="boolean"?Q?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var Q;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((Q=M.req)===null||Q===void 0?void 0:Q.upgradeOrConnect)===void 0}function re(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function $(M){var Q;return!!(M&&((Q=M[c])!==null&&Q!==void 0?Q:M.readableDidRead||M.readableAborted))}function Z(M){var Q,be,te,we,K,N,ne,W,G,J;return!!(M&&((Q=(be=(te=(we=(K=(N=M[i])!==null&&N!==void 0?N:M.readableErrored)!==null&&K!==void 0?K:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(W=M._writableState)===null||W===void 0?void 0:W.errorEmitted)!==null&&be!==void 0?be:(G=M._readableState)===null||G===void 0?void 0:G.errored)!==null&&Q!==void 0?Q:!((J=M._writableState)===null||J===void 0)&&J.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:$,kIsDisturbed:c,isErrored:Z,kIsErrored:i,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:h,isFinished:T,isIterable:x,isReadableNodeStream:f,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:D,isNodeStream:b,isWebStream:k,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),kt=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{AbortError:r,codes:o}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=o,{kEmptyObject:a,once:l}=Je(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:f}=nr(),{Promise:g,PromisePrototypeThen:h,SymbolDispose:b}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:q}=ht(),D;function U($){return $.setHeader&&typeof $.abort=="function"}var ae=()=>{};function Y($,Z,M){var Q,be;if(arguments.length===2?(M=Z,Z=a):Z==null?Z=a:d(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),k($)||I($))return V($,Z,M);if(!j($))throw new n("stream",["ReadableStream","WritableStream","Stream"],$);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m($),we=(be=Z.writable)!==null&&be!==void 0?be:S($),K=$._writableState,N=$._readableState,ne=()=>{$.writable||J()},W=T($)&&m($)===te&&S($)===we,G=P($,!1),J=()=>{G=!0,$.destroyed&&(W=!1),!(W&&(!$.readable||te))&&(!te||ge)&&M.call($)},ge=x($,!1),oe=()=>{ge=!0,$.destroyed&&(W=!1),!(W&&(!$.writable||we))&&(!we||G)&&M.call($)},R=H=>{M.call($,H)},F=y($),ee=()=>{F=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);if(te&&!ge&&m($,!0)&&!x($,!1))return M.call($,new i);if(we&&!G&&!P($,!1))return M.call($,new i);M.call($)},he=()=>{F=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);M.call($)},fe=()=>{$.req.on("finish",J)};U($)?($.on("complete",J),W||$.on("abort",ee),$.req?fe():$.on("request",fe)):we&&!K&&($.on("end",ne),$.on("close",ne)),!W&&typeof $.aborted=="boolean"&&$.on("aborted",ee),$.on("end",oe),$.on("finish",J),Z.error!==!1&&$.on("error",R),$.on("close",ee),F?t.nextTick(ee):K!=null&&K.errorEmitted||N!=null&&N.errorEmitted?W||t.nextTick(he):(!te&&(!W||w($))&&(G||E($)===!1)||!we&&(!W||E($))&&(ge||w($)===!1)||N&&$.req&&$.aborted)&&t.nextTick(he);let ye=()=>{M=ae,$.removeListener("aborted",ee),$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",fe),$.req&&$.req.removeListener("finish",J),$.removeListener("end",ne),$.removeListener("close",ne),$.removeListener("finish",J),$.removeListener("end",oe),$.removeListener("error",R),$.removeListener("close",ee)};if(Z.signal&&!F){let H=()=>{let me=M;ye(),me.call($,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Je().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...se)=>{me[b](),ve.apply($,se)})}}return ye}function V($,Z,M){let Q=!1,be=ae;if(Z.signal)if(be=()=>{Q=!0,M.call($,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||Je().addAbortListener;let we=D(Z.signal,be),K=M;M=l((...N)=>{we[b](),K.apply($,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply($,we))};return h($[q].promise,te,te),ae}function re($,Z){var M;let Q=!1;return Z===null&&(Z=a),(M=Z)!==null&&M!==void 0&&M.cleanup&&(f(Z.cleanup,"cleanup"),Q=Z.cleanup),new g((be,te)=>{let we=Y($,Z,K=>{Q&&we(),K?te(K):be()})})}e.exports=Y,e.exports.finished=re}),Ft=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ke(),{Symbol:i}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=ht(),d=i("kDestroy"),f=i("kConstruct");function g(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function h(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(g(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?b(this,T,q):this.once(d,function(Y){b(this,r(Y,T),q)}),this)}function b(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;g(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let D=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||D!=null&&D.errorEmitted||(U&&(U.errorEmitted=!0),D&&(D.errorEmitted=!0),T.emit("error",q))}function k(){let T=this._readableState,q=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,D){let U=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(q):q&&(q.stack,ae&&!ae.errored&&(ae.errored=q),U&&!U.errored&&(U.errored=q),D?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(f,q),!(T.listenerCount(f)>1)&&t.nextTick(E,T)}function E(T){let q=!1;function D(U){if(q){x(T,U??new o);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(d,U):U?x(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,U)}}function S(T){T.emit(f)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,q){T.emit("error",q),t.nextTick(P,T)}function j(T,q){!T||l(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(O,T,q):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:h,undestroy:k,errorOrDestroy:x}}),yi=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:o}=(Ct(),Re(wt));function n(a){o.call(this,a)}r(n.prototype,o.prototype),r(n,o),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",h));let f=!1;function g(){f||(f=!0,a.end())}function h(){f||(f=!0,typeof a.destroy=="function"&&a.destroy())}function b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}i(c,"error",b),i(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",h),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function i(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:i}}),wr=pe((s,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:o}=Ke(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:a}=ht(),l=kt(),{ERR_INVALID_ARG_TYPE:c}=o,u,d=(f,g)=>{if(typeof f!="object"||!("aborted"in f))throw new c(g,"AbortSignal",f)};e.exports.addAbortSignal=function(f,g){if(d(f,"signal"),!n(g)&&!i(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(f,g)},e.exports.addAbortSignalNoValidate=function(f,g){if(typeof f!="object"||!("aborted"in f))return g;let h=n(g)?()=>{g.destroy(new r(void 0,{cause:f.reason}))}:()=>{g[a](new r(void 0,{cause:f.reason}))};if(f.aborted)h();else{u=u||Je().addAbortListener;let b=u(f,h);l(g,b[t])}return g}}),Wc=pe((s,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Be(),{Buffer:i}=(Fe(),Re($e)),{inspect:a}=Je();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return i.alloc(0);let c=i.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)o(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let f=u.data;if(l>f.length)c+=f,l-=f.length;else{l===f.length?(c+=f,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(f,0,l),this.head=u,u.data=t(f,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=i.allocUnsafe(l),u=l,d=this.head,f=0;do{let g=d.data;if(l>g.length)o(c,g,u-l),l-=g.length;else{l===g.length?(o(c,g,u-l),++f,d.next?this.head=d.next:this.head=this.tail=null):(o(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++f}while((d=d.next)!==null);return this.length-=f,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),kr=pe((s,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:o}=nr(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,i=16*1024,a=16;function l(f,g,h){return f.highWaterMark!=null?f.highWaterMark:g?f[h]:null}function c(f){return f?a:i}function u(f,g){o(g,"value",0),f?a=g:i=g}function d(f,g,h,b){let y=l(g,b,h);if(y!=null){if(!r(y)||y<0){let w=b?`options.${h}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(f.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),zc=pe((s,e)=>{le(),ue(),ce();var t=(Fe(),Re($e)),r=t.Buffer;function o(i,a){for(var l in i)a[l]=i[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,s),s.Buffer=n);function n(i,a,l){return r(i,a,l)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(i,a,l){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,a,l)},n.alloc=function(i,a,l){if(typeof i!="number")throw new TypeError("Argument must be a number");var c=r(i);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return r(i)},n.allocUnsafeSlow=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(i)}}),Vc=pe(s=>{le(),ue(),ce();var e=zc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function o(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}s.StringDecoder=n;function n(m){this.encoding=o(m);var k;switch(this.encoding){case"utf16le":this.text=f,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=h,this.end=b,k=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function i(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,x){var v=k.length-1;if(v<x)return 0;var E=i(k[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=i(k[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=i(k[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function f(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function h(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-x))}function b(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),ps=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Be(),{Buffer:i}=(Fe(),Re($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,f){let g;if(typeof d=="string"||d instanceof i)return new u({objectMode:!0,...f,read(){this.push(d),this.push(null)}});let h;if(d&&d[o])h=!0,g=d[o]();else if(d&&d[n])h=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...f}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof g.throw=="function";if(x&&v){let{value:E,done:S}=await g.throw(k);if(await E,S)return}if(typeof g.return=="function"){let{value:E}=await g.return();await E}}async function m(){for(;;){try{let{value:k,done:x}=h?await g.next():g.next();if(x)b.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(k){b.destroy(k)}break}}return b}e.exports=c}),_r=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:f,SymbolAsyncIterator:g,Symbol:h}=Be();e.exports=se,se.ReadableState=ve;var{EventEmitter:b}=(Ct(),Re(wt)),{Stream:y,prependListener:w}=yi(),{Buffer:m}=(Fe(),Re($e)),{addAbortSignal:k}=wr(),x=kt(),v=Je().debuglog("stream",C=>{v=C}),E=Wc(),S=Ft(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=kr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ae}=Ke(),{validateObject:Y}=nr(),V=h("kPaused"),{StringDecoder:re}=Vc(),$=ps();c(se.prototype,y.prototype),c(se,y);var Z=()=>{},{errorOrDestroy:M}=S,Q=1,be=2,te=4,we=8,K=16,N=32,ne=64,W=128,G=256,J=512,ge=1024,oe=2048,R=4096,F=8192,ee=16384,he=32768,fe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(L){L?this.state|=C:this.state&=~C}}}a(ve.prototype,{objectMode:me(Q),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(K),sync:me(N),needReadable:me(ne),emittedReadable:me(W),readableListening:me(G),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me(F),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,ke){typeof ke!="boolean"&&(ke=L instanceof ft()),this.state=oe|R|K|N,C&&C.objectMode&&(this.state|=Q),ke&&C&&C.readableObjectMode&&(this.state|=Q),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let L=this instanceof ft();this._readableState=new ve(C,this,L),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!L&&k(C.signal,this)),y.call(this,C),S.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=S.destroy,se.prototype._undestroy=S.undestroy,se.prototype._destroy=function(C,L){L(C)},se.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[f]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((L,ke)=>x(this,xe=>xe&&xe!==C?ke(xe):L(null)))},se.prototype.push=function(C,L){return Ce(this,C,L,!1)},se.prototype.unshift=function(C,L){return Ce(this,C,L,!0)};function Ce(C,L,ke,xe){v("readableAddChunk",L);let Se=C._readableState,De;if((Se.state&Q)===0&&(typeof L=="string"?(ke=ke||Se.defaultEncoding,Se.encoding!==ke&&(xe&&Se.encoding?L=m.from(L,ke).toString(Se.encoding):(L=m.from(L,ke),ke=""))):L instanceof m?ke="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),ke=""):L!=null&&(De=new j("chunk",["string","Buffer","Uint8Array"],L))),De)M(C,De);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&Q)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;p(C,Se,L,!0)}else if(Se.ended)M(C,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!ke?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?p(C,Se,L,!1):z(C,Se)):p(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function p(C,L,ke,xe){L.flowing&&L.length===0&&!L.sync&&C.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,C.emit("data",ke)):(L.length+=L.objectMode?1:ke.length,xe?L.buffer.unshift(ke):L.buffer.push(ke),(L.state&ne)!==0&&de(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,xe="";for(let Se of ke)xe+=L.write(Se);return ke.clear(),xe!==""&&ke.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(C){if(C>_)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,L){return C<=0||L.length===0&&L.ended?0:(L.state&Q)!==0?1:n(C)?L.flowing&&L.length?L.buffer.first().length:L.length:C<=L.length?C:L.ended?L.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=i(C,10));let L=this._readableState,ke=C;if(C>L.highWaterMark&&(L.highWaterMark=A(C)),C!==0&&(L.state&=~W),C===0&&L.needReadable&&((L.highWaterMark!==0?L.length>=L.highWaterMark:L.length>0)||L.ended))return v("read: emitReadable",L.length,L.ended),L.length===0&&L.ended?st(this):de(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&st(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|N,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(De){M(this,De)}L.state&=~N,L.reading||(C=B(ke,L))}let Se;return C>0?Se=Jt(C,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,C=0):(L.length-=C,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),ke!==C&&L.ended&&st(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let ke=L.decoder.end();ke&&ke.length&&(L.buffer.push(ke),L.length+=L.objectMode?1:ke.length)}L.ended=!0,L.sync?de(C):(L.needReadable=!1,L.emittedReadable=!0,_e(C))}}function de(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(_e,C))}function _e(C){let L=C._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(C.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,it(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let ke=L.length;if(v("maybeReadMore read 0"),C.read(0),ke===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let ke=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ge:Ut;xe.endEmitted?t.nextTick(Se):ke.once("end",Se),C.on("unpipe",De);function De(lt,yt){v("onunpipe"),lt===ke&&yt&&yt.hasUnpiped===!1&&(yt.hasUnpiped=!0,hr())}function Ge(){v("onend"),C.end()}let et,dr=!1;function hr(){v("cleanup"),C.removeListener("close",at),C.removeListener("finish",At),et&&C.removeListener("drain",et),C.removeListener("error",jt),C.removeListener("unpipe",De),ke.removeListener("end",Ge),ke.removeListener("end",Ut),ke.removeListener("data",rn),dr=!0,et&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&et()}function fr(){dr||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),ke.pause()),et||(et=Ee(ke,C),C.on("drain",et))}ke.on("data",rn);function rn(lt){v("ondata");let yt=C.write(lt);v("dest.write",yt),yt===!1&&fr()}function jt(lt){if(v("onerror",lt),Ut(),C.removeListener("error",jt),C.listenerCount("error")===0){let yt=C._writableState||C._readableState;yt&&!yt.errorEmitted?M(C,lt):C.emit("error",lt)}}w(C,"error",jt);function at(){C.removeListener("finish",At),Ut()}C.once("close",at);function At(){v("onfinish"),C.removeListener("close",at),Ut()}C.once("finish",At);function Ut(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?fr():xe.flowing||(v("pipe resume"),ke.resume()),C};function Ee(C,L){return function(){let ke=C._readableState;ke.awaitDrainWriters===L?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(L)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,ke={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let De=0;De<Se.length;De++)Se[De].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},se.prototype.on=function(C,L){let ke=y.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?de(this):xe.reading||t.nextTick(Te,this)),ke},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let ke=y.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),ke},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Te(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[V]=!1,this};function Oe(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(nt,C,L))}function nt(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),it(C),L.flowing&&!L.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[V]=!0,this};function it(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let ke=l(C);for(let xe=1;xe<ke.length;xe++){let Se=ke[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[g]=function(){return Ve(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ve(this,C)};function Ve(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let ke=ot(C,L);return ke.stream=C,ke}async function*ot(C,L){let ke=Z;function xe(Ge){this===C?(ke(),ke=Z):ke=Ge}C.on("readable",xe);let Se,De=x(C,{writable:!1},Ge=>{Se=Ge?O(Se,Ge):null,ke(),ke=Z});try{for(;;){let Ge=C.destroyed?null:C.read();if(Ge!==null)yield Ge;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ge){throw Se=O(Se,Ge),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),De())}}a(se.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[V]!==!1},set(C){this[V]=!!C}}}),se._fromList=Jt;function Jt(C,L){if(L.length===0)return null;let ke;return L.objectMode?ke=L.buffer.shift():!C||C>=L.length?(L.decoder?ke=L.buffer.join(""):L.buffer.length===1?ke=L.buffer.first():ke=L.buffer.concat(L.length),L.buffer.clear()):ke=L.buffer.consume(C,L.decoder),ke}function st(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ze,L,C))}function Ze(C,L){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(tn,L);else if(C.autoDestroy){let ke=L._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&L.destroy()}}}function tn(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return $(se,C,L)};var Qt;function ur(){return Qt===void 0&&(Qt={}),Qt}se.fromWeb=function(C,L){return ur().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return ur().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var ke,xe;return new se({objectMode:(ke=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&ke!==void 0?ke:!0,...L,destroy(Se,De){S.destroyer(C,Se),De(Se)}}).wrap(C)}}),vi=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=U;var{EventEmitter:f}=(Ct(),Re(wt)),g=yi().Stream,{Buffer:h}=(Fe(),Re($e)),b=Ft(),{addAbortSignal:y}=wr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=kr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=b;l(Y.prototype,g.prototype),l(Y,g);function q(){}var D=u("kOnFinished");function U(R,F,ee){typeof ee!="boolean"&&(ee=F instanceof ft()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?w(this,R,"writableHighWaterMark",ee):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(R&&R.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.bind(void 0,F),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ae(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!R||R.emitClose!==!1,this.autoDestroy=!R||R.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[D]=[]}function ae(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},i(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let F=this instanceof ft();if(!F&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,F),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&y(R.signal,this)),g.call(this,R),b.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}i(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new E)};function V(R,F,ee,he){let fe=R._writableState;if(typeof ee=="function")he=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!h.isEncoding(ee))throw new j(ee);typeof he!="function"&&(he=q)}if(F===null)throw new P;if(!fe.objectMode)if(typeof F=="string")fe.decodeStrings!==!1&&(F=h.from(F,ee),ee="buffer");else if(F instanceof h)ee="buffer";else if(g._isUint8Array(F))F=g._uint8ArrayToBuffer(F),ee="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],F);let ye;return fe.ending?ye=new O:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(he,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,F,ee,he))}Y.prototype.write=function(R,F,ee){return V(this,R,F,ee)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=c(R)),!h.isEncoding(R))throw new j(R);return this._writableState.defaultEncoding=R,this};function re(R,F,ee,he,fe){let ye=F.objectMode?1:ee.length;F.length+=ye;let H=F.length<F.highWaterMark;return H||(F.needDrain=!0),F.writing||F.corked||F.errored||!F.constructed?(F.buffered.push({chunk:ee,encoding:he,callback:fe}),F.allBuffers&&he!=="buffer"&&(F.allBuffers=!1),F.allNoop&&fe!==q&&(F.allNoop=!1)):(F.writelen=ye,F.writecb=fe,F.writing=!0,F.sync=!0,R._write(ee,he,F.onwrite),F.sync=!1),H&&!F.errored&&!F.destroyed}function $(R,F,ee,he,fe,ye,H){F.writelen=he,F.writecb=H,F.writing=!0,F.sync=!0,F.destroyed?F.onwrite(new S("write")):ee?R._writev(fe,F.onwrite):R._write(fe,ye,F.onwrite),F.sync=!1}function Z(R,F,ee,he){--F.pendingcb,he(ee),te(F),T(R,ee)}function M(R,F){let ee=R._writableState,he=ee.sync,fe=ee.writecb;if(typeof fe!="function"){T(R,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,F?(F.stack,ee.errored||(ee.errored=F),R._readableState&&!R._readableState.errored&&(R._readableState.errored=F),he?t.nextTick(Z,R,ee,F,fe):Z(R,ee,F,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),he?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(Q,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function Q({stream:R,state:F,count:ee,cb:he}){return F.afterWriteTickInfo=null,be(R,F,ee,he)}function be(R,F,ee,he){for(!F.ending&&!R.destroyed&&F.length===0&&F.needDrain&&(F.needDrain=!1,R.emit("drain"));ee-- >0;)F.pendingcb--,he();F.destroyed&&te(F),W(R,F)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var F;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H((F=R.errored)!==null&&F!==void 0?F:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=R.errored)!==null&&he!==void 0?he:new S("end"))}ae(R)}function we(R,F){if(F.corked||F.bufferProcessing||F.destroyed||!F.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=F,ye=ee.length-he;if(!ye)return;let H=he;if(F.bufferProcessing=!0,ye>1&&R._writev){F.pendingcb-=ye-1;let me=F.allNoop?q:se=>{for(let Ce=H;Ce<ee.length;++Ce)ee[Ce].callback(se)},ve=F.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=F.allBuffers,$(R,F,!0,F.length,ve,"",me),ae(F)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Ce=fe?1:me.length;$(R,F,!1,Ce,me,ve,se)}while(H<ee.length&&!F.writing);H===ee.length?ae(F):H>256?(ee.splice(0,H),F.bufferedIndex=0):F.bufferedIndex=H}F.bufferProcessing=!1}Y.prototype._write=function(R,F,ee){if(this._writev)this._writev([{chunk:R,encoding:F}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,F,ee){let he=this._writableState;typeof R=="function"?(ee=R,R=null,F=null):typeof F=="function"&&(ee=F,F=null);let fe;if(R!=null){let ye=V(this,R,F);ye instanceof o&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,W(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||he.finished?t.nextTick(ee,fe):he[D].push(ee)),this};function K(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function N(R,F){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,F.pendingcb--,fe){let ye=F[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,F.sync)}else K(F)&&(F.prefinished=!0,R.emit("prefinish"),F.pendingcb++,t.nextTick(G,R,F))}F.sync=!0,F.pendingcb++;try{R._final(he)}catch(fe){he(fe)}F.sync=!1}function ne(R,F){!F.prefinished&&!F.finalCalled&&(typeof R._final=="function"&&!F.destroyed?(F.finalCalled=!0,N(R,F)):(F.prefinished=!0,R.emit("prefinish")))}function W(R,F,ee){K(F)&&(ne(R,F),F.pendingcb===0&&(ee?(F.pendingcb++,t.nextTick((he,fe)=>{K(fe)?G(he,fe):fe.pendingcb--},R,F)):K(F)&&(F.pendingcb++,G(R,F))))}function G(R,F){F.pendingcb--,F.finished=!0;let ee=F[D].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(R.emit("finish"),F.autoDestroy){let he=R._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&R.destroy()}}a(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var J=b.destroy;Y.prototype.destroy=function(R,F){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,F),this},Y.prototype._undestroy=b.undestroy,Y.prototype._destroy=function(R,F){F(R)},Y.prototype[f.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,F){return oe().newStreamWritableFromWritableStream(R,F)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Kc=pe((s,e)=>{le(),ue(),ce();var t=Pt(),r=(Fe(),Re($e)),{isReadable:o,isWritable:n,isIterable:i,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:f}=ht(),g=kt(),{AbortError:h,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Ft(),m=ft(),k=_r(),x=vi(),{createDeferredPromise:v}=Je(),E=ps(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},P=globalThis.AbortController||tr().AbortController,{FunctionPrototypeCall:O}=Be(),j=class extends m{constructor(D){super(D),D?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),D?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function D(U,ae){if(u(U))return U;if(l(U))return q({readable:U});if(c(U))return q({writable:U});if(a(U))return q({writable:!1,readable:!1});if(d(U))return q({readable:k.fromWeb(U)});if(f(U))return q({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:V,write:re,final:$,destroy:Z}=T(U);if(i(V))return E(j,V,{objectMode:!0,write:re,final:$,destroy:Z});let M=V?.then;if(typeof M=="function"){let Q,be=O(M,V,te=>{if(te!=null)throw new y("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){$(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new y("Iterable, AsyncIterable or AsyncFunction",ae,V)}if(I(U))return D(U.arrayBuffer());if(i(U))return E(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&f(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let V=U!=null&&U.readable?l(U?.readable)?U?.readable:D(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:D(U.writable):void 0;return q({readable:V,writable:re})}let Y=U?.then;if(typeof Y=="function"){let V;return O(Y,U,re=>{re!=null&&V.push(re),V.push(null)},re=>{w(V,re)}),V=new j({objectMode:!0,writable:!1,read(){}})}throw new b(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new P,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:$,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new h(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield $}})(),{signal:V}),write(re,$,Z){let M=ae;ae=null,M({chunk:re,done:!1,cb:Z})},final(re){let $=ae;ae=null,$({done:!0,cb:re})},destroy(re,$){Y.abort(),$(re)}}}function q(D){let U=D.readable&&typeof D.readable.read!="function"?k.wrap(D.readable):D.readable,ae=D.writable,Y=!!o(U),V=!!n(ae),re,$,Z,M,Q;function be(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(g(ae,te=>{V=!1,te&&w(U,te),be(te)}),Q._write=function(te,we,K){ae.write(te,we)?K():re=K},Q._final=function(te){ae.end(),$=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if($){let te=$;$=null,te()}})),Y&&(g(U,te=>{Y=!1,te&&w(U,te),be(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){Q.push(null)}),Q._read=function(){for(;;){let te=U.read();if(te===null){Z=Q._read;return}if(!Q.push(te))return}}),Q._destroy=function(te,we){!te&&M!==null&&(te=new h),Z=null,re=null,$=null,M===null?we(te):(M=we,w(ae,te),w(U,te))},Q}}),ft=pe((s,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=Be();e.exports=l;var i=_r(),a=vi();n(l.prototype,i.prototype),n(l,i);{let f=o(a.prototype);for(let g=0;g<f.length;g++){let h=f[g];l.prototype[h]||(l.prototype[h]=a.prototype[h])}}function l(f){if(!(this instanceof l))return new l(f);i.call(this,f),a.call(this,f),f?(this.allowHalfOpen=f.allowHalfOpen!==!1,f.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),f.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(f){this._readableState&&this._writableState&&(this._readableState.destroyed=f,this._writableState.destroyed=f)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(f,g){return u().newStreamDuplexFromReadableWritablePair(f,g)},l.toWeb=function(f){return u().newReadableWritablePairFromDuplex(f)};var d;l.from=function(f){return d||(d=Kc()),d(f,"body")}}),ms=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ke().codes,n=ft(),{getHighWaterMark:i}=kr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let f=d?i(this,d,"readableHighWaterMark",!0):null;f===0&&(d={...d,highWaterMark:null,readableHighWaterMark:f,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((f,g)=>{if(f){d?d(f):this.destroy(f);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,f,g){throw new o("_transform()")},l.prototype._write=function(d,f,g){let h=this._readableState,b=this._writableState,y=h.length;this._transform(d,f,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===h.length||h.length<h.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),gs=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=o;var r=ms();t(o.prototype,r.prototype),t(o,r);function o(n){if(!(this instanceof o))return new o(n);r.call(this,n)}o.prototype._transform=function(n,i,a){a(null,n)}}),wi=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:i}=Be(),a=kt(),{once:l}=Je(),c=Ft(),u=ft(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:h,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:k}=nr(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:j}=ht(),T=globalThis.AbortController||tr().AbortController,q,D,U;function ae(te,we,K){let N=!1;te.on("close",()=>{N=!0});let ne=a(te,{readable:we,writable:K},W=>{N=!W});return{destroy:W=>{N||(N=!0,c.destroyer(te,W||new b("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(x(te))return te;if(E(te))return re(te);throw new f("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=_r()),yield*D.prototype[n].call(te)}async function $(te,we,K,{end:N}){let ne,W=null,G=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},J=()=>new o((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",G);let ge=a(we,{readable:!1},G);try{we.writableNeedDrain&&await J();for await(let oe of te)we.write(oe)||await J();N&&(we.end(),await J()),K()}catch(oe){K(ne!==oe?d(ne,oe):oe)}finally{ge(),we.off("drain",G)}}async function Z(te,we,K,{end:N}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let W of te)await ne.ready,ne.write(W).catch(()=>{});await ne.ready,N&&await ne.close(),K()}catch(W){try{await ne.abort(W),K(W)}catch(G){K(G)}}}function M(...te){return Q(te,l(Y(te)))}function Q(te,we,K){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new h("streams");let N=new T,ne=N.signal,W=K?.signal,G=[];k(W,"options.signal");function J(){fe(new w)}U=U||Je().addAbortListener;let ge;W&&(ge=U(W,J));let oe,R,F=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,se){var Ce;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;F.length;)F.shift()(oe);(Ce=ge)===null||Ce===void 0||Ce[i](),N.abort(),se&&(oe||G.forEach(p=>p()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Ce=ve<te.length-1,p=ve>0,_=Ce||K?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(_){let{destroy:X,cleanup:de}=ae(se,Ce,p);F.push(X),v(se)&&A&&G.push(de)}se.on("error",B),v(se)&&A&&G.push(()=>{se.removeListener("error",B)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Ce){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=gs());let B=new q({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&B.write(z),_&&B.end(),t.nextTick(he)},z=>{B.destroy(z),t.nextTick(he,z)});else if(x(ye,!0))ee++,$(ye,B,he,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,$(z,B,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:_e}=ae(ye,!1,!0);F.push(de),A&&G.push(_e)}}else if(S(se)){if(E(ye)){ee+=2;let B=be(ye,se,he,{end:_});v(se)&&A&&G.push(B)}else if(I(ye)||O(ye)){let B=ye.readable||ye;ee++,$(B,se,he,{end:_})}else if(x(ye))ee++,$(ye,se,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(P(se)){if(E(ye))ee++,Z(V(ye),se,he,{end:_});else if(O(ye)||x(ye))ee++,Z(ye,se,he,{end:_});else if(I(ye))ee++,Z(ye.readable,se,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(J),ye}function be(te,we,K,{end:N}){let ne=!1;if(we.on("close",()=>{ne||K(new y)}),te.pipe(we,{end:!1}),N){let W=function(){ne=!0,we.end()};j(te)?t.nextTick(W):te.once("end",W)}else K();return a(te,{readable:!0,writable:!1},W=>{let G=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",K).once("error",K):K(W)}),a(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:Q,pipeline:M}}),bs=pe((s,e)=>{le(),ue(),ce();var{pipeline:t}=wi(),r=ft(),{destroyer:o}=Ft(),{isNodeStream:n,isReadable:i,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=ht(),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:h}}=Ke(),b=kt();e.exports=function(...y){if(y.length===0)throw new h("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(i(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,x,v,E;function S(T){let q=v;v=null,q?q(T):T?E.destroy(T):!j&&!O&&E.destroy()}let I=y[0],P=t(y,S),O=!!(a(I)||u(I)||c(I)),j=!!(i(P)||d(P)||c(P));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:j}),O){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),k=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(l(I)){let q=(c(I)?I.writable:I).getWriter();E._write=async function(D,U,ae){try{await q.ready,q.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},E._final=async function(D){try{await q.ready,q.close().catch(()=>{}),k=D}catch(U){D(U)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let q=k;k=null,q()}})}if(j){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=P.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new f),x=null,m=null,k=null,v===null?q(T):(v=q,n(P)&&o(P,T))},E}}),Gc=pe((s,e)=>{le(),ue(),ce();var t=globalThis.AbortController||tr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=nr(),d=Be().Symbol("kWeak"),f=Be().Symbol("kResistStopPropagation"),{finished:g}=kt(),h=bs(),{addAbortSignalNoValidate:b}=wr(),{isWritable:y,isNodeStream:w}=ht(),{deprecate:m}=Je(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=Be(),q=T("kEmpty"),D=T("kEof");function U(W,G){if(G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),w(W)&&!y(W))throw new r("stream",W,"must be writable");let J=h(this,W);return G!=null&&G.signal&&b(G.signal,J),J}function ae(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal");let J=1;G?.concurrency!=null&&(J=v(G.concurrency));let ge=J-1;return G?.highWaterMark!=null&&(ge=v(G.highWaterMark)),c(J,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=J,(async function*(){let oe=Je().AbortSignalAny([G?.signal].filter(x)),R=this,F=[],ee={signal:oe},he,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!ye&&H<J&&F.length<ge&&(fe(),fe=null)}async function Ce(){try{for await(let p of R){if(ye)return;if(oe.aborted)throw new a;try{if(p=W(p,ee),p===q)continue;p=O(p)}catch(_){p=P(_)}H+=1,j(p,ve,me),F.push(p),he&&(he(),he=null),!ye&&(F.length>=ge||H>=J)&&await new I(_=>{fe=_})}F.push(D)}catch(p){let _=P(p);j(_,ve,me),F.push(_)}finally{ye=!0,he&&(he(),he=null)}}Ce();try{for(;;){for(;F.length>0;){let p=await F[0];if(p===D)return;if(oe.aborted)throw new a;p!==q&&(yield p),F.shift(),se()}await new I(p=>{he=p})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal"),(async function*(){let G=0;for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new a({cause:W.signal.reason});yield[G++,ge]}}).call(this)}async function V(W,G=void 0){for await(let J of M.call(this,W,G))return!0;return!1}async function re(W,G=void 0){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...J)=>!await W(...J),G)}async function $(W,G){for await(let J of M.call(this,W,G))return J}async function Z(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,J,G));}function M(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,J,G)}var Q=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(W,G,J){var ge;if(typeof W!="function")throw new o("reducer",["Function","AsyncFunction"],W);J!=null&&u(J,"options"),J?.signal!=null&&l(J.signal,"options.signal");let oe=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new a(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let R=new t,F=R.signal;if(J!=null&&J.signal){let fe={once:!0,[d]:this,[f]:!0};J.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var he;if(ee=!0,J!=null&&(he=J.signal)!==null&&he!==void 0&&he.aborted)throw new a;oe?G=await W(G,fe,{signal:F}):(G=fe,oe=!0)}if(!ee&&!oe)throw new Q}finally{R.abort()}return G}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal");let G=[];for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new a(void 0,{cause:W.signal.reason});k(G,ge)}return G}function we(W,G){let J=ae.call(this,W,G);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function K(W){if(W=E(W),S(W))return 0;if(W<0)throw new i("number",">= 0",W);return W}function N(W,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),W=K(W),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;W--<=0&&(yield oe)}}).call(this)}function ne(W,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),W=K(W),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;if(W-- >0&&(yield oe),W<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:N,filter:M,flatMap:we,map:ae,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:V,find:$}}),ys=pe((s,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:o,isNodeStream:n,isWebStream:i}=ht(),{pipelineImpl:a}=wi(),{finished:l}=kt();vs();function c(...u){return new r((d,f)=>{let g,h,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!i(b)){let y=t(u);g=y.signal,h=y.end}a(u,(y,w)=>{y?f(y):d(w)},{signal:g,end:h})})}e.exports={finished:l,pipeline:c}}),vs=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Be(),{promisify:{custom:i}}=Je(),{streamReturningOperators:a,promiseReturningOperators:l}=Gc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=bs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:f}=kr(),{pipeline:g}=wi(),{destroyer:h}=Ft(),b=kt(),y=ys(),w=ht(),m=e.exports=yi().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=_r();for(let x of o(a)){let v=function(...S){if(new.target)throw c();return m.Readable.from(n(E,this,S))},E=a[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of o(l)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=l[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=vi(),m.Duplex=ft(),m.Transform=ms(),m.PassThrough=gs(),m.pipeline=g;var{addAbortSignal:k}=wr();m.addAbortSignal=k,m.finished=b,m.destroy=h,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=f,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.finished}}),m.Stream=m,m._isUint8Array=function(x){return x instanceof Uint8Array},m._uint8ArrayToBuffer=function(x){return t.from(x.buffer,x.byteOffset,x.byteLength)}}),Ot=pe((s,e)=>{le(),ue(),ce();var t=vs(),r=ys(),o=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=o,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),Yc=pe((s,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var o=function(){};o.prototype=r.prototype,t.prototype=new o,t.prototype.constructor=t}}}),Jc=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),r=Symbol.for("BufferList");function o(n){if(!(this instanceof o))return new o(n);o._init.call(this,n)}o._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},o.prototype._new=function(n){return new o(n)},o.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let a=0;a<this._bufs.length;a++){let l=i+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-i];i=l}},o.prototype._reverseOffset=function(n){let i=n[0],a=n[1];for(let l=0;l<i;l++)a+=this._bufs[l].length;return a},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},o.prototype.slice=function(n,i){return typeof n=="number"&&n<0&&(n+=this.length),typeof i=="number"&&i<0&&(i+=this.length),this.copy(null,0,n,i)},o.prototype.copy=function(n,i,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,f=d,g=c&&i||0,h=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(f<=this._bufs[u[0]].length-h)return c?this._bufs[u[0]].copy(n,i,h,h+f):this._bufs[u[0]].slice(h,h+f);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-h;if(f>y)this._bufs[b].copy(n,g,h),g+=y;else{this._bufs[b].copy(n,g,h,h+f),g+=y;break}f-=y,h&&(h=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,i){if(n=n||0,i=typeof i!="number"?this.length:i,n<0&&(n+=this.length),i<0&&(i+=this.length),n===i)return this._new();let a=this._offset(n),l=this._offset(i),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},o.prototype.toString=function(n,i,a){return this.slice(i,a).toString(n)},o.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},o.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},o.prototype.append=function(n){return this._attach(n,o.prototype._appendBuffer)},o.prototype.prepend=function(n){return this._attach(n,o.prototype._prependBuffer,!0)},o.prototype._attach=function(n,i,a){if(n==null)return this;if(n.buffer)i.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],i,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],i,a)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},o.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},o.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},o.prototype.indexOf=function(n,i,a){if(a===void 0&&typeof i=="string"&&(a=i,i=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),i=Number(i||0),isNaN(i)&&(i=0),i<0&&(i=this.length+i),i<0&&(i=0),n.length===0)return i>this.length?this.length:i;let l=this._offset(i),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let f=d.indexOf(n,u);if(f!==-1)return this._reverseOffset([c,f]);u=d.length-n.length+1}else{let f=this._reverseOffset([c,u]);if(this._match(f,n))return f;u++}u=0}return-1},o.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let a=0;a<i.length;a++)if(this.get(n+a)!==i[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let i in n)(function(a){n[a]===null?o.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:o.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(i)})(),o.prototype._isBufferList=function(n){return n instanceof o||o.isBufferList(n)},o.isBufferList=function(n){return n!=null&&n[r]},e.exports=o}),Qc=pe((s,e)=>{le(),ue(),ce();var t=Ot().Duplex,r=Yc(),o=Jc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),i=null}o._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,o.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,a,l){this._appendBuffer(i),typeof l=="function"&&l()},n.prototype._read=function(i){if(!this.length)return this.push(null);i=Math.min(i,this.length),this.push(this.slice(0,i)),this.consume(i)},n.prototype.end=function(i){t.prototype.end.call(this,i),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(i,a){this._bufs.length=0,this.length=0,a(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof o||n.isBufferList(i)},n.isBufferList=o.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=o}),Xc=pe((s,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),ws=pe((s,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Fe(),Re($e));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let i=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+i.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let i=t.types[n];t.codes[i]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let i=t.properties[n];t.propertiesCodes[i]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function o(n){return[0,1,2].map(i=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|i<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=o("publish"),t.SUBSCRIBE_HEADER=o("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=o("unsubscribe"),t.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),Zc=pe((s,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,i=n*7,a=n*365.25;e.exports=function(f,g){g=g||{};var h=typeof f;if(h==="string"&&f.length>0)return l(f);if(h==="number"&&isFinite(f))return g.long?u(f):c(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function l(f){if(f=String(f),!(f.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(g){var h=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return h*a;case"weeks":case"week":case"w":return h*i;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*o;case"minutes":case"minute":case"mins":case"min":case"m":return h*r;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function c(f){var g=Math.abs(f);return g>=n?Math.round(f/n)+"d":g>=o?Math.round(f/o)+"h":g>=r?Math.round(f/r)+"m":g>=t?Math.round(f/t)+"s":f+"ms"}function u(f){var g=Math.abs(f);return g>=n?d(f,g,n,"day"):g>=o?d(f,g,o,"hour"):g>=r?d(f,g,r,"minute"):g>=t?d(f,g,t,"second"):f+" ms"}function d(f,g,h,b){var y=g>=h*1.5;return Math.round(f/h)+" "+b+(y?"s":"")}}),eu=pe((s,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=Zc(),n.destroy=f,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let h=0;for(let b=0;b<g.length;b++)h=(h<<5)-h+g.charCodeAt(b),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=o;function n(g){let h,b=null,y,w;function m(...k){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(h||v);x.diff=E,x.prev=h,x.curr=v,h=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let S=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";S++;let O=n.formatters[P];if(typeof O=="function"){let j=k[S];I=O.call(x,j),k.splice(S,1),S--}return I}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:k=>{b=k}}),typeof n.init=="function"&&n.init(m),m}function i(g,h){let b=n(this.namespace+(typeof h>"u"?":":h)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let h=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of h)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,h){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<h.length&&(h[y]===g[b]||h[y]==="*"))h[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function c(){let g=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),g}function u(g){for(let h of n.skips)if(l(g,h))return!1;for(let h of n.names)if(l(g,h))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),pt=pe((s,e)=>{le(),ue(),ce(),s.formatArgs=r,s.save=o,s.load=n,s.useColors=t,s.storage=i(),s.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),s.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(u++,f==="%c"&&(d=u))}),l.splice(d,0,c)}s.log=console.debug||console.log||(()=>{});function o(l){try{l?s.storage.setItem("debug",l):s.storage.removeItem("debug")}catch{}}function n(){let l;try{l=s.storage.getItem("debug")||s.storage.getItem("DEBUG")}catch{}return!l&&typeof Ne<"u"&&"env"in Ne&&(l=Ne.env.DEBUG),l}function i(){try{return localStorage}catch{}}e.exports=eu()(s);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),tu=pe((s,e)=>{le(),ue(),ce();var t=Qc(),{EventEmitter:r}=(Ct(),Re(wt)),o=Xc(),n=ws(),i=pt()("mqtt-packet:parser"),a=class No extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof No?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new No().parser(c)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),i("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=c&15,f=n.requiredHeaderFlags[u];return f!=null&&d!==f?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),i("_parseLength %d",c.value),!!c}_parsePayload(){i("_parsePayload: payload %O",this._list);let c=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}c=!0}return i("_parsePayload complete result: %s",c),c}_parseConnect(){i("_parseConnect");let c,u,d,f,g={},h=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(h.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(h.protocolVersion=this._list.readUInt8(this._pos),h.protocolVersion>=128&&(h.bridgeMode=!0,h.protocolVersion=h.protocolVersion-128),h.protocolVersion!==3&&h.protocolVersion!==4&&h.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)h.will={},h.will.retain=y,h.will.qos=w;else{if(y)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(h.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,h.keepalive=this._parseNum(),h.keepalive===-1)return this._emitError(new Error("Packet too short"));if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(h.clientId=m,i("_parseConnect: packet.clientId: %s",h.clientId),g.will){if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(h.will.topic=c,i("_parseConnect: packet.will.topic: %s",h.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));h.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",h.will.payload)}if(g.username){if(f=this._parseString(),f===null)return this._emitError(new Error("Cannot parse username"));h.username=f,i("_parseConnect: packet.username: %s",h.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));h.password=d}return this.settings=h,i("_parseConnect: complete"),h}_parseConnack(){i("_parseConnack");let c=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),i("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){i("_parseSubscribe");let c=this.packet,u,d,f,g,h,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(f=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,f>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(b=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,h=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:f},this.settings.protocolVersion===5?(y.nl=b,y.rap=h,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){i("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){i("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let f=this._list.toString("utf8",this._pos,d);return this._pos+=u,i("_parseString: result: %s",f),f}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=c,i("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){i("_parseVarByteNum");let u=4,d=0,f=1,g=0,h=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=f*(b&n.VARBYTEINT_MASK),f*=128,(b&n.VARBYTEINT_FIN_MASK)===0){h=!0;break}if(this._list.length<=d)break}return!h&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),h?c?h={bytes:d,value:g}:h=g:h=!1,i("_parseVarByteNum: result: %o",h),h}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",c),c}_parseByType(c){switch(i("_parseByType: type: %s",c),c){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let f=this._parseByte();if(!f)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[f];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let h=this._parseByType(n.propertiesTypes[g]);if(d[g][h.name])if(Array.isArray(d[g][h.name]))d[g][h.name].push(h.value);else{let b=d[g][h.name];d[g][h.name]=[b],d[g][h.name].push(h.value)}else d[g][h.name]=h.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(c){i("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),ru=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),r=65536,o={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)o[u]=i(u)}function l(u){let d=0,f=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,f++);while(u>0&&f<4);return u>0&&(f=0),n?g.subarray(0,f):g.slice(0,f)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:o,generateCache:a,generateNumber:i,genBufVariableByteInt:l,generate4ByteBuffer:c}}),nu=pe((s,e)=>{le(),ue(),ce(),typeof Ne>"u"||!Ne.version||Ne.version.indexOf("v0.")===0||Ne.version.indexOf("v1.")===0&&Ne.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Ne;function t(r,o,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return Ne.nextTick(r);case 2:return Ne.nextTick(function(){r.call(null,o)});case 3:return Ne.nextTick(function(){r.call(null,o,n)});case 4:return Ne.nextTick(function(){r.call(null,o,n,i)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return Ne.nextTick(function(){r.apply(null,l)})}}}),ks=pe((s,e)=>{le(),ue(),ce();var t=ws(),{Buffer:r}=(Fe(),Re($e)),o=r.allocUnsafe(0),n=r.from([0]),i=ru(),a=nu().nextTick,l=pt()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,d=i.generateCache,f=i.genBufVariableByteInt,g=i.generate4ByteBuffer,h=Y,b=!0;function y(K,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),b&&(b=!1,d()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,N);case"connack":return k(K,N,ne);case"publish":return x(K,N,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(K,N,ne);case"subscribe":return E(K,N,ne);case"suback":return S(K,N,ne);case"unsubscribe":return I(K,N,ne);case"unsuback":return P(K,N,ne);case"pingreq":case"pingresp":return O(K,N);case"disconnect":return j(K,N,ne);case"auth":return T(K,N,ne);default:return N.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return h===Y},set(K){K?((!c||Object.keys(c).length===0)&&(b=!0),h=Y):(b=!1,h=V)}});function w(K){K.uncork()}function m(K,N,ne){let W=K||{},G=W.protocolId||"MQTT",J=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,F=W.clientId||"",ee=W.username,he=W.password,fe=W.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof G!="string"&&!r.isBuffer(G))return N.destroy(new Error("Invalid protocolId")),!1;if(ye+=G.length+2,J!==3&&J!==4&&J!==5)return N.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof F=="string"||r.isBuffer(F))&&(F||J>=4)&&(F||oe))ye+=r.byteLength(F)+2;else{if(J<4)return N.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return N.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return N.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(J===5){if(H=Z(N,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return N.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return N.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return N.destroy(new Error("Invalid will payload")),!1;if(me={},J===5){if(me=Z(N,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return N.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return N.destroy(new Error("Username is required to use password")),!1;if(we(he))ye+=te(he)+2;else return N.destroy(new Error("Invalid password")),!1}N.write(t.CONNECT_HEADER),D(N,ye),$(N,G),W.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=he!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,N.write(r.from([se])),h(N,R),J===5&&H.write(),$(N,F),ge&&(J===5&&me.write(),U(N,ge.topic),$(N,ge.payload)),ee!=null&&$(N,ee),he!=null&&$(N,he),!0}function k(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=W===5?G.reasonCode:G.returnCode,ge=G.properties,oe=2;if(typeof J!="number")return N.destroy(new Error("Invalid return code")),!1;let R=null;if(W===5){if(R=Z(N,ge),!R)return!1;oe+=R.length}return N.write(t.CONNACK_HEADER),D(N,oe),N.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),N.write(r.from([J])),R?.write(),!0}function x(K,N,ne){l("publish: packet: %o",K);let W=ne?ne.protocolVersion:4,G=K||{},J=G.qos||0,ge=G.retain?t.RETAIN_MASK:0,oe=G.topic,R=G.payload||o,F=G.messageId,ee=G.properties,he=0;if(typeof oe=="string")he+=r.byteLength(oe)+2;else if(r.isBuffer(oe))he+=oe.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof F!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(W===5){if(fe=Z(N,ee),!fe)return!1;he+=fe.length}return N.write(t.PUBLISH_HEADER[J][G.dup?1:0][ge?1:0]),D(N,he),h(N,te(oe)),N.write(oe),J>0&&h(N,F),fe?.write(),l("publish: payload: %o",R),N.write(R)}function v(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.cmd||"puback",ge=G.messageId,oe=G.dup&&J==="pubrel"?t.DUP_MASK:0,R=0,F=G.reasonCode,ee=G.properties,he=W===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][R][oe][0]),he===3&&(he+=F!==0?1:-1),D(N,he),h(N,ge),W===5&&he!==2&&N.write(r.from([F])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function E(K,N,ne){l("subscribe: packet: ");let W=ne?ne.protocolVersion:4,G=K||{},J=G.dup?t.DUP_MASK:0,ge=G.messageId,oe=G.subscriptions,R=G.properties,F=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;F+=2;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;F+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let ye=oe[fe].topic,H=oe[fe].qos;if(typeof ye!="string")return N.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return N.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(W===5){if(typeof(oe[fe].nl||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[fe].rap||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=oe[fe].rh||0;if(typeof me!="number"||me>2)return N.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}F+=r.byteLength(ye)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(N,F),h(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Ce;U(N,ye),Ce=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Ce|=me?t.SUBSCRIBE_OPTIONS_NL:0,Ce|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Ce|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),he=N.write(r.from([Ce]))}return he}function S(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.granted,oe=G.properties,R=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return N.destroy(new Error("Invalid qos vector")),!1;R+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let F=null;if(W===5){if(F=M(N,oe,ne,R),!F)return!1;R+=F.length}return N.write(t.SUBACK_HEADER),D(N,R),h(N,J),F!==null&&F.write(),N.write(r.from(ge))}function I(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,oe=G.unsubscriptions,R=G.properties,F=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(F+=2,typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){if(typeof oe[fe]!="string")return N.destroy(new Error("Invalid unsubscriptions")),!1;F+=r.byteLength(oe[fe])+2}else return N.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;F+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,F),h(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<oe.length;fe++)he=U(N,oe[fe]);return he}function P(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,oe=G.granted,R=G.properties,F=G.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return N.destroy(new Error("Invalid qos vector")),!1;he+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(N,R,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[F][ee][ge][0]),D(N,he),h(N,J),fe!==null&&fe.write(),W===5&&N.write(r.from(oe)),!0}function O(K,N,ne){return N.write(t.EMPTY[K.cmd])}function j(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,oe=W===5?1:0,R=null;if(W===5){if(R=M(N,ge,ne,oe),!R)return!1;oe+=R.length}return N.write(r.from([t.codes.disconnect<<4])),D(N,oe),W===5&&N.write(r.from([J])),R!==null&&R.write(),!0}function T(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,oe=W===5?1:0;W!==5&&N.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(N,ge,ne,oe);return R?(oe+=R.length,N.write(r.from([t.codes.auth<<4])),D(N,oe),N.write(r.from([J])),R!==null&&R.write(),!0):!1}var q={};function D(K,N){if(N>t.VARBYTEINT_MAX)return K.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=q[N];return ne||(ne=f(N),N<16384&&(q[N]=ne)),l("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function U(K,N){let ne=r.byteLength(N);return h(K,ne),l("writeString: %s",N),K.write(N,"utf8")}function ae(K,N,ne){U(K,N),U(K,ne)}function Y(K,N){return l("writeNumberCached: number: %d",N),l("writeNumberCached: %o",c[N]),K.write(c[N])}function V(K,N){let ne=u(N);return l("writeNumberGenerated: %o",ne),K.write(ne)}function re(K,N){let ne=g(N);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,N){typeof N=="string"?U(K,N):N?(h(K,N.length),K.write(N)):h(K,0)}function Z(K,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){be(K,{},0)}};let ne=0;function W(G,J){let ge=t.propertiesTypes[G],oe=0;switch(ge){case"byte":{if(typeof J!="boolean")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=2;break}case"binary":{if(J&&J===null)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=1+r.byteLength(J)+2;break}case"int16":{if(typeof J!="number"||J<0||J>65535)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=1+r.byteLength(f(J));break}case"string":{if(typeof J!="string")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=Object.getOwnPropertyNames(J).reduce((R,F)=>{let ee=J[F];return Array.isArray(ee)?R+=ee.reduce((he,fe)=>(he+=3+r.byteLength(F.toString())+2+r.byteLength(fe.toString()),he),0):R+=3+r.byteLength(F.toString())+2+r.byteLength(J[F].toString()),R},0);break}default:return K.destroy(new Error(`Invalid property ${G}: ${J}`)),!1}return oe}if(N)for(let G in N){let J=0,ge=0,oe=N[G];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(G,oe[R]),!ge)return!1;J+=ge}else{if(ge=W(G,oe),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(f(ne))+ne,write(){be(K,N,ne)}}}function M(K,N,ne,W){let G=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(K,N);if(J)for(;W+ge.length>J;){let oe=G.shift();if(oe&&N[oe])delete N[oe],ge=Z(K,N);else return!1}return ge}function Q(K,N,ne){switch(t.propertiesTypes[N]){case"byte":{K.write(r.from([t.properties[N]])),K.write(r.from([+ne]));break}case"int8":{K.write(r.from([t.properties[N]])),K.write(r.from([ne]));break}case"binary":{K.write(r.from([t.properties[N]])),$(K,ne);break}case"int16":{K.write(r.from([t.properties[N]])),h(K,ne);break}case"int32":{K.write(r.from([t.properties[N]])),re(K,ne);break}case"var":{K.write(r.from([t.properties[N]])),D(K,ne);break}case"string":{K.write(r.from([t.properties[N]])),U(K,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let G=ne[W];Array.isArray(G)?G.forEach(J=>{K.write(r.from([t.properties[N]])),ae(K,W.toString(),J.toString())}):(K.write(r.from([t.properties[N]])),ae(K,W.toString(),G.toString()))});break}default:return K.destroy(new Error(`Invalid property ${N} value: ${ne}`)),!1}}function be(K,N,ne){D(K,ne);for(let W in N)if(Object.prototype.hasOwnProperty.call(N,W)&&N[W]!=null){let G=N[W];if(Array.isArray(G))for(let J=0;J<G.length;J++)Q(K,W,G[J]);else Q(K,W,G)}}function te(K){return K?K instanceof r?K.length:r.byteLength(K):0}function we(K){return typeof K=="string"||K instanceof r}e.exports=y}),iu=pe((s,e)=>{le(),ue(),ce();var t=ks(),{EventEmitter:r}=(Ct(),Re(wt)),{Buffer:o}=(Fe(),Re($e));function n(a,l){let c=new i;return t(a,c,l),c.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=o.byteLength(c[d]),a+=l[d];let f=o.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(f,u),u+=l[d]):(f.write(c[d],u),u+=l[d]);return f}destroy(a){a&&this.emit("error",a)}};e.exports=n}),ou=pe(s=>{le(),ue(),ce(),s.parser=tu().parser,s.generate=iu(),s.writeToStream=ks()}),su=pe((s,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof vr?vr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return o(n);let i=new Map;if(i.set(Date,d=>new Date(d)),i.set(Map,(d,f)=>new Map(l(Array.from(d),f))),i.set(Set,(d,f)=>new Set(l(Array.from(d),f))),n.constructorHandlers)for(let d of n.constructorHandlers)i.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,f){let g=Object.keys(d),h=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?h[y]=w:w.constructor!==Object&&(a=i.get(w.constructor))?h[y]=a(w,f):ArrayBuffer.isView(w)?h[y]=t(w):h[y]=f(w)}return h}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=i.get(d.constructor)))return a(d,c);let f={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=i.get(h.constructor))?f[g]=a(h,c):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=c(h)}return f}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=i.get(d.constructor)))return a(d,u);let f={};for(let g in d){let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=i.get(h.constructor))?f[g]=a(h,u):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=u(h)}return f}}function o(n){let i=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,h)=>new Map(u(Array.from(g),h))),l.set(Set,(g,h)=>new Set(u(Array.from(g),h))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?f:d;function u(g,h){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],k=g[m];if(typeof k!="object"||k===null)y[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))y[m]=c(k,h);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let x=i.indexOf(k);x!==-1?y[m]=a[x]:y[m]=h(k)}}return y}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let h={};i.push(g),a.push(h);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,d);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=i.indexOf(y);w!==-1?h[b]=a[w]:h[b]=d(y)}}return i.pop(),a.pop(),h}function f(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,f);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,f);let h={};i.push(g),a.push(h);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,f);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=i.indexOf(y);w!==-1?h[b]=a[w]:h[b]=f(y)}}return i.pop(),a.pop(),h}}}),au=pe((s,e)=>{le(),ue(),ce(),e.exports=su()()}),_s=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.validateTopic=e,s.validateTopics=t;function e(r){let o=r.split("/");for(let n=0;n<o.length;n++)if(o[n]!=="+"){if(o[n]==="#")return n===o.length-1;if(o[n].indexOf("+")!==-1||o[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let o=0;o<r.length;o++)if(!e(r[o]))return r[o];return null}}),xs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Ot(),t={objectMode:!0},r={clean:!0},o=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,i){return this._inflights.set(n.messageId,n),i&&i(),this}createStream(){let n=new e.Readable(t),i=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{i.push(c)}),n._read=()=>{!a&&l<i.length?n.push(i[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),i(null,a)):i&&i(new Error("missing packet")),this}get(n,i){let a=this._inflights.get(n.messageId);return a?i(null,a):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};s.default=o}),lu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,o,n)=>{r.log("handlePublish: packet %o",o),n=typeof n<"u"?n:r.noop;let i=o.topic.toString(),a=o.payload,{qos:l}=o,{messageId:c}=o,{options:u}=r;if(r.options.protocolVersion===5){let d;if(o.properties&&(d=o.properties.topicAlias),typeof d<"u")if(i.length===0)if(d>0&&d<=65535){let f=r.topicAliasRecv.getTopicByAlias(d);if(f)i=f,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,d))r.log("handlePublish :: registered topic: %s - alias: %d",i,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(i,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));f?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:f},n):r.incomingStore.put(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for puback"));f||r.emit("message",i,a,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:f},n)})});break}case 0:r.emit("message",i,a,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};s.default=t}),cu=pe((s,e)=>{e.exports={version:"5.15.0"}}),qt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.MQTTJS_VERSION=s.nextTick=s.ErrorWithSubackPacket=s.ErrorWithReasonCode=void 0,s.applyMixin=r;var e=class pc extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,pc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};s.ErrorWithReasonCode=e;var t=class mc extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,mc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};s.ErrorWithSubackPacket=t;function r(o,n,i=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(i||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}s.nextTick=typeof Ne?.nextTick=="function"?Ne.nextTick:o=>{setTimeout(o,0)},s.MQTTJS_VERSION=cu().version}),xr=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=void 0;var e=qt();s.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,o)=>{let{messageId:n}=o,i=o.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",i),i){case"pubcomp":case"puback":{let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=o.granted;for(let d=0;d<u.length;d++){let f=u[d];if((f&128)!==0){c=new Error(`Subscribe error: ${s.ReasonCodes[f]}`),c.code=f;let g=r.messageIdToTopic[n];g&&g.forEach(h=>{delete r._resubscribeTopics[h]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,o);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};s.default=t}),uu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=qt(),t=xr(),r=(o,n)=>{let{options:i}=o,a=i.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(l===24)o.reconnecting=!1,o._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",d)}})};s.default=r}),du=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Ne=="object"&&Ne?Ne:{},o=(g,h,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,h,b,y):console.error(`[${b}] ${h}: ${g}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){h()}signal=new i;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",h=()=>{g&&(g=!1,o("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",h))}}var a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class pr{heap;length;static#l=!1;static create(h){let b=c(h);if(!b)return[];pr.#l=!0;let y=new pr(h,b);return pr.#l=!1,y}constructor(h,b){if(!pr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(h),this.length=0}push(h){this.heap[this.length++]=h}pop(){return this.heap[--this.length]}},f=class gc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#f;#k;#A;#u;static unsafeExposeInternals(h){return{starts:h.#w,ttls:h.#f,sizes:h.#v,keyMap:h.#n,keyList:h.#r,valList:h.#e,next:h.#c,prev:h.#h,get head(){return h.#a},get tail(){return h.#o},free:h.#y,isBackgroundFetch:b=>h.#t(b),backgroundFetch:(b,y,w,m)=>h.#L(b,y,w,m),moveToTail:b=>h.#C(b),indexes:b=>h.#_(b),rindexes:b=>h.#x(b),isStale:b=>h.#p(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(h){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=h;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let $=b?c(b):Array;if(!$)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=O,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!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(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=D,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new $(b),this.#h=new $(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#d){let Z="LRU_CACHE_UNBOUNDED";a(Z)&&(t.add(Z),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,gc))}}getRemainingTTL(h){return this.#n.has(h)?1/0:0}#N(){let h=new u(this.#l),b=new u(this.#l);this.#f=h,this.#w=b,this.#j=(m,k,x=e.now())=>{if(b[m]=k!==0?x:0,h[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=h[m]!==0?e.now():0},this.#E=(m,k)=>{if(h[k]){let x=h[k],v=b[k];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let E=m.now-v;m.remainingTTL=x-E}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let k=setTimeout(()=>y=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=h[k],v=b[k];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let k=b[m],x=h[m];return!!x&&!!k&&(y||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#F(){let h=new u(this.#l);this.#b=0,this.#v=h,this.#T=b=>{this.#b-=h[b],h[b]=0},this.#U=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!l(w))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 w},this.#M=(b,y,w)=>{if(h[b]=y,this.#d){let m=this.#d-h[b];for(;this.#b>m;)this.#R(!0)}this.#b+=h[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=h=>{};#M=(h,b,y)=>{};#U=(h,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#B(b)||((h||!this.#p(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#B(b)||((h||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#B(h){return h!==void 0&&this.#n.get(this.#r[h])===h}*entries(){for(let h of this.#_())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*rentries(){for(let h of this.#x())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*keys(){for(let h of this.#_()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*rkeys(){for(let h of this.#x()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*values(){for(let h of this.#_())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}*rvalues(){for(let h of this.#x())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(h,b={}){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&h(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(h,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}rforEach(h,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}purgeStale(){let h=!1;for(let b of this.#x({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),h=!0);return h}info(h){let b=this.#n.get(h);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[b],x=this.#w[b];if(k&&x){let v=k-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let h=[];for(let b of this.#_({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let k={value:m};if(this.#f&&this.#w){k.ttl=this.#f[b];let x=e.now()-this.#w[b];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[b]),h.unshift([y,k])}return h}load(h){this.clear();for(let[b,y]of h){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(h,b,y={}){if(b===void 0)return this.delete(h),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#U(h,b,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(h,"set"),this;let I=this.#i===0?void 0:this.#n.get(h);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=h,this.#e[I]=b,this.#n.set(h,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let P=this.#e[I];if(b!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!k&&(this.#k&&this.#m?.(O,h,"set"),this.#u&&this.#s?.push([O,h,"set"]))}else k||(this.#k&&this.#m?.(P,h,"set"),this.#u&&this.#s?.push([P,h,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=b,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(E||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.shift();)this.#g?.(...O)}return this}pop(){try{for(;this.#i;){let h=this.#e[this.#a];if(this.#R(!0),this.#t(h)){if(h.__staleWhileFetching)return h.__staleWhileFetching}else if(h!==void 0)return h}}finally{if(this.#u&&this.#s){let h=this.#s,b;for(;b=h?.shift();)this.#g?.(...b)}}}#R(h){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),h&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(h,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(h);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(h,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(h);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(h,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:x}=y;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},E=(T,q=!1)=>{let{aborted:D}=k.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!q?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!q)return I(k.signal.reason);let ae=O;return this.#e[b]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[b]=ae.__staleWhileFetching:this.#S(h,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(h,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=k.signal,D=q&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,ae=U||y.noDeleteOnFetchRejection,Y=O;if(this.#e[b]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#S(h,"fetch"):D||(this.#e[b]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},P=(T,q)=>{let D=this.#P?.(h,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),k.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let O=new Promise(P).then(E,S),j=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(h,j,{...v.options,status:void 0}),b=this.#n.get(h)):this.#e[b]=j,j}#t(h){if(!this.#A)return!1;let b=h;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=b;if(!this.#A)return D&&(D.fetch="get"),this.get(h,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let ae={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:D,signal:U},Y=this.#n.get(h);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(h,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=y&&V.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?V.__staleWhileFetching:V.__returned=V}let re=this.#p(Y);if(!q&&!re)return D&&(D.fetch="hit"),this.#C(Y),w&&this.#I(Y),D&&this.#E(D,Y),V;let $=this.#L(h,Y,ae,T),Z=$.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?$.__staleWhileFetching:$.__returned=$}}async forceFetch(h,b={}){let y=await this.fetch(h,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(h,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,x=this.get(h,k);if(!m&&x!==void 0)return x;let v=y(h,x,{options:k,context:w});return this.set(h,v,k),v}get(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,x=this.#n.get(h);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return k&&this.#E(k,x),this.#p(x)?(k&&(k.get="stale"),E?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(h,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#D(h,b){this.#h[b]=h,this.#c[h]=b}#C(h){h!==this.#o&&(h===this.#a?this.#a=this.#c[h]:this.#D(this.#h[h],this.#c[h]),this.#D(this.#o,h),this.#o=h)}delete(h){return this.#S(h,"delete")}#S(h,b){let y=!1;if(this.#i!==0){let w=this.#n.get(h);if(w!==void 0)if(y=!0,this.#i===1)this.#$(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,h,b),this.#u&&this.#s?.push([m,h,b])),this.#n.delete(h),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#$("delete")}#$(h){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#k&&this.#m?.(y,w,h),this.#u&&this.#s?.push([y,w,h])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#w&&(this.#f.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};s.LRUCache=f}),mt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.ContainerIterator=s.Container=s.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.o}};s.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};s.Base=t;var r=class extends t{};s.Container=r}),hu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(o){return this.S.push(o),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;s.default=r}),fu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(o){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let a=0;a<i;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=o}else this.q[this.j+this.i]=o;return++this.i}pop(){if(this.i===0)return;let o=this.q[this.j++];return this.i-=1,o}front(){if(this.i!==0)return this.q[this.j]}},r=t;s.default=r}),pu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[],n=function(a,l){return a>l?-1:a<l?1:0},i=!0){if(super(),this.v=n,Array.isArray(o))this.C=i?[...o]:o;else{this.C=[];let l=this;o.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(o){let n=this.C[o];for(;o>0;){let i=o-1>>1,a=this.C[i];if(this.v(a,n)<=0)break;this.C[o]=a,o=i}this.C[o]=n}k(o,n){let i=this.C[o];for(;o<n;){let a=o<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,i)>=0)break;this.C[o]=c,o=a}this.C[o]=i}clear(){this.i=0,this.C.length=0}push(o){this.C.push(o),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let o=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),o}top(){return this.C[0]}find(o){return this.C.indexOf(o)>=0}remove(o){let n=this.C.indexOf(o);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(o){let n=this.C.indexOf(o);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;s.default=r}),ki=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Container{},r=t;s.default=r}),gt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ss=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.RandomIterator=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(o,n){super(n),this.o=o,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(o){this.container.setElementByPos(this.o,o)}};s.RandomIterator=r}),mu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(ki()),t=Ss();function r(a){return a&&a.t?a:{default:a}}var o=class bc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new bc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new o(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;s.default=i}),gu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(ki()),t=mt(),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class yc extends t.ContainerIterator{constructor(c,u,d,f){super(f),this.o=c,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new yc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let f=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=f,f.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=i;s.default=a}),bu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(ki()),t=Ss();function r(a){return a&&a.t?a:{default:a}}var o=class vc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new vc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let f=0;f<this.P;++f)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(f){d.pushBack(f)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new o(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},i=n;s.default=i}),yu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.TreeNodeEnableIndex=s.TreeNode=void 0;var e=class{constructor(r,o){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=o}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let o=r.tt;for(;o.U===r;)r=o,o=r.tt;r=o}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let o=r.tt;for(;o.W===r;)r=o,o=r.tt;return r.W!==o?o:r}}te(){let r=this.tt,o=this.W,n=o.U;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.U=this,this.tt=o,this.W=n,n&&(n.tt=this),o}se(){let r=this.tt,o=this.U,n=o.W;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.W=this,this.tt=o,this.U=n,n&&(n.tt=this),o}};s.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};s.TreeNodeEnableIndex=t}),Es=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=yu(),t=mt(),r=gt(),o=class extends t.Container{constructor(i=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=i,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let f=d.tt;for(;f!==this.h;)f.rt+=1,f=f.tt;let g=this.he(d);if(g){let{parentNode:h,grandParent:b,curNode:y}=g;h.ie(),b.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(i,a){let l=this.h;for(;i;){let c=this.v(i.u,a);if(c<0)i=i.W;else if(c>0)l=i,i=i.U;else return i}return l}Z(i,a){let l=this.h;for(;i;)this.v(i.u,a)<=0?i=i.W:(l=i,i=i.U);return l}$(i,a){let l=this.h;for(;i;){let c=this.v(i.u,a);if(c<0)l=i,i=i.W;else if(c>0)i=i.U;else return i}return l}rr(i,a){let l=this.h;for(;i;)this.v(i.u,a)<0?(l=i,i=i.W):i=i.U;return l}ue(i){for(;;){let a=i.tt;if(a===this.h)return;if(i.ee===1){i.ee=0;return}if(i===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,i=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,i=a)}}}fe(i){if(this.i===1)return this.clear(),this.h;let a=i;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[i.u,a.u]=[a.u,i.u],[i.l,a.l]=[a.l,i.l],i=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(i,a){return i===void 0?!1:this.oe(i.U,a)||a(i)?!0:this.oe(i.W,a)}he(i){for(;;){let a=i.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,i=l;continue}else if(i===a.W){if(i.ee=0,i.U&&(i.U.tt=a),i.W&&(i.W.tt=l),a.W=i.U,l.U=i.W,i.U=a,i.W=l,l===this.Y)this.Y=i,this.h.tt=i;else{let u=l.tt;u.U===l?u.U=i:u.W=i}return i.tt=l.tt,a.tt=i,l.tt=i,l.ee=1,{parentNode:a,grandParent:l,curNode:i}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,i=l;continue}else if(i===a.U){if(i.ee=0,i.U&&(i.U.tt=l),i.W&&(i.W.tt=a),l.W=i.U,a.U=i.W,i.U=l,i.W=a,l===this.Y)this.Y=i,this.h.tt=i;else{let u=l.tt;u.U===l?u.U=i:u.W=i}return i.tt=l.tt,a.tt=i,l.tt=i,l.ee=1,{parentNode:a,grandParent:l,curNode:i}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(i,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,i);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(i,a),u.U.tt=u,c=u.U,this.h.U=c;else{let f=this.h.W,g=this.v(f.u,i);if(g===0){f.l=a;return}else if(g<0)f.W=new this.re(i,a),f.W.tt=f,c=f.W,this.h.W=c;else{if(l!==void 0){let h=l.o;if(h!==this.h){let b=this.v(h.u,i);if(b===0){h.l=a;return}else if(b>0){let y=h.L(),w=this.v(y.u,i);if(w===0){y.l=a;return}else w<0&&(c=new this.re(i,a),y.W===void 0?(y.W=c,c.tt=y):(h.U=c,c.tt=h))}}}if(c===void 0)for(c=this.Y;;){let h=this.v(c.u,i);if(h>0){if(c.U===void 0){c.U=new this.re(i,a),c.U.tt=c,c=c.U;break}c=c.U}else if(h<0){if(c.W===void 0){c.W=new this.re(i,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(i,a){for(;i;){let l=this.v(i.u,a);if(l<0)i=i.W;else if(l>0)i=i.U;else return i}return i||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(i,a){let l=i.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return i===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let a=this.I(this.Y,i);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(i){let a=i.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return i.iteratorType===0?l&&i.next():(!l||a.U===void 0)&&i.next(),this.V(a),i}forEach(i){let a=0;for(let l of this)i(l,a++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===i){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let i=function(a){return a?Math.max(i(a.U),i(a.W))+1:0};return i(this.Y)}},n=o;s.default=n}),As=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(n,i,a){super(a),this.o=n,this.h=i,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,i=this.h.tt;if(n===this.h)return i?i.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==i;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},o=r;s.default=o}),vu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Es()),t=o(As()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class wc extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new wc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.insert(f)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=i;s.default=a}),wu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Es()),t=o(As()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class kc extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new kc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.setElement(f[0],f[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=i;s.default=a}),Is=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ts=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.HashContainerIterator=s.HashContainer=void 0;var e=mt(),t=o(Is()),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};s.HashContainerIterator=n;var i=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};s.HashContainer=i}),ku=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ts(),t=gt(),r=class _c extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new _c(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(i=[]){super();let a=this;i.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(i,a){return this.M(i,void 0,a)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a=this.p;for(;i--;)a=a.B;return a.u}find(i,a){let l=this.I(i,a);return new r(l,this.h,this)}forEach(i){let a=0,l=this.p;for(;l!==this.h;)i(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=o;s.default=n}),_u=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ts(),t=o(Is()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class xc extends e.HashContainerIterator{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new xc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=i;s.default=a}),xu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),Object.defineProperty(s,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(s,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(s,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(s,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(s,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(s,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(s,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(s,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(s,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(s,"Vector",{enumerable:!0,get:function(){return o.default}});var e=d(hu()),t=d(fu()),r=d(pu()),o=d(mu()),n=d(gu()),i=d(bu()),a=d(vu()),l=d(wu()),c=d(ku()),u=d(_u());function d(f){return f&&f.t?f:{default:f}}}),Su=pe((s,e)=>{le(),ue(),ce();var t=xu().OrderedSet,r=pt()("number-allocator:trace"),o=pt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function i(a,l){if(!(this instanceof i))return new i(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}i.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},i.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},i.prototype.free=function(a){if(a<this.min||a>this.max){o("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let f=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(f,d))):this.ss.updateKeyByIterator(c,new n(f,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=i}),Cs=pe((s,e)=>{le(),ue(),ce();var t=Su();e.exports.NumberAllocator=t}),Eu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=du(),t=Cs(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(o){o>0&&(this.aliasToTopic=new e.LRUCache({max:o}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,o),this.max=o,this.length=0)}put(o,n){if(n===0||n>this.max)return!1;let i=this.aliasToTopic.get(n);return i&&delete this.topicToAlias[i],this.aliasToTopic.set(n,o),this.topicToAlias[o]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(o){return this.aliasToTopic.get(o)}getAliasByTopic(o){let n=this.topicToAlias[o];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};s.default=r}),Au=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(s,"__esModule",{value:!0});var t=xr(),r=e(Eu()),o=qt(),n=(i,a)=>{i.log("_handleConnack");let{options:l}=i,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)i.reconnecting=!1,i._onConnect(a);else if(c>0){let u=new o.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};s.default=n}),Iu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(t,r,o)=>{t.log("handling pubrel packet");let n=typeof o<"u"?o:t.noop,{messageId:i}=r,a={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};s.default=e}),Tu=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(s,"__esModule",{value:!0});var t=e(lu()),r=e(uu()),o=e(Au()),n=e(xr()),i=e(Iu()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,i.default)(l,c,u);break;case"connack":(0,o.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};s.default=a}),Ps=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};s.default=e}),Cu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};s.default=e}),Pu=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(s,"__esModule",{value:!0}),s.TypedEventEmitter=void 0;var t=e((Ct(),Re(wt))),r=qt(),o=class{};s.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Sr=pe((s,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o){return typeof o}:function(o){return o&&typeof Symbol=="function"&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ou=pe((s,e)=>{le(),ue(),ce();var t=Sr().default;function r(o,n){if(t(o)!="object"||!o)return o;var i=o[Symbol.toPrimitive];if(i!==void 0){var a=i.call(o,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(o)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Mu=pe((s,e)=>{le(),ue(),ce();var t=Sr().default,r=Ou();function o(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ru=pe((s,e)=>{le(),ue(),ce();var t=Mu();function r(o,n,i){return(n=t(n))in o?Object.defineProperty(o,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):o[n]=i,o}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Lu=pe((s,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Nu=pe((s,e)=>{le(),ue(),ce();function t(r,o){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,a,l,c,u=[],d=!0,f=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(i=l.call(n)).done)&&(u.push(i.value),u.length!==o);d=!0);}catch(g){f=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(f)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ju=pe((s,e)=>{le(),ue(),ce();function t(r,o){(o==null||o>r.length)&&(o=r.length);for(var n=0,i=Array(o);n<o;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Uu=pe((s,e)=>{le(),ue(),ce();var t=ju();function r(o,n){if(o){if(typeof o=="string")return t(o,n);var i={}.toString.call(o).slice(8,-1);return i==="Object"&&o.constructor&&(i=o.constructor.name),i==="Map"||i==="Set"?Array.from(o):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(o,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((s,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((s,e)=>{le(),ue(),ce();var t=Lu(),r=Nu(),o=Uu(),n=Bu();function i(a,l){return t(a)||r(a,l)||o(a,l)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Os=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(s,function(t){var r=function(g){return function(h){var b=g(h);return h.add(b),b}},o=function(g){return function(h,b){return g.set(h,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,a=i*2,l=function(g,h){return function(b){var y=h.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<i){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),d=l(u,c),f=r(d);t.addUniqueNumber=f,t.generateUniqueNumber=d})}),$u=pe((s,e)=>{le(),ue(),ce();function t(o,n,i,a,l,c,u){try{var d=o[c](u),f=d.value}catch(g){return void i(g)}d.done?n(f):Promise.resolve(f).then(a,l)}function r(o){return function(){var n=this,i=arguments;return new Promise(function(a,l){var c=o.apply(n,i);function u(f){t(c,a,l,u,d,"next",f)}function d(f){t(c,a,l,u,d,"throw",f)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ms=pe((s,e)=>{le(),ue(),ce();function t(r,o){this.v=r,this.k=o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((s,e)=>{le(),ue(),ce();function t(r,o,n,i){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function f(g,h){t(l,g,function(b){return this._invoke(g,h,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(f("next",0),f("throw",1),f("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,o,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((s,e)=>{le(),ue(),ce();var t=Rs();function r(){var o,n,i=typeof Symbol=="function"?Symbol:{},a=i.iterator||"@@iterator",l=i.toStringTag||"@@toStringTag";function c(w,m,k,x){var v=m&&m.prototype instanceof d?m:d,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,P){var O,j,T,q=0,D=P||[],U=!1,ae={p:0,n:0,v:o,a:Y,f:Y.bind(o,4),d:function(V,re){return O=V,j=0,T=o,ae.n=re,u}};function Y(V,re){for(j=V,T=re,n=0;!U&&q&&!$&&n<D.length;n++){var $,Z=D[n],M=ae.p,Q=Z[2];V>3?($=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=o):Z[0]<=M&&(($=V<2&&M<Z[1])?(j=0,ae.v=re,ae.n=Z[1]):M<Q&&($=V<3||Z[0]>re||re>Q)&&(Z[4]=V,Z[5]=re,ae.n=Q,j=0))}if($||V>1)return u;throw U=!0,re}return function(V,re,$){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,$),j=re,T=$;(n=j<2?o:T)||!U;){O||(j?j<3?(j>1&&(ae.n=-1),Y(j,T)):ae.n=T:ae.v=T);try{if(q=2,O){if(j||(V="next"),n=O[V]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=O.return)&&n.call(O),j<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),j=1);O=o}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){O=o,j=1,T=Z}finally{q=1}}return{value:n,done:U}}})(w,k,x),!0),E}var u={};function d(){}function f(){}function g(){}n=Object.getPrototypeOf;var h=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(h);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return f.prototype=g,t(b,"constructor",g),t(g,"constructor",f),f.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ns=pe((s,e)=>{le(),ue(),ce();var t=Ms(),r=Rs();function o(n,i){function a(c,u,d,f){try{var g=n[c](u),h=g.value;return h instanceof t?i.resolve(h.v).then(function(b){a("next",b,d,f)},function(b){a("throw",b,d,f)}):i.resolve(h).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,f)})}catch(b){f(b)}}var l;this.next||(r(o.prototype),r(o.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function f(){return new i(function(g,h){a(c,d,g,h)})}return l=l?l.then(f,f):f()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),js=pe((s,e)=>{le(),ue(),ce();var t=Ls(),r=Ns();function o(n,i,a,l,c){return new r(t().w(n,i,a,l),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((s,e)=>{le(),ue(),ce();var t=js();function r(o,n,i,a,l){var c=t(o,n,i,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((s,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var i in o)n.unshift(i);return function a(){for(;n.length;)if((i=n.pop())in o)return a.value=i,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((s,e)=>{le(),ue(),ce();var t=Sr().default;function r(o){if(o!=null){var n=o[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(o);if(typeof o.next=="function")return o;if(!isNaN(o.length))return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}}}throw new TypeError(t(o)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((s,e)=>{le(),ue(),ce();var t=Ms(),r=Ls(),o=Fu(),n=js(),i=Ns(),a=qu(),l=Hu();function c(){var u=r(),d=u.m(c),f=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===f||(w.displayName||w.name)==="GeneratorFunction")}var h={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,h[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(k.d,l(x),E)},finish:function(x){return m(k.f,x)}},m=function(x,v,E){k.p=w.prev,k.n=w.next;try{return x(v,E)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return y.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,k){return u.w(b(y),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:i,async:function(y,w,m,k,x){return(g(w)?n:o)(b(y),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=pe((s,e)=>{le(),ue(),ce();var t=Wu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Vu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Ru(),Du(),Os(),$u(),zu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(s,function(t,r,o,n,i,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var f=function(m){return d(d({},m),{},{connect:function(k){var x=k.call;return i(a.mark(function v(){var E,S,I,P;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,O.next=1,x("connect",{port:S},[S]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(k){var x=k.call;return(function(){var v=i(a.mark(function E(S){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(S),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,x("disconnect",{portId:I});case 2:case"end":return P.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(k){var x=k.call;return function(){return x("isSupported")}}})};function g(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var k=new Map;return b.set(m,k),k},w=function(m){var k=f(m);return function(x){var v=y(x);x.addEventListener("message",function(D){var U=D.data,ae=U.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),V=Y.reject,re=Y.resolve;v.delete(ae),U.error===void 0?re(U.result):V(new Error(U.error.message))}}),l(x)&&x.start();for(var E=function(D){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),U===null?x.postMessage({id:re,method:D},ae):x.postMessage({id:re,method:D,params:U},ae)})},S=function(D,U){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},ae)},I={},P=0,O=Object.entries(k);P<O.length;P++){var j=o(O[P],2),T=j[0],q=j[1];I=h(h({},I),{},r({},T,q({call:E,notify:S})))}return h({},I)}};t.createBroker=w})}),Ku=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Sr(),Vu(),Os()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(s,function(t,r,o,n){var i=new Map([[0,null]]),a=new Map([[0,null]]),l=o.createBroker({clearInterval:function(u){var d=u.call;return function(f){r(i.get(f))==="symbol"&&(i.set(f,null),d("clear",{timerId:f,timerType:"interval"}).then(function(){i.delete(f)}))}},clearTimeout:function(u){var d=u.call;return function(f){r(a.get(f))==="symbol"&&(a.set(f,null),d("clear",{timerId:f,timerType:"timeout"}).then(function(){a.delete(f)}))}},setInterval:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(i);i.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=i.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(f.apply(void 0,b),i.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),f.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),Gu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Ku()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(s,function(t,r){var o=function(d,f){var g=null;return function(){if(g!==null)return g;var h=new Blob([f],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(h);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=o(r.load,n),a=function(d){return i().clearInterval(d)},l=function(d){return i().clearTimeout(d)},c=function(){var d;return(d=i()).setInterval.apply(d,arguments)},u=function(){var d;return(d=i()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Er=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.isReactNativeBrowser=s.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Ne?.versions?!Object.prototype.hasOwnProperty.call(Ne.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",o=e()||t()||r();s.isWebWorker=t(),s.isReactNativeBrowser=r(),s.default=o}),Yu=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(c,u,d,f){f===void 0&&(f=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,f,g)}:function(c,u,d,f){f===void 0&&(f=d),c[f]=u[d]}),t=s&&s.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=s&&s.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var f=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(f[f.length]=g);return f},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var f=c(u),g=0;g<f.length;g++)f[g]!=="default"&&e(d,u,f[g]);return t(d,u),d}})();Object.defineProperty(s,"__esModule",{value:!0});var o=Gu(),n=r(Er()),i={set:o.setInterval,clear:o.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:a}};s.default=l}),Us=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(s,"__esModule",{value:!0});var t=e(Yu()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(o,n){this.client=o,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(o.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(o){if(o*=1e3,isNaN(o)||o<=0||o>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${o}`);this._keepalive=o,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${o}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let o=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+o,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};s.default=r}),_i=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var P=Object.getOwnPropertyDescriptor(E,S);(!P||("get"in P?!E.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,P)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=s&&s.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=s&&s.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var P in S)Object.prototype.hasOwnProperty.call(S,P)&&(I[I.length]=P);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),P=0;P<I.length;P++)I[P]!=="default"&&e(S,E,I[P]);return t(S,E),S}})(),o=s&&s.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(s,"__esModule",{value:!0});var n=o(ou()),i=Ot(),a=o(au()),l=o(pt()),c=r(_s()),u=o(xs()),d=o(Tu()),f=o(Ps()),g=o(Cu()),h=qt(),b=Pu(),y=o(Us()),w=r(Er()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,h.nextTick)(()=>{E(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class jo extends b.TypedEventEmitter{static VERSION=h.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(E,S){super(),this.options=S||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=S[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",jo.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",S.protocol),this.log("MqttClient :: options.protocolVersion",S.protocolVersion),this.log("MqttClient :: options.username",S.username),this.log("MqttClient :: options.keepalive",S.keepalive),this.log("MqttClient :: options.reconnectPeriod",S.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",S.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",S.properties?S.properties.topicAliasMaximum:void 0),this.options.clientId=typeof S.clientId=="string"?S.clientId:jo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new f.default:this.options.messageIdProvider,this.outgoingStore=S.outgoingStore||new u.default,this.incomingStore=S.incomingStore||new u.default,this.queueQoSZero=S.queueQoSZero===void 0?!0:S.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,S.properties&&S.properties.topicAliasMaximum>0&&(S.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let j=null;if(!O){this._resubscribe();return}j=O.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,q=>{O.cb&&O.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),P())};this.log("connect :: sending queued packets"),P()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new i.Writable,S=n.default.parser(this.options),I=null,P=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),S.on("packet",D=>{this.log("parser :: on packet push to packets array."),P.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=P.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,j);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(P.length)(0,h.nextTick)(O);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(E),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let q={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(E,S,I,P){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:j,retain:T,dup:q,properties:D,cbStorePut:U}=I;if(this._checkDisconnecting(P))return this;let ae=()=>{let Y=0;if((j===1||j===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let V={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:Y,dup:q};switch(O.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,P,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(E,S,I){return new Promise((P,O)=>{this.publish(E,S,I,(j,T)=>{j?O(j):P(T)})})}subscribe(E,S,I){let P=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let O=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,j=Object.keys(E));let T=c.validateTopics(j);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let q={qos:0};P===5&&(q.nl=!1,q.rap=!1,q.rh=0),S={...q,...S};let{properties:D}=S,U=[],ae=(re,$)=>{if($=$||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<$.qos||O){let Z={topic:re,qos:$.qos};P===5&&(Z.nl=$.nl,Z.rap=$.rap,Z.rh=$.rh,Z.properties=D),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),U.push(Z)}};if(Array.isArray(E)?E.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),ae(re,E[re])}),!U.length)return I(null,[]),this;let Y=(re,$)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:$};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};P===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,Q.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:K}=we;for(let N=0;N<K.length;N+=1)re[N].qos=K[N]}te?be(new h.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,$=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;$.push(Y(M,Q))}return Promise.all($).then(Z=>{I(null,U,Z.at(-1))}).catch(Z=>{I(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,S){return new Promise((I,P)=>{this.subscribe(E,S,(O,j)=>{O?P(O):I(j)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let P=c.validateTopics(E);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,P)=>{this.unsubscribe(E,S,(O,j)=>{O?P(O):I(j)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=j||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,h.nextTick)(P)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(E,S){return new Promise((I,P)=>{this.end(E,S,O=>{O?P(O):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let P={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(P,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let P=E,O;if(P.cmd==="publish"&&(P=(0,a.default)(E),O=this._removeTopicAliasAndRecoverTopicName(P),O))return S&&S(O);this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(E,S,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let O=this._applyTopicAlias(E);if(O){S(O);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(P){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let P=E;if(P.cmd==="publish"){P=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(P);if(j)return S&&S(j)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:S}):O>0?(S=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let j=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){q&&q(D,U),j()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),j()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,P)=>{S(I,P),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};s.default=x}),Ju=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Cs(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};s.default=t});function Qu(){if(xi)return Ar;xi=!0;let s=2147483647,e=36,t=1,r=26,o=38,n=700,i=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,h=Math.floor,b=String.fromCharCode;function y(O){throw new RangeError(f[O])}function w(O,j){let T=[],q=O.length;for(;q--;)T[q]=j(O[q]);return T}function m(O,j){let T=O.split("@"),q="";T.length>1&&(q=T[0]+"@",O=T[1]),O=O.replace(d,".");let D=O.split("."),U=w(D,j).join(".");return q+U}function k(O){let j=[],T=0,q=O.length;for(;T<q;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=O.charCodeAt(T++);(U&64512)==56320?j.push(((D&1023)<<10)+(U&1023)+65536):(j.push(D),T--)}else j.push(D)}return j}let x=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},E=function(O,j){return O+22+75*(O<26)-((j!=0)<<5)},S=function(O,j,T){let q=0;for(O=T?h(O/n):O>>1,O+=h(O/j);O>g*r>>1;q+=e)O=h(O/g);return h(q+(g+1)*O/(O+o))},I=function(O){let j=[],T=O.length,q=0,D=a,U=i,ae=O.lastIndexOf(l);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&y("not-basic"),j.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let V=q;for(let $=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&y("invalid-input"),M>h((s-q)/$)&&y("overflow"),q+=M*$;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let be=e-Q;$>h(s/be)&&y("overflow"),$*=be}let re=j.length+1;U=S(q-V,re,V==0),h(q/re)>s-D&&y("overflow"),D+=h(q/re),q%=re,j.splice(q++,0,D)}return String.fromCodePoint(...j)},P=function(O){let j=[];O=k(O);let T=O.length,q=a,D=0,U=i;for(let V of O)V<128&&j.push(b(V));let ae=j.length,Y=ae;for(ae&&j.push(l);Y<T;){let V=s;for(let $ of O)$>=q&&$<V&&(V=$);let re=Y+1;V-q>h((s-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let $ of O)if($<q&&++D>s&&y("overflow"),$===q){let Z=D;for(let M=e;;M+=e){let Q=M<=U?t:M>=U+r?r:M-U;if(Z<Q)break;let be=Z-Q,te=e-Q;j.push(b(E(Q+be%te,0))),Z=h(be/te)}j.push(b(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return j.join("")};return Ar={version:"2.3.1",ucs2:{decode:k,encode:x},decode:I,encode:P,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+P(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},Ar}var Ar,xi,_t,Xu=Ye(()=>{le(),ue(),ce(),Ar={},xi=!1,_t=Qu(),_t.decode,_t.encode,_t.toASCII,_t.toUnicode,_t.ucs2,_t.version});function Zu(){return Ii||(Ii=!0,Ai=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var s={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;s[e]=r;for(e in s)return!1;if(typeof Object.keys=="function"&&Object.keys(s).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(s).length!==0)return!1;var o=Object.getOwnPropertySymbols(s);if(o.length!==1||o[0]!==e||!Object.prototype.propertyIsEnumerable.call(s,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(s,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ai}function ed(){return Ci||(Ci=!0,Ti=Error),Ti}function td(){return Oi||(Oi=!0,Pi=EvalError),Pi}function rd(){return Ri||(Ri=!0,Mi=RangeError),Mi}function nd(){return Ni||(Ni=!0,Li=ReferenceError),Li}function Bs(){return Ui||(Ui=!0,ji=SyntaxError),ji}function ir(){return Di||(Di=!0,Bi=TypeError),Bi}function id(){return Fi||(Fi=!0,$i=URIError),$i}function od(){if(qi)return Ir;qi=!0;var s=typeof Symbol<"u"&&Symbol,e=Zu();return Ir=function(){return typeof s!="function"||typeof Symbol!="function"||typeof s("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Ir}function sd(){if(Hi)return Tr;Hi=!0;var s={__proto__:null,foo:{}},e=Object;return Tr=function(){return{__proto__:s}.foo===s.foo&&!(s instanceof e)},Tr}function ad(){if(Wi)return Cr;Wi=!0;var s="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},i=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Cr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(s+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,o(c,arguments));return Object(y)===y?y:this}return l.apply(a,o(c,arguments))},f=t(0,l.length-c.length),g=[],h=0;h<f;h++)g[h]="$"+h;if(u=Function("binder","return function ("+i(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},Cr}function Si(){if(zi)return Pr;zi=!0;var s=ad();return Pr=Function.prototype.bind||s,Pr}function ld(){if(Vi)return Or;Vi=!0;var s=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Si();return Or=t.call(s,e),Or}function Ht(){if(Ki)return Mr;Ki=!0;var s,e=ed(),t=td(),r=rd(),o=nd(),n=Bs(),i=ir(),a=id(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new i},f=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=od()(),h=sd()(),b=Object.getPrototypeOf||(h?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?s:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?s:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?s:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):s,"%AsyncFromSyncIteratorPrototype%":s,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?s:Atomics,"%BigInt%":typeof BigInt>"u"?s:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?s:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?s:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?s:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?s:Float32Array,"%Float64Array%":typeof Float64Array>"u"?s:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?s:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?s:Int8Array,"%Int16Array%":typeof Int16Array>"u"?s:Int16Array,"%Int32Array%":typeof Int32Array>"u"?s:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):s,"%JSON%":typeof JSON=="object"?JSON:s,"%Map%":typeof Map>"u"?s:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?s:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?s:Promise,"%Proxy%":typeof Proxy>"u"?s:Proxy,"%RangeError%":r,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?s:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?s:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?s:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?s:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):s,"%Symbol%":g?Symbol:s,"%SyntaxError%":n,"%ThrowTypeError%":f,"%TypedArray%":w,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?s:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?s:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?s:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?s:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?s:WeakMap,"%WeakRef%":typeof WeakRef>"u"?s:WeakRef,"%WeakSet%":typeof WeakSet>"u"?s:WeakSet};if(b)try{null.error}catch(Y){var k=b(b(Y));m["%Error.prototype%"]=k}var x=function Y(V){var re;if(V==="%AsyncFunction%")re=c("async function () {}");else if(V==="%GeneratorFunction%")re=c("function* () {}");else if(V==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(V==="%AsyncGenerator%"){var $=Y("%AsyncGeneratorFunction%");$&&(re=$.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&b&&(re=b(Z.prototype))}return m[V]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},E=Si(),S=ld(),I=E.call(Function.call,Array.prototype.concat),P=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),j=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var V=j(Y,0,1),re=j(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var $=[];return O(Y,q,function(Z,M,Q,be){$[$.length]=Q?O(be,D,"$1"):M||Z}),$},ae=function(Y,V){var re=Y,$;if(S(v,re)&&($=v[re],re="%"+$[0]+"%"),S(m,re)){var Z=m[re];if(Z===y&&(Z=x(re)),typeof Z>"u"&&!V)throw new i("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:$,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return Mr=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="boolean")throw new i('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=U(Y),$=re.length>0?re[0]:"",Z=ae("%"+$+"%",V),M=Z.name,Q=Z.value,be=!1,te=Z.alias;te&&($=te[0],P(re,I([0,1],te)));for(var we=1,K=!0;we<re.length;we+=1){var N=re[we],ne=j(N,0,1),W=j(N,-1);if((ne==='"'||ne==="'"||ne==="`"||W==='"'||W==="'"||W==="`")&&ne!==W)throw new n("property names with quotes must have matching quotes");if((N==="constructor"||!K)&&(be=!0),$+="."+N,M="%"+$+"%",S(m,M))Q=m[M];else if(Q!=null){if(!(N in Q)){if(!V)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var G=u(Q,N);K=!!G,K&&"get"in G&&!("originalValue"in G.get)?Q=G.get:Q=Q[N]}else K=S(Q,N),Q=Q[N];K&&!be&&(m[M]=Q)}}return Q},Mr}function Ei(){if(Gi)return Rr;Gi=!0;var s=Ht(),e=s("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Rr=e,Rr}function Ds(){if(Yi)return Lr;Yi=!0;var s=Ht(),e=s("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Lr=e,Lr}function cd(){if(Ji)return Nr;Ji=!0;var s=Ei(),e=Bs(),t=ir(),r=Ds();return Nr=function(o,n,i){if(!o||typeof o!="object"&&typeof o!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(o,n);if(s)s(o,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:i,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)o[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Nr}function ud(){if(Qi)return jr;Qi=!0;var s=Ei(),e=function(){return!!s};return e.hasArrayLengthDefineBug=function(){if(!s)return null;try{return s([],"length",{value:1}).length!==1}catch{return!0}},jr=e,jr}function dd(){if(Xi)return Ur;Xi=!0;var s=Ht(),e=cd(),t=ud()(),r=Ds(),o=ir(),n=s("%Math.floor%");return Ur=function(i,a){if(typeof i!="function")throw new o("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new o("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in i&&r){var d=r(i,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(i,"length",a,!0,!0):e(i,"length",a)),i},Ur}function hd(){if(Zi)return Wt;Zi=!0;var s=Si(),e=Ht(),t=dd(),r=ir(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||s.call(n,o),a=Ei(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var d=i(s,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(s,o,arguments)};return a?a(Wt,"apply",{value:c}):Wt.apply=c,Wt}function fd(){if(eo)return Br;eo=!0;var s=Ht(),e=hd(),t=e(s("String.prototype.indexOf"));return Br=function(r,o){var n=s(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Br}var Ai,Ii,Ti,Ci,Pi,Oi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,$i,Fi,Ir,qi,Tr,Hi,Cr,Wi,Pr,zi,Or,Vi,Mr,Ki,Rr,Gi,Lr,Yi,Nr,Ji,jr,Qi,Ur,Xi,Wt,Zi,Br,eo,pd=Ye(()=>{le(),ue(),ce(),Ai={},Ii=!1,Ti={},Ci=!1,Pi={},Oi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,$i={},Fi=!1,Ir={},qi=!1,Tr={},Hi=!1,Cr={},Wi=!1,Pr={},zi=!1,Or={},Vi=!1,Mr={},Ki=!1,Rr={},Gi=!1,Lr={},Yi=!1,Nr={},Ji=!1,jr={},Qi=!1,Ur={},Xi=!1,Wt={},Zi=!1,Br={},eo=!1});function to(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function md(){!Mt||!Rt||(Mt=!1,Rt.length?rt=Rt.concat(rt):or=-1,rt.length&&$s())}function $s(){if(!Mt){var s=setTimeout(md,0);Mt=!0;for(var e=rt.length;e;){for(Rt=rt,rt=[];++or<e;)Rt&&Rt[or].run();or=-1,e=rt.length}Rt=null,Mt=!1,clearTimeout(s)}}function gd(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new Fs(s,e)),rt.length===1&&!Mt&&setTimeout($s,0)}function Fs(s,e){this.fun=s,this.array=e}function We(){}function bd(s){to("_linkedBinding")}function yd(s){to("dlopen")}function vd(){return[]}function wd(){return[]}function kd(s,e){if(!s)throw new Error(e||"assertion error")}function _d(){return!1}function xd(){return bt.now()/1e3}function ro(s){var e=Math.floor((Date.now()-bt.now())*.001),t=bt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=$r)),[r,o]}function xt(){return io}function Sd(s){return[]}var rt,Mt,Rt,or,qs,Hs,Ws,zs,Vs,Ks,Gs,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,Dr,ca,ua,da,ha,fa,pa,ma,ga,ba,ya,va,wa,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,Ma,Ra,bt,no,$r,La,Na,ja,Ua,Ba,Da,$a,Fa,qa,Ha,Wa,io,za=Ye(()=>{le(),ue(),ce(),rt=[],Mt=!1,or=-1,Fs.prototype.run=function(){this.fun.apply(null,this.array)},qs="browser",Hs="x64",Ws="browser",zs={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Vs=["/usr/bin/node"],Ks=[],Gs="v16.8.0",Ys={},Js=function(s,e){console.warn((e?e+": ":"")+s)},Qs=function(s){to("binding")},Xs=function(s){return 0},Zs=function(){return"/"},ea=function(s){},ta={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ra=We,na=[],ia={},oa=!1,sa={},aa=We,la=We,Dr=function(){return{}},ca=Dr,ua=Dr,da=We,ha=We,fa=We,pa={},ma={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ga=We,ba=We,ya=We,va=We,wa=We,ka=We,_a=We,xa=void 0,Sa=void 0,Ea=void 0,Aa=We,Ia=2,Ta=1,Ca="/bin/usr/node",Pa=9229,Oa="node",Ma=[],Ra=We,bt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},bt.now===void 0&&(no=Date.now(),bt.timing&&bt.timing.navigationStart&&(no=bt.timing.navigationStart),bt.now=()=>Date.now()-no),$r=1e9,ro.bigint=function(s){var e=ro(s);return typeof BigInt>"u"?e[0]*$r+e[1]:BigInt(e[0]*$r)+BigInt(e[1])},La=10,Na={},ja=0,Ua=xt,Ba=xt,Da=xt,$a=xt,Fa=xt,qa=We,Ha=xt,Wa=xt,io={version:Gs,versions:Ys,arch:Hs,platform:Ws,release:ta,_rawDebug:ra,moduleLoadList:na,binding:Qs,_linkedBinding:bd,_events:Na,_eventsCount:ja,_maxListeners:La,on:xt,addListener:Ua,once:Ba,off:Da,removeListener:$a,removeAllListeners:Fa,emit:qa,prependListener:Ha,prependOnceListener:Wa,listeners:Sd,domain:ia,_exiting:oa,config:sa,dlopen:yd,uptime:xd,_getActiveRequests:vd,_getActiveHandles:wd,reallyExit:aa,_kill:la,cpuUsage:Dr,resourceUsage:ca,memoryUsage:ua,kill:da,exit:ha,openStdin:fa,allowedNodeEnvironmentFlags:pa,assert:kd,features:ma,_fatalExceptions:ga,setUncaughtExceptionCaptureCallback:ba,hasUncaughtExceptionCaptureCallback:_d,emitWarning:Js,nextTick:gd,_tickCallback:ya,_debugProcess:va,_debugEnd:wa,_startProfilerIdleNotifier:ka,_stopProfilerIdleNotifier:_a,stdout:xa,stdin:Ea,stderr:Sa,abort:Aa,umask:Xs,chdir:ea,cwd:Zs,env:zs,title:qs,argv:Vs,execArgv:Ks,pid:Ia,ppid:Ta,execPath:Ca,debugPort:Pa,hrtime:ro,argv0:Oa,_preload_modules:Ma,setSourceMapsEnabled:Ra}});function Ed(){if(oo)return Fr;oo=!0;var s=io;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,i){for(var a="",l=0,c=-1,u=0,d,f=0;f<=n.length;++f){if(f<n.length)d=n.charCodeAt(f);else{if(d===47)break;d=47}if(d===47){if(!(c===f-1||u===1))if(c!==f-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=f,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=f,u=0;continue}}i&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,f):a=n.slice(c+1,f),l=f-c-1;c=f,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,i){var a=i.dir||i.root,l=i.base||(i.name||"")+(i.ext||"");return a?a===i.root?a+l:a+n+l:l}var o={resolve:function(){for(var n="",i=!1,a,l=arguments.length-1;l>=-1&&!i;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=s.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,i=c.charCodeAt(0)===47)}return n=t(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var i=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&a&&(n+="/"),i?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,i=0;i<arguments.length;++i){var a=arguments[i];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":o.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=o.resolve(n),i=o.resolve(i),n===i))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var d=i.length,f=d-u,g=c<f?c:f,h=-1,b=0;b<=g;++b){if(b===g){if(f>g){if(i.charCodeAt(u+b)===47)return i.slice(u+b+1);if(b===0)return i.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?h=b:b===0&&(h=0));break}var y=n.charCodeAt(a+b),w=i.charCodeAt(u+b);if(y!==w)break;y===47&&(h=b)}var m="";for(b=a+h+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+i.slice(u+h):(u+=h,i.charCodeAt(u)===47&&++u,i.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var i=n.charCodeAt(0),a=i===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var d=i.length-1,f=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else f===-1&&(c=!1,f=u+1),d>=0&&(g===i.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=f))}return a===l?l=f:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var i=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var f=n.charCodeAt(d);if(f===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),f===46?i===-1?i=d:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||l===-1||u===0||u===1&&i===l-1&&i===a+1?"":n.slice(i,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var i={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return i;var a=n.charCodeAt(0),l=a===47,c;l?(i.root="/",c=1):c=0;for(var u=-1,d=0,f=-1,g=!0,h=n.length-1,b=0;h>=c;--h){if(a=n.charCodeAt(h),a===47){if(!g){d=h+1;break}continue}f===-1&&(g=!1,f=h+1),a===46?u===-1?u=h:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||f===-1||b===0||b===1&&u===f-1&&u===d+1?f!==-1&&(d===0&&l?i.base=i.name=n.slice(1,f):i.base=i.name=n.slice(d,f)):(d===0&&l?(i.name=n.slice(1,u),i.base=n.slice(1,f)):(i.name=n.slice(d,u),i.base=n.slice(d,f)),i.ext=n.slice(u,f)),d>0?i.dir=n.slice(0,d-1):l&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Fr=o,Fr}var Fr,oo,so,Ad=Ye(()=>{le(),ue(),ce(),za(),Fr={},oo=!1,so=Ed()}),Va={};Bt(Va,{URL:()=>nl,Url:()=>Xa,default:()=>ze,fileURLToPath:()=>Ga,format:()=>Za,parse:()=>rl,pathToFileURL:()=>Ya,resolve:()=>el,resolveObject:()=>tl});function Id(){if(lo)return qr;lo=!0;var s=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=s&&e&&typeof e.get=="function"?e.get:null,r=s&&Map.prototype.forEach,o=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=o&&n&&typeof n.get=="function"?n.get:null,a=o&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,f=typeof WeakRef=="function"&&WeakRef.prototype,g=f?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Te=String(Ae),Oe=m.call(ie,Te.length+1);return k.call(Te,Ee,"$&_")+"."+k.call(k.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ee,"$&_")}var re=Ja,$=re.custom,Z=G($)?$:null;qr=function z(ie,Ee,Ae,Te){var Oe=Ee||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var nt=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof nt!="boolean"&&nt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var it=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ve=String(ie);return it?V(ie,Ve):Ve}if(typeof ie=="bigint"){var ot=String(ie)+"n";return it?V(ie,ot):ot}var Jt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Jt&&Jt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var st=X(Oe,Ae);if(typeof Te>"u")Te=[];else if(ee(Te,ie)>=0)return"[Circular]";function Ze(at,At,Ut){if(At&&(Te=P.call(Te),Te.push(At)),Ut){var lt={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(lt.quoteStyle=Oe.quoteStyle),z(at,lt,Ae+1,Te)}return z(at,Oe,Ae+1,Te)}if(typeof ie=="function"&&!we(ie)){var tn=F(ie),Qt=_e(ie,Ze);return"[Function"+(tn?": "+tn:" (anonymous)")+"]"+(Qt.length>0?" { "+I.call(Qt,", ")+" }":"")}if(G(ie)){var ur=D?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?p(ur):ur}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],ke=0;ke<L.length;ke++)C+=" "+L[ke].name+"="+M(Q(L[ke].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var xe=_e(ie,Ze);return st&&!B(xe)?"["+de(xe,st)+"]":"[ "+I.call(xe,", ")+" ]"}if(K(ie)){var Se=_e(ie,Ze);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Ze(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&nt){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Jt-Ae});if(nt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var De=[];return r&&r.call(ie,function(at,At){De.push(Ze(At,ie,!0)+" => "+Ze(at,ie))}),A("Map",t.call(ie),De,st)}if(H(ie)){var Ge=[];return a&&a.call(ie,function(at){Ge.push(Ze(at,ie))}),A("Set",i.call(ie),Ge,st)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return p(Ze(Number(ie)));if(J(ie))return p(Ze(j.call(ie)));if(W(ie))return p(h.call(ie));if(N(ie))return p(Ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Hr<"u"&&ie===Hr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=_e(ie,Ze),dr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,hr=ie instanceof Object?"":"null prototype",fr=!dr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):hr?"Object":"",rn=dr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",jt=rn+(fr||hr?"["+I.call(S.call([],fr||[],hr||[]),": ")+"] ":"");return et.length===0?jt+"{}":st?jt+"{"+de(et,st)+"}":jt+"{ "+I.call(et,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function Q(z){return k.call(String(z),/"/g,""")}function be(z){return R(z)==="[object Array]"&&(!U||!(typeof z=="object"&&U in z))}function te(z){return R(z)==="[object Date]"&&(!U||!(typeof z=="object"&&U in z))}function we(z){return R(z)==="[object RegExp]"&&(!U||!(typeof z=="object"&&U in z))}function K(z){return R(z)==="[object Error]"&&(!U||!(typeof z=="object"&&U in z))}function N(z){return R(z)==="[object String]"&&(!U||!(typeof z=="object"&&U in z))}function ne(z){return R(z)==="[object Number]"&&(!U||!(typeof z=="object"&&U in z))}function W(z){return R(z)==="[object Boolean]"&&(!U||!(typeof z=="object"&&U in z))}function G(z){if(D)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!q)return!1;try{return q.call(z),!0}catch{}return!1}function J(z){if(!z||typeof z!="object"||!j)return!1;try{return j.call(z),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(z){return z in(this||Hr)};function oe(z,ie){return ge.call(z,ie)}function R(z){return b.call(z)}function F(z){if(z.name)return z.name;var ie=w.call(y.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function he(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{i.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{d.call(z,d)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!g||!z||typeof z!="object")return!1;try{return g.call(z),!0}catch{}return!1}function H(z){if(!i||!z||typeof z!="object")return!1;try{i.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function me(z){if(!d||!z||typeof z!="object")return!1;try{d.call(z,d);try{c.call(z,c)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Te=k.call(k.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Ce);return M(Te,"single",ie)}function Ce(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function p(z){return"Object("+z+")"}function _(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Te=Ae?de(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Te+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
|
|
1
|
+
var AikaaraChat=(function(Pe){"use strict";class Uo{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class nn{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Uo(t,o=>{this.send({command:"message",identifier:t,data:JSON.stringify(o)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((o,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>o(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class mr{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(o){console.error(`Error in event handler for "${e}":`,o)}})}removeAllListeners(){this.handlers.clear()}}const Ec=1e3,Ac=10,Ic=400,Tc=600,Bo="#6366f1",Cc=12,Pc="system-ui, -apple-system, sans-serif",Do="Type a message...",Oc="bottom-right",Mc="light",Rc={x:20,y:20},on="aikaara_conversation_id";class $o extends mr{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new nn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,o){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...o&&{source:o}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Ac;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Ec)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const o=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new nn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Fo{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(o,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const i=await n.json();if(i&&typeof i=="object"&&"success"in i){if(!i.success)throw new Error(`API error: ${i.message||"Request failed"}`);return i.data}return i}async fetchWithHeaders(e,t,r){const o={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(o["X-Api-Key"]=this.apiKey),this.authToken&&(o.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:o};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class qo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const o={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(o),o}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(o=>o.status==="sending"&&o.role===e.role&&o.content===e.content&&o.conversationId===e.conversationId&&Date.now()-new Date(o.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const o=Ho(this._messages,e);return o?(Object.assign(o,e,{id:o.id}),{message:o,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(o=>o.externalId===e||o.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){const t=[];for(const r of e){const o=Ho(t,r);if(o){const n=gr(o),i=gr(r);!n&&i&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function Ho(s,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const i=gr(e),a=Wo(e),l=zo(e);if(!i&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=s.length-1;u>=0;u--){const d=s[u],f=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!f||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=gr(d);if(i&&y&&i===y)return d;const w=Wo(d);if(a&&w&&a===w)return d;const m=zo(d);if(l&&m&&l===m)return d}return null}function Wo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Vo(s);if(t)return t}function zo(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(s.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=s.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function gr(s){const e=s.attachments&&s.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(s.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Vo(s);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function Vo(s){const e=s.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Ko{_conversationId;persist;constructor(e,t=!0){this.persist=t,this._conversationId=e||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(e){this._conversationId=e,this.persist&&e&&this.saveToStorage(e)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(on)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(on)}catch{return null}}saveToStorage(e){try{localStorage.setItem(on,e)}catch{}}}var sn=Object.defineProperty,Lc=Object.getOwnPropertyDescriptor,Nc=Object.getOwnPropertyNames,jc=Object.prototype.hasOwnProperty,Ye=(s,e)=>()=>(s&&(e=s(s=0)),e),pe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Bt=(s,e)=>{for(var t in e)sn(s,t,{get:e[t],enumerable:!0})},Uc=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nc(e))!jc.call(s,o)&&o!==t&&sn(s,o,{get:()=>e[o],enumerable:!(r=Lc(e,o))||r.enumerable});return s},Re=s=>Uc(sn({},"__esModule",{value:!0}),s),le=Ye(()=>{}),Ne={};Bt(Ne,{_debugEnd:()=>Fn,_debugProcess:()=>$n,_events:()=>ni,_eventsCount:()=>ii,_exiting:()=>An,_fatalExceptions:()=>Un,_getActiveHandles:()=>es,_getActiveRequests:()=>Zo,_kill:()=>Cn,_linkedBinding:()=>Qo,_maxListeners:()=>ri,_preload_modules:()=>Zn,_rawDebug:()=>xn,_startProfilerIdleNotifier:()=>qn,_stopProfilerIdleNotifier:()=>Hn,_tickCallback:()=>Dn,abort:()=>Kn,addListener:()=>oi,allowedNodeEnvironmentFlags:()=>Nn,arch:()=>cn,argv:()=>hn,argv0:()=>Xn,assert:()=>ts,binding:()=>bn,browser:()=>_n,chdir:()=>wn,config:()=>In,cpuUsage:()=>Zt,cwd:()=>vn,debugPort:()=>Qn,default:()=>fi,dlopen:()=>Xo,domain:()=>En,emit:()=>ui,emitWarning:()=>gn,env:()=>dn,execArgv:()=>fn,execPath:()=>Jn,exit:()=>Rn,features:()=>jn,hasUncaughtExceptionCaptureCallback:()=>rs,hrtime:()=>br,kill:()=>Mn,listeners:()=>is,memoryUsage:()=>On,moduleLoadList:()=>Sn,nextTick:()=>Yo,off:()=>ai,on:()=>ct,once:()=>si,openStdin:()=>Ln,pid:()=>Gn,platform:()=>un,ppid:()=>Yn,prependListener:()=>di,prependOnceListener:()=>hi,reallyExit:()=>Tn,release:()=>kn,removeAllListeners:()=>ci,removeListener:()=>li,resourceUsage:()=>Pn,setSourceMapsEnabled:()=>ei,setUncaughtExceptionCaptureCallback:()=>Bn,stderr:()=>zn,stdin:()=>Vn,stdout:()=>Wn,title:()=>ln,umask:()=>yn,uptime:()=>ns,version:()=>pn,versions:()=>mn});function an(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function Bc(){!It||!Tt||(It=!1,Tt.length?tt=Tt.concat(tt):Xt=-1,tt.length&&Go())}function Go(){if(!It){var s=setTimeout(Bc,0);It=!0;for(var e=tt.length;e;){for(Tt=tt,tt=[];++Xt<e;)Tt&&Tt[Xt].run();Xt=-1,e=tt.length}Tt=null,It=!1,clearTimeout(s)}}function Yo(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Jo(s,e)),tt.length===1&&!It&&setTimeout(Go,0)}function Jo(s,e){this.fun=s,this.array=e}function He(){}function Qo(s){an("_linkedBinding")}function Xo(s){an("dlopen")}function Zo(){return[]}function es(){return[]}function ts(s,e){if(!s)throw new Error(e||"assertion error")}function rs(){return!1}function ns(){return ut.now()/1e3}function br(s){var e=Math.floor((Date.now()-ut.now())*.001),t=ut.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=yr)),[r,o]}function ct(){return fi}function is(s){return[]}var tt,It,Tt,Xt,ln,cn,un,dn,hn,fn,pn,mn,gn,bn,yn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Zt,Pn,On,Mn,Rn,Ln,Nn,jn,Un,Bn,Dn,$n,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ut,ti,yr,ri,ni,ii,oi,si,ai,li,ci,ui,di,hi,fi,Dc=Ye(()=>{le(),ue(),ce(),tt=[],It=!1,Xt=-1,Jo.prototype.run=function(){this.fun.apply(null,this.array)},ln="browser",cn="x64",un="browser",dn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},hn=["/usr/bin/node"],fn=[],pn="v16.8.0",mn={},gn=function(s,e){console.warn((e?e+": ":"")+s)},bn=function(s){an("binding")},yn=function(s){return 0},vn=function(){return"/"},wn=function(s){},kn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},_n=!0,xn=He,Sn=[],En={},An=!1,In={},Tn=He,Cn=He,Zt=function(){return{}},Pn=Zt,On=Zt,Mn=He,Rn=He,Ln=He,Nn={},jn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Un=He,Bn=He,Dn=He,$n=He,Fn=He,qn=He,Hn=He,Wn=void 0,zn=void 0,Vn=void 0,Kn=He,Gn=2,Yn=1,Jn="/bin/usr/node",Qn=9229,Xn="node",Zn=[],ei=He,ut={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ut.now===void 0&&(ti=Date.now(),ut.timing&&ut.timing.navigationStart&&(ti=ut.timing.navigationStart),ut.now=()=>Date.now()-ti),yr=1e9,br.bigint=function(s){var e=br(s);return typeof BigInt>"u"?e[0]*yr+e[1]:BigInt(e[0]*yr)+BigInt(e[1])},ri=10,ni={},ii=0,oi=ct,si=ct,ai=ct,li=ct,ci=ct,ui=He,di=ct,hi=ct,fi={version:pn,versions:mn,arch:cn,platform:un,browser:_n,release:kn,_rawDebug:xn,moduleLoadList:Sn,binding:bn,_linkedBinding:Qo,_events:ni,_eventsCount:ii,_maxListeners:ri,on:ct,addListener:oi,once:si,off:ai,removeListener:li,removeAllListeners:ci,emit:ui,prependListener:di,prependOnceListener:hi,listeners:is,domain:En,_exiting:An,config:In,dlopen:Xo,uptime:ns,_getActiveRequests:Zo,_getActiveHandles:es,reallyExit:Tn,_kill:Cn,cpuUsage:Zt,resourceUsage:Pn,memoryUsage:On,kill:Mn,exit:Rn,openStdin:Ln,allowedNodeEnvironmentFlags:Nn,assert:ts,features:jn,_fatalExceptions:Un,setUncaughtExceptionCaptureCallback:Bn,hasUncaughtExceptionCaptureCallback:rs,emitWarning:gn,nextTick:Yo,_tickCallback:Dn,_debugProcess:$n,_debugEnd:Fn,_startProfilerIdleNotifier:qn,_stopProfilerIdleNotifier:Hn,stdout:Wn,stdin:Vn,stderr:zn,abort:Kn,umask:yn,chdir:wn,cwd:vn,env:dn,title:ln,argv:hn,execArgv:fn,pid:Gn,ppid:Yn,execPath:Jn,debugPort:Qn,hrtime:br,argv0:Xn,_preload_modules:Zn,setSourceMapsEnabled:ei}}),ce=Ye(()=>{Dc()});function $c(){if(pi)return Dt;pi=!0,Dt.byteLength=a,Dt.toByteArray=c,Dt.fromByteArray=f;for(var s=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,n=r.length;o<n;++o)s[o]=r[o],e[r.charCodeAt(o)]=o;e[45]=62,e[95]=63;function i(g){var h=g.length;if(h%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=h);var y=b===h?0:4-b%4;return[b,y]}function a(g){var h=i(g),b=h[0],y=h[1];return(b+y)*3/4-y}function l(g,h,b){return(h+b)*3/4-b}function c(g){var h,b=i(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)h=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=h>>16&255,m[k++]=h>>8&255,m[k++]=h&255;return w===2&&(h=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=h&255),w===1&&(h=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=h>>8&255,m[k++]=h&255),m}function u(g){return s[g>>18&63]+s[g>>12&63]+s[g>>6&63]+s[g&63]}function d(g,h,b){for(var y,w=[],m=h;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function f(g){for(var h,b=g.length,y=b%3,w=[],m=16383,k=0,x=b-y;k<x;k+=m)w.push(d(g,k,k+m>x?x:k+m));return y===1?(h=g[b-1],w.push(s[h>>2]+s[h<<4&63]+"==")):y===2&&(h=(g[b-2]<<8)+g[b-1],w.push(s[h>>10]+s[h>>4&63]+s[h<<2&63]+"=")),w.join("")}return Dt}function Fc(){return mi?er:(mi=!0,er.read=function(s,e,t,r,o){var n,i,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?o-1:0,f=t?-1:1,g=s[e+d];for(d+=f,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+s[e+d],d+=f,u-=8);for(i=n&(1<<-u)-1,n>>=-u,u+=r;u>0;i=i*256+s[e+d],d+=f,u-=8);if(n===0)n=1-c;else{if(n===l)return i?NaN:(g?-1:1)*(1/0);i=i+Math.pow(2,r),n=n-c}return(g?-1:1)*i*Math.pow(2,n-r)},er.write=function(s,e,t,r,o,n){var i,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,h=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,i=u):(i=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-i))<1&&(i--,l*=2),i+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(i++,l/=2),i+d>=u?(a=0,i=u):i+d>=1?(a=(e*l-1)*Math.pow(2,o),i=i+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),i=0));o>=8;s[t+g]=a&255,g+=h,a/=256,o-=8);for(i=i<<o|a,c+=o;c>0;s[t+g]=i&255,g+=h,i/=256,c-=8);s[t+g-h]|=b*128},er)}function qc(){if(gi)return vt;gi=!0;let s=$c(),e=Fc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;vt.Buffer=i,vt.SlowBuffer=w,vt.INSPECT_MAX_BYTES=50;let r=2147483647;vt.kMaxLength=r,i.TYPED_ARRAY_SUPPORT=o(),!i.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function o(){try{let p=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(p,_),p.foo()===42}catch{return!1}}Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}});function n(p){if(p>r)throw new RangeError('The value "'+p+'" is invalid for option "size"');let _=new Uint8Array(p);return Object.setPrototypeOf(_,i.prototype),_}function i(p,_,A){if(typeof p=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(p)}return a(p,_,A)}i.poolSize=8192;function a(p,_,A){if(typeof p=="string")return d(p,_);if(ArrayBuffer.isView(p))return g(p);if(p==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p);if(H(p,ArrayBuffer)||p&&H(p.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(p,SharedArrayBuffer)||p&&H(p.buffer,SharedArrayBuffer)))return h(p,_,A);if(typeof p=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=p.valueOf&&p.valueOf();if(B!=null&&B!==p)return i.from(B,_,A);let X=b(p);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof p[Symbol.toPrimitive]=="function")return i.from(p[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p)}i.from=function(p,_,A){return a(p,_,A)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array);function l(p){if(typeof p!="number")throw new TypeError('"size" argument must be of type number');if(p<0)throw new RangeError('The value "'+p+'" is invalid for option "size"')}function c(p,_,A){return l(p),p<=0?n(p):_!==void 0?typeof A=="string"?n(p).fill(_,A):n(p).fill(_):n(p)}i.alloc=function(p,_,A){return c(p,_,A)};function u(p){return l(p),n(p<0?0:y(p)|0)}i.allocUnsafe=function(p){return u(p)},i.allocUnsafeSlow=function(p){return u(p)};function d(p,_){if((typeof _!="string"||_==="")&&(_="utf8"),!i.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(p,_)|0,B=n(A),X=B.write(p,_);return X!==A&&(B=B.slice(0,X)),B}function f(p){let _=p.length<0?0:y(p.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=p[B]&255;return A}function g(p){if(H(p,Uint8Array)){let _=new Uint8Array(p);return h(_.buffer,_.byteOffset,_.byteLength)}return f(p)}function h(p,_,A){if(_<0||p.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(p.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(p):A===void 0?B=new Uint8Array(p,_):B=new Uint8Array(p,_,A),Object.setPrototypeOf(B,i.prototype),B}function b(p){if(i.isBuffer(p)){let _=y(p.length)|0,A=n(_);return A.length===0||p.copy(A,0,0,_),A}if(p.length!==void 0)return typeof p.length!="number"||me(p.length)?n(0):f(p);if(p.type==="Buffer"&&Array.isArray(p.data))return f(p.data)}function y(p){if(p>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return p|0}function w(p){return+p!=p&&(p=0),i.alloc(+p)}i.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==i.prototype},i.compare=function(p,_){if(H(p,Uint8Array)&&(p=i.from(p,p.offset,p.byteLength)),H(_,Uint8Array)&&(_=i.from(_,_.offset,_.byteLength)),!i.isBuffer(p)||!i.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===_)return 0;let A=p.length,B=_.length;for(let X=0,de=Math.min(A,B);X<de;++X)if(p[X]!==_[X]){A=p[X],B=_[X];break}return A<B?-1:B<A?1:0},i.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(p,_){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return i.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<p.length;++A)_+=p[A].length;let B=i.allocUnsafe(_),X=0;for(A=0;A<p.length;++A){let de=p[A];if(H(de,Uint8Array))X+de.length>B.length?(i.isBuffer(de)||(de=i.from(de)),de.copy(B,X)):Uint8Array.prototype.set.call(B,de,X);else if(i.isBuffer(de))de.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return B};function m(p,_){if(i.isBuffer(p))return p.length;if(ArrayBuffer.isView(p)||H(p,ArrayBuffer))return p.byteLength;if(typeof p!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof p);let A=p.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return F(p).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(p).length;default:if(X)return B?-1:F(p).length;_=(""+_).toLowerCase(),X=!0}}i.byteLength=m;function k(p,_,A){let B=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(p||(p="utf8");;)switch(p){case"hex":return V(this,_,A);case"utf8":case"utf-8":return q(this,_,A);case"ascii":return ae(this,_,A);case"latin1":case"binary":return Y(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(B)throw new TypeError("Unknown encoding: "+p);p=(p+"").toLowerCase(),B=!0}}i.prototype._isBuffer=!0;function x(p,_,A){let B=p[_];p[_]=p[A],p[A]=B}i.prototype.swap16=function(){let p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<p;_+=2)x(this,_,_+1);return this},i.prototype.swap32=function(){let p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<p;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},i.prototype.swap64=function(){let p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<p;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},i.prototype.toString=function(){let p=this.length;return p===0?"":arguments.length===0?q(this,0,p):k.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(p){if(!i.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:i.compare(this,p)===0},i.prototype.inspect=function(){let p="",_=vt.INSPECT_MAX_BYTES;return p=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(p+=" ... "),"<Buffer "+p+">"},t&&(i.prototype[t]=i.prototype.inspect),i.prototype.compare=function(p,_,A,B,X){if(H(p,Uint8Array)&&(p=i.from(p,p.offset,p.byteLength)),!i.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(_===void 0&&(_=0),A===void 0&&(A=p?p.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),_<0||A>p.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&_>=A)return 0;if(B>=X)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,X>>>=0,this===p)return 0;let de=X-B,_e=A-_,z=Math.min(de,_e),ie=this.slice(B,X),Ee=p.slice(_,A);for(let Ae=0;Ae<z;++Ae)if(ie[Ae]!==Ee[Ae]){de=ie[Ae],_e=Ee[Ae];break}return de<_e?-1:_e<de?1:0};function v(p,_,A,B,X){if(p.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:p.length-1),A<0&&(A=p.length+A),A>=p.length){if(X)return-1;A=p.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof _=="string"&&(_=i.from(_,B)),i.isBuffer(_))return _.length===0?-1:E(p,_,A,B,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(p,_,A):Uint8Array.prototype.lastIndexOf.call(p,_,A):E(p,[_],A,B,X);throw new TypeError("val must be string, number or Buffer")}function E(p,_,A,B,X){let de=1,_e=p.length,z=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(p.length<2||_.length<2)return-1;de=2,_e/=2,z/=2,A/=2}function ie(Ae,Te){return de===1?Ae[Te]:Ae.readUInt16BE(Te*de)}let Ee;if(X){let Ae=-1;for(Ee=A;Ee<_e;Ee++)if(ie(p,Ee)===ie(_,Ae===-1?0:Ee-Ae)){if(Ae===-1&&(Ae=Ee),Ee-Ae+1===z)return Ae*de}else Ae!==-1&&(Ee-=Ee-Ae),Ae=-1}else for(A+z>_e&&(A=_e-z),Ee=A;Ee>=0;Ee--){let Ae=!0;for(let Te=0;Te<z;Te++)if(ie(p,Ee+Te)!==ie(_,Te)){Ae=!1;break}if(Ae)return Ee}return-1}i.prototype.includes=function(p,_,A){return this.indexOf(p,_,A)!==-1},i.prototype.indexOf=function(p,_,A){return v(this,p,_,A,!0)},i.prototype.lastIndexOf=function(p,_,A){return v(this,p,_,A,!1)};function S(p,_,A,B){A=Number(A)||0;let X=p.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let de=_.length;B>de/2&&(B=de/2);let _e;for(_e=0;_e<B;++_e){let z=parseInt(_.substr(_e*2,2),16);if(me(z))return _e;p[A+_e]=z}return _e}function I(p,_,A,B){return ye(F(_,p.length-A),p,A,B)}function P(p,_,A,B){return ye(ee(_),p,A,B)}function O(p,_,A,B){return ye(fe(_),p,A,B)}function j(p,_,A,B){return ye(he(_,p.length-A),p,A,B)}i.prototype.write=function(p,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-_;if((A===void 0||A>X)&&(A=X),p.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return S(this,p,_,A);case"utf8":case"utf-8":return I(this,p,_,A);case"ascii":case"latin1":case"binary":return P(this,p,_,A);case"base64":return O(this,p,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,p,_,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(p,_,A){return _===0&&A===p.length?s.fromByteArray(p):s.fromByteArray(p.slice(_,A))}function q(p,_,A){A=Math.min(p.length,A);let B=[],X=_;for(;X<A;){let de=p[X],_e=null,z=de>239?4:de>223?3:de>191?2:1;if(X+z<=A){let ie,Ee,Ae,Te;switch(z){case 1:de<128&&(_e=de);break;case 2:ie=p[X+1],(ie&192)===128&&(Te=(de&31)<<6|ie&63,Te>127&&(_e=Te));break;case 3:ie=p[X+1],Ee=p[X+2],(ie&192)===128&&(Ee&192)===128&&(Te=(de&15)<<12|(ie&63)<<6|Ee&63,Te>2047&&(Te<55296||Te>57343)&&(_e=Te));break;case 4:ie=p[X+1],Ee=p[X+2],Ae=p[X+3],(ie&192)===128&&(Ee&192)===128&&(Ae&192)===128&&(Te=(de&15)<<18|(ie&63)<<12|(Ee&63)<<6|Ae&63,Te>65535&&Te<1114112&&(_e=Te))}}_e===null?(_e=65533,z=1):_e>65535&&(_e-=65536,B.push(_e>>>10&1023|55296),_e=56320|_e&1023),B.push(_e),X+=z}return U(B)}let D=4096;function U(p){let _=p.length;if(_<=D)return String.fromCharCode.apply(String,p);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,p.slice(B,B+=D));return A}function ae(p,_,A){let B="";A=Math.min(p.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(p[X]&127);return B}function Y(p,_,A){let B="";A=Math.min(p.length,A);for(let X=_;X<A;++X)B+=String.fromCharCode(p[X]);return B}function V(p,_,A){let B=p.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let X="";for(let de=_;de<A;++de)X+=ve[p[de]];return X}function re(p,_,A){let B=p.slice(_,A),X="";for(let de=0;de<B.length-1;de+=2)X+=String.fromCharCode(B[de]+B[de+1]*256);return X}i.prototype.slice=function(p,_){let A=this.length;p=~~p,_=_===void 0?A:~~_,p<0?(p+=A,p<0&&(p=0)):p>A&&(p=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<p&&(_=p);let B=this.subarray(p,_);return Object.setPrototypeOf(B,i.prototype),B};function $(p,_,A){if(p%1!==0||p<0)throw new RangeError("offset is not uint");if(p+_>A)throw new RangeError("Trying to access beyond buffer length")}i.prototype.readUintLE=i.prototype.readUIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p],X=1,de=0;for(;++de<_&&(X*=256);)B+=this[p+de]*X;return B},i.prototype.readUintBE=i.prototype.readUIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p+--_],X=1;for(;_>0&&(X*=256);)B+=this[p+--_]*X;return B},i.prototype.readUint8=i.prototype.readUInt8=function(p,_){return p=p>>>0,_||$(p,1,this.length),this[p]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(p,_){return p=p>>>0,_||$(p,2,this.length),this[p]|this[p+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(p,_){return p=p>>>0,_||$(p,2,this.length),this[p]<<8|this[p+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(p,_){return p=p>>>0,_||$(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},i.prototype.readBigUInt64LE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=_+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,X=this[++p]+this[++p]*2**8+this[++p]*2**16+A*2**24;return BigInt(B)+(BigInt(X)<<BigInt(32))}),i.prototype.readBigUInt64BE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=_*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],X=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(X)}),i.prototype.readIntLE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=this[p],X=1,de=0;for(;++de<_&&(X*=256);)B+=this[p+de]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*_)),B},i.prototype.readIntBE=function(p,_,A){p=p>>>0,_=_>>>0,A||$(p,_,this.length);let B=_,X=1,de=this[p+--B];for(;B>0&&(X*=256);)de+=this[p+--B]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*_)),de},i.prototype.readInt8=function(p,_){return p=p>>>0,_||$(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},i.prototype.readInt16LE=function(p,_){p=p>>>0,_||$(p,2,this.length);let A=this[p]|this[p+1]<<8;return A&32768?A|4294901760:A},i.prototype.readInt16BE=function(p,_){p=p>>>0,_||$(p,2,this.length);let A=this[p+1]|this[p]<<8;return A&32768?A|4294901760:A},i.prototype.readInt32LE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},i.prototype.readInt32BE=function(p,_){return p=p>>>0,_||$(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},i.prototype.readBigInt64LE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++p]*256+this[++p]*65536+this[++p]*16777216)}),i.prototype.readBigInt64BE=se(function(p){p=p>>>0,J(p,"offset");let _=this[p],A=this[p+7];(_===void 0||A===void 0)&&ge(p,this.length-8);let B=(_<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(B)<<BigInt(32))+BigInt(this[++p]*16777216+this[++p]*65536+this[++p]*256+A)}),i.prototype.readFloatLE=function(p,_){return p=p>>>0,_||$(p,4,this.length),e.read(this,p,!0,23,4)},i.prototype.readFloatBE=function(p,_){return p=p>>>0,_||$(p,4,this.length),e.read(this,p,!1,23,4)},i.prototype.readDoubleLE=function(p,_){return p=p>>>0,_||$(p,8,this.length),e.read(this,p,!0,52,8)},i.prototype.readDoubleBE=function(p,_){return p=p>>>0,_||$(p,8,this.length),e.read(this,p,!1,52,8)};function Z(p,_,A,B,X,de){if(!i.isBuffer(p))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<de)throw new RangeError('"value" argument is out of bounds');if(A+B>p.length)throw new RangeError("Index out of range")}i.prototype.writeUintLE=i.prototype.writeUIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Z(this,p,_,A,_e,0)}let X=1,de=0;for(this[_]=p&255;++de<A&&(X*=256);)this[_+de]=p/X&255;return _+A},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;Z(this,p,_,A,_e,0)}let X=A-1,de=1;for(this[_+X]=p&255;--X>=0&&(de*=256);)this[_+X]=p/de&255;return _+A},i.prototype.writeUint8=i.prototype.writeUInt8=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,1,255,0),this[_]=p&255,_+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,65535,0),this[_]=p&255,this[_+1]=p>>>8,_+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,65535,0),this[_]=p>>>8,this[_+1]=p&255,_+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,4294967295,0),this[_+3]=p>>>24,this[_+2]=p>>>16,this[_+1]=p>>>8,this[_]=p&255,_+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,4294967295,0),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4};function M(p,_,A,B,X){G(_,B,X,p,A,7);let de=Number(_&BigInt(4294967295));p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de,de=de>>8,p[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,_e=_e>>8,p[A++]=_e,A}function Q(p,_,A,B,X){G(_,B,X,p,A,7);let de=Number(_&BigInt(4294967295));p[A+7]=de,de=de>>8,p[A+6]=de,de=de>>8,p[A+5]=de,de=de>>8,p[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return p[A+3]=_e,_e=_e>>8,p[A+2]=_e,_e=_e>>8,p[A+1]=_e,_e=_e>>8,p[A]=_e,A+8}i.prototype.writeBigUInt64LE=se(function(p,_=0){return M(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=se(function(p,_=0){return Q(this,p,_,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,p,_,A,z-1,-z)}let X=0,de=1,_e=0;for(this[_]=p&255;++X<A&&(de*=256);)p<0&&_e===0&&this[_+X-1]!==0&&(_e=1),this[_+X]=(p/de>>0)-_e&255;return _+A},i.prototype.writeIntBE=function(p,_,A,B){if(p=+p,_=_>>>0,!B){let z=Math.pow(2,8*A-1);Z(this,p,_,A,z-1,-z)}let X=A-1,de=1,_e=0;for(this[_+X]=p&255;--X>=0&&(de*=256);)p<0&&_e===0&&this[_+X+1]!==0&&(_e=1),this[_+X]=(p/de>>0)-_e&255;return _+A},i.prototype.writeInt8=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,1,127,-128),p<0&&(p=255+p+1),this[_]=p&255,_+1},i.prototype.writeInt16LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,32767,-32768),this[_]=p&255,this[_+1]=p>>>8,_+2},i.prototype.writeInt16BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,2,32767,-32768),this[_]=p>>>8,this[_+1]=p&255,_+2},i.prototype.writeInt32LE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,2147483647,-2147483648),this[_]=p&255,this[_+1]=p>>>8,this[_+2]=p>>>16,this[_+3]=p>>>24,_+4},i.prototype.writeInt32BE=function(p,_,A){return p=+p,_=_>>>0,A||Z(this,p,_,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[_]=p>>>24,this[_+1]=p>>>16,this[_+2]=p>>>8,this[_+3]=p&255,_+4},i.prototype.writeBigInt64LE=se(function(p,_=0){return M(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=se(function(p,_=0){return Q(this,p,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(p,_,A,B,X,de){if(A+B>p.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(p,_,A,B,X){return _=+_,A=A>>>0,X||be(p,_,A,4),e.write(p,_,A,B,23,4),A+4}i.prototype.writeFloatLE=function(p,_,A){return te(this,p,_,!0,A)},i.prototype.writeFloatBE=function(p,_,A){return te(this,p,_,!1,A)};function we(p,_,A,B,X){return _=+_,A=A>>>0,X||be(p,_,A,8),e.write(p,_,A,B,52,8),A+8}i.prototype.writeDoubleLE=function(p,_,A){return we(this,p,_,!0,A)},i.prototype.writeDoubleBE=function(p,_,A){return we(this,p,_,!1,A)},i.prototype.copy=function(p,_,A,B){if(!i.isBuffer(p))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=p.length&&(_=p.length),_||(_=0),B>0&&B<A&&(B=A),B===A||p.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),p.length-_<B-A&&(B=p.length-_+A);let X=B-A;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(p,this.subarray(A,B),_),X},i.prototype.fill=function(p,_,A,B){if(typeof p=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!i.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(p.length===1){let de=p.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(p=de)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,p||(p=0);let X;if(typeof p=="number")for(X=_;X<A;++X)this[X]=p;else{let de=i.isBuffer(p)?p:i.from(p,B),_e=de.length;if(_e===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=de[X%_e]}return this};let K={};function N(p,_,A){K[p]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${p}]`,this.stack,delete this.name}get code(){return p}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${p}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(p){return p?`${p} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(p,_){return`The "${p}" argument must be of type number. Received type ${typeof _}`},TypeError),N("ERR_OUT_OF_RANGE",function(p,_,A){let B=`The value of "${p}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${_}. Received ${X}`,B},RangeError);function ne(p){let _="",A=p.length,B=p[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${p.slice(A-3,A)}${_}`;return`${p.slice(0,A)}${_}`}function W(p,_,A){J(_,"offset"),(p[_]===void 0||p[_+A]===void 0)&&ge(_,p.length-(A+1))}function G(p,_,A,B,X,de){if(p>A||p<_){let _e=typeof _=="bigint"?"n":"",z;throw _===0||_===BigInt(0)?z=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:z=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new K.ERR_OUT_OF_RANGE("value",z,p)}W(B,X,de)}function J(p,_){if(typeof p!="number")throw new K.ERR_INVALID_ARG_TYPE(_,"number",p)}function ge(p,_,A){throw Math.floor(p)!==p?(J(p,A),new K.ERR_OUT_OF_RANGE("offset","an integer",p)):_<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,p)}let oe=/[^+/0-9A-Za-z-_]/g;function R(p){if(p=p.split("=")[0],p=p.trim().replace(oe,""),p.length<2)return"";for(;p.length%4!==0;)p=p+"=";return p}function F(p,_){_=_||1/0;let A,B=p.length,X=null,de=[];for(let _e=0;_e<B;++_e){if(A=p.charCodeAt(_e),A>55295&&A<57344){if(!X){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===B){(_-=3)>-1&&de.push(239,191,189);continue}X=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(_-=3)>-1&&de.push(239,191,189);if(X=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function ee(p){let _=[];for(let A=0;A<p.length;++A)_.push(p.charCodeAt(A)&255);return _}function he(p,_){let A,B,X,de=[];for(let _e=0;_e<p.length&&!((_-=2)<0);++_e)A=p.charCodeAt(_e),B=A>>8,X=A%256,de.push(X),de.push(B);return de}function fe(p){return s.toByteArray(R(p))}function ye(p,_,A,B){let X;for(X=0;X<B&&!(X+A>=_.length||X>=p.length);++X)_[X+A]=p[X];return X}function H(p,_){return p instanceof _||p!=null&&p.constructor!=null&&p.constructor.name!=null&&p.constructor.name===_.name}function me(p){return p!==p}let ve=(function(){let p="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)_[B+X]=p[A]+p[X]}return _})();function se(p){return typeof BigInt>"u"?Ce:p}function Ce(){throw new Error("BigInt not supported")}return vt}var Dt,pi,er,mi,vt,gi,Hc=Ye(()=>{le(),ue(),ce(),Dt={},pi=!1,er={},mi=!1,vt={},gi=!1}),$e={};Bt($e,{Buffer:()=>vr,INSPECT_MAX_BYTES:()=>os,default:()=>dt,kMaxLength:()=>ss});var dt,vr,os,ss,Fe=Ye(()=>{le(),ue(),ce(),Hc(),dt=qc(),dt.Buffer,dt.SlowBuffer,dt.INSPECT_MAX_BYTES,dt.kMaxLength,vr=dt.Buffer,os=dt.INSPECT_MAX_BYTES,ss=dt.kMaxLength}),ue=Ye(()=>{Fe()}),Be=pe((s,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let o="";for(let n=0;n<r.length;n++)o+=` ${r[n].stack}
|
|
2
|
+
`;super(o),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,o){return r.includes(o)},ArrayPrototypeIndexOf(r,o){return r.indexOf(o)},ArrayPrototypeJoin(r,o){return r.join(o)},ArrayPrototypeMap(r,o){return r.map(o)},ArrayPrototypePop(r,o){return r.pop(o)},ArrayPrototypePush(r,o){return r.push(o)},ArrayPrototypeSlice(r,o,n){return r.slice(o,n)},Error,FunctionPrototypeCall(r,o,...n){return r.call(o,...n)},FunctionPrototypeSymbolHasInstance(r,o){return Function.prototype[Symbol.hasInstance].call(r,o)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,o){return Object.defineProperties(r,o)},ObjectDefineProperty(r,o,n){return Object.defineProperty(r,o,n)},ObjectGetOwnPropertyDescriptor(r,o){return Object.getOwnPropertyDescriptor(r,o)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,o){return Object.setPrototypeOf(r,o)},Promise,PromisePrototypeCatch(r,o){return r.catch(o)},PromisePrototypeThen(r,o,n){return r.then(o,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,o){return r.test(o)},SafeSet:Set,String,StringPrototypeSlice(r,o,n){return r.slice(o,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,o,n){return r.set(o,n)},Boolean,Uint8Array}}),as=pe((s,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[o,n]){let i=r.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),Ke=pe((s,e)=>{le(),ue(),ce();var{format:t,inspect:r}=as(),{AggregateError:o}=Be(),n=globalThis.AggregateError||o,i=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function f(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function g(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function h(m,k,x){x||(x=Error);class v extends x{constructor(...S){super(g(m,k,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:x.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${m}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=m,v.prototype[i]=!0,u[m]=v}function b(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function y(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};h("ERR_ASSERTION","%s",Error),h("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],I=[];for(let O of k)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?E.push(O.toLowerCase()):l.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(S.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var P;if((P=x.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${x.constructor.name}`;else{let O=r(x,{depth:-1});v+=`. Received ${O}`}}else{let O=r(x,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof x} (${O})`}return v},TypeError),h("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),h("ERR_INVALID_RETURN_VALUE",(m,k,x)=>{var v;let E=x!=null&&(v=x.constructor)!==null&&v!==void 0&&v.name?`instance of ${x.constructor.name}`:`type ${typeof x}`;return`Expected ${m} to be returned from the "${k}" function but got ${E}.`},TypeError),h("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),h("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=f(String(x));else if(typeof x=="bigint"){v=String(x);let E=BigInt(2)**BigInt(32);(x>E||x<-E)&&(v=f(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),h("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),h("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),h("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),h("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),h("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),h("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),h("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),h("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),h("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),h("ERR_STREAM_WRITE_AFTER_END","write after end",Error),h("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),tr=pe((s,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),wt={};Bt(wt,{EventEmitter:()=>ls,default:()=>$t,defaultMaxListeners:()=>cs,init:()=>us,listenerCount:()=>ds,on:()=>hs,once:()=>fs});function Wc(){if(bi)return rr;bi=!0;var s=typeof Reflect=="object"?Reflect:null,e=s&&typeof s.apply=="function"?s.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;s&&typeof s.ownKeys=="function"?t=s.ownKeys:Object.getOwnPropertySymbols?t=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:t=function(x){return Object.getOwnPropertyNames(x)};function r(x){console&&console.warn&&console.warn(x)}var o=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}rr=n,rr.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var i=10;function a(x){if(typeof x!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof x)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return i},set:function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");i=x}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var j=I[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,q=h(j,T),E=0;E<T;++E)e(q[E],this,v);return!0};function c(x,v,E,S){var I,P,O;if(a(E),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),P=x._events),O=P[v]),O===void 0)O=P[v]=E,++x._eventsCount;else if(typeof O=="function"?O=P[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),I=l(x),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=x,j.type=v,j.count=O.length,r(j)}return x}n.prototype.addListener=function(x,v){return c(this,x,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(x,v){return c(this,x,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(x,v){return a(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,I,P,O;if(a(v),S=this._events,S===void 0)return this;if(E=S[x],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[x],S.removeListener&&this.emit("removeListener",x,E.listener||v));else if(typeof E!="function"){for(I=-1,P=E.length-1;P>=0;P--)if(E[P]===v||E[P].listener===v){O=E[P].listener,I=P;break}if(I<0)return this;I===0?E.shift():b(E,I),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[x]),this;if(arguments.length===0){var I=Object.keys(E),P;for(S=0;S<I.length;++S)P=I[S],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(x,v[S]);return this};function f(x,v,E){var S=x._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?y(I):h(I,I.length)}n.prototype.listeners=function(x){return f(this,x,!0)},n.prototype.rawListeners=function(x){return f(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var E=v[x];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function h(x,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=x[S];return E}function b(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),E=0;E<v.length;++E)v[E]=x[E].listener||x[E];return v}function w(x,v){return new Promise(function(E,S){function I(O){x.removeListener(v,P),S(O)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),E([].slice.call(arguments))}k(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&k(x,"error",v,E)}function k(x,v,E,S){if(typeof x.on=="function")S.once?x.once(v,E):x.on(v,E);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(P){S.once&&x.removeEventListener(v,I),E(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return rr}var rr,bi,$t,ls,cs,us,ds,hs,fs,Ct=Ye(()=>{le(),ue(),ce(),rr={},bi=!1,$t=Wc(),$t.once,$t.once=function(s,e){return new Promise((t,r)=>{function o(...i){n!==void 0&&s.removeListener("error",n),t(i)}let n;e!=="error"&&(n=i=>{s.removeListener(name,o),r(i)},s.once("error",n)),s.once(e,o)})},$t.on=function(s,e){let t=[],r=[],o=null,n=!1,i={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(o){let u=Promise.reject(o);return o=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){s.removeListener(e,a),s.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){o=c,s.removeListener(e,a),s.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return s.on(e,a),s.on("error",l),i;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):o=c,i.return()}},{EventEmitter:ls,defaultMaxListeners:cs,init:us,listenerCount:ds,on:hs,once:fs}=$t}),Je=pe((s,e)=>{le(),ue(),ce();var t=(Fe(),Re($e)),{format:r,inspect:o}=as(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:i,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||tr().AbortSignal,u=globalThis.AbortController||tr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,f=globalThis.Blob||t.Blob,g=typeof f<"u"?function(y){return y instanceof f}:function(y){return!1},h=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,k)=>{y=m,w=k}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((k,...x)=>k?m(k):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Ct(),Re(wt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);h(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[i]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(k=>{h(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),nr=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:i,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:f,String:g,StringPrototypeToUpperCase:h,StringPrototypeTrim:b}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:E}=Je(),{isAsyncFunction:S,isArrayBufferView:I}=Je().types,P={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(f(T,H)===null)throw new k(me,H,q);H=u(H,8)}return Y(H,me),H}var U=y((H,me,ve=c,se=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),ae=y((H,me,ve=-2147483648,se=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);if(H<ve||H>se)throw new x(me,`>= ${ve} && <= ${se}`,H)}),Y=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!i(H))throw new x(me,"an integer",H);let se=ve?1:0,Ce=4294967295;if(H<se||H>Ce)throw new x(me,`>= ${se} && <= ${Ce}`,H)});function V(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,se){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||se!=null&&H>se||(ve!=null||se!=null)&&a(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&se!=null?" && ":""}${se!=null?`<= ${se}`:""}`,H)}var $=y((H,me,ve)=>{if(!r(ve,H)){let se="must be one of: "+o(n(ve,Ce=>typeof Ce=="string"?`'${Ce}'`:g(Ce)),", ");throw new k(me,H,se)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!d(H,me)?ve:H[me]}var Q=y((H,me,ve=null)=>{let se=M(ve,"allowArray",!1),Ce=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!se&&t(H)||typeof H!="object"&&(!Ce||typeof H!="function"))throw new m(me,"Object",H)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let se=`must be longer than ${ve}`;throw new k(me,H,se)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)V(H[ve],`${me}[${ve}]`)}function K(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function N(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let se=H[ve],Ce=`${me}[${ve}]`;if(se==null)throw new m(Ce,"AbortSignal",se);ge(se,Ce)}}function ne(H,me="signal"){if(V(H,me),P[H]===void 0)throw P[h(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var W=y((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function G(H,me){let ve=E(me),se=H.length;if(ve==="hex"&&se%2!==0)throw new k("encoding",me,`is invalid for data of length ${se}`)}function J(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&b(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),oe=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||S(H))throw new m(me,"Function",H)}),F=y((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${o(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!f(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let se=0;se<me;se++){let Ce=H[se];fe(Ce,"hints"),ve+=Ce,se!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:j,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:K,validateAbortSignalArray:N,validateBoolean:Z,validateBuffer:W,validateDictionary:be,validateEncoding:G,validateFunction:oe,validateInt32:ae,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:$,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:V,validateUint32:Y,validateUndefined:F,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Pt=pe((s,e)=>{le(),ue(),ce();var t=e.exports={},r,o;function n(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?o=clearTimeout:o=i}catch{o=i}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(o===clearTimeout)return clearTimeout(w);if((o===i||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(w);try{return o(w)}catch{try{return o.call(null,w)}catch{return o.call(this,w)}}}var c=[],u=!1,d,f=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):f=-1,c.length&&h())}function h(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++f<m;)d&&d[f].run();f=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new b(w,m)),c.length===1&&!u&&a(h)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),ht=pe((s,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Be(),n=o("nodejs.stream.destroyed"),i=o("nodejs.stream.errored"),a=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),c=o("nodejs.stream.disturbed"),u=o("nodejs.webstream.isClosedPromise"),d=o("nodejs.webstream.controllerErrorFunction");function f(M,Q=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function g(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.writable)!==!1))}function h(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function b(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!b(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!b(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!b(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function k(M){return y(M)||w(M)||m(M)}function x(M,Q){return M==null?!1:Q===!0?typeof M[t]=="function":Q===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function S(M,Q){if(!g(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||Q===!1&&be.ended===!0&&be.length===0)}function I(M){if(!f(M))return null;if(M.readableEnded===!0)return!0;let Q=M._readableState;return!Q||Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function P(M,Q){if(!f(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||Q===!1&&be.ended===!0&&be.length===0)}function O(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:f(M)&&M.readable&&!P(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!E(M)}function T(M,Q){return b(M)?v(M)?!0:!(Q?.readable!==!1&&O(M)||Q?.writable!==!1&&j(M)):null}function q(M){var Q,be;return b(M)?M.writableErrored?M.writableErrored:(Q=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,be;return b(M)?M.readableErrored?M.readableErrored:(Q=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!b(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,be=M._readableState;return typeof Q?.closed=="boolean"||typeof be?.closed=="boolean"?Q?.closed||be?.closed:typeof M._closed=="boolean"&&ae(M)?M._closed:null}function ae(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&ae(M)}function V(M){var Q;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((Q=M.req)===null||Q===void 0?void 0:Q.upgradeOrConnect)===void 0}function re(M){if(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function $(M){var Q;return!!(M&&((Q=M[c])!==null&&Q!==void 0?Q:M.readableDidRead||M.readableAborted))}function Z(M){var Q,be,te,we,K,N,ne,W,G,J;return!!(M&&((Q=(be=(te=(we=(K=(N=M[i])!==null&&N!==void 0?N:M.readableErrored)!==null&&K!==void 0?K:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(W=M._writableState)===null||W===void 0?void 0:W.errorEmitted)!==null&&be!==void 0?be:(G=M._readableState)===null||G===void 0?void 0:G.errored)!==null&&Q!==void 0?Q:!((J=M._writableState)===null||J===void 0)&&J.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:$,kIsDisturbed:c,isErrored:Z,kIsErrored:i,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:h,isFinished:T,isIterable:x,isReadableNodeStream:f,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:D,isNodeStream:b,isWebStream:k,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:q,isServerRequest:V,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),kt=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{AbortError:r,codes:o}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:i}=o,{kEmptyObject:a,once:l}=Je(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:f}=nr(),{Promise:g,PromisePrototypeThen:h,SymbolDispose:b}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:q}=ht(),D;function U($){return $.setHeader&&typeof $.abort=="function"}var ae=()=>{};function Y($,Z,M){var Q,be;if(arguments.length===2?(M=Z,Z=a):Z==null?Z=a:d(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),k($)||I($))return V($,Z,M);if(!j($))throw new n("stream",["ReadableStream","WritableStream","Stream"],$);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m($),we=(be=Z.writable)!==null&&be!==void 0?be:S($),K=$._writableState,N=$._readableState,ne=()=>{$.writable||J()},W=T($)&&m($)===te&&S($)===we,G=P($,!1),J=()=>{G=!0,$.destroyed&&(W=!1),!(W&&(!$.readable||te))&&(!te||ge)&&M.call($)},ge=x($,!1),oe=()=>{ge=!0,$.destroyed&&(W=!1),!(W&&(!$.writable||we))&&(!we||G)&&M.call($)},R=H=>{M.call($,H)},F=y($),ee=()=>{F=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);if(te&&!ge&&m($,!0)&&!x($,!1))return M.call($,new i);if(we&&!G&&!P($,!1))return M.call($,new i);M.call($)},he=()=>{F=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);M.call($)},fe=()=>{$.req.on("finish",J)};U($)?($.on("complete",J),W||$.on("abort",ee),$.req?fe():$.on("request",fe)):we&&!K&&($.on("end",ne),$.on("close",ne)),!W&&typeof $.aborted=="boolean"&&$.on("aborted",ee),$.on("end",oe),$.on("finish",J),Z.error!==!1&&$.on("error",R),$.on("close",ee),F?t.nextTick(ee):K!=null&&K.errorEmitted||N!=null&&N.errorEmitted?W||t.nextTick(he):(!te&&(!W||w($))&&(G||E($)===!1)||!we&&(!W||E($))&&(ge||w($)===!1)||N&&$.req&&$.aborted)&&t.nextTick(he);let ye=()=>{M=ae,$.removeListener("aborted",ee),$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",fe),$.req&&$.req.removeListener("finish",J),$.removeListener("end",ne),$.removeListener("close",ne),$.removeListener("finish",J),$.removeListener("end",oe),$.removeListener("error",R),$.removeListener("close",ee)};if(Z.signal&&!F){let H=()=>{let me=M;ye(),me.call($,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Je().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...se)=>{me[b](),ve.apply($,se)})}}return ye}function V($,Z,M){let Q=!1,be=ae;if(Z.signal)if(be=()=>{Q=!0,M.call($,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||Je().addAbortListener;let we=D(Z.signal,be),K=M;M=l((...N)=>{we[b](),K.apply($,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply($,we))};return h($[q].promise,te,te),ae}function re($,Z){var M;let Q=!1;return Z===null&&(Z=a),(M=Z)!==null&&M!==void 0&&M.cleanup&&(f(Z.cleanup,"cleanup"),Q=Z.cleanup),new g((be,te)=>{let we=Y($,Z,K=>{Q&&we(),K?te(K):be()})})}e.exports=Y,e.exports.finished=re}),Ft=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ke(),{Symbol:i}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=ht(),d=i("kDestroy"),f=i("kConstruct");function g(T,q,D){T&&(T.stack,q&&!q.errored&&(q.errored=T),D&&!D.errored&&(D.errored=T))}function h(T,q){let D=this._readableState,U=this._writableState,ae=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof q=="function"&&q(),this):(g(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),ae.constructed?b(this,T,q):this.once(d,function(Y){b(this,r(Y,T),q)}),this)}function b(T,q,D){let U=!1;function ae(Y){if(U)return;U=!0;let V=T._readableState,re=T._writableState;g(Y,re,V),re&&(re.closed=!0),V&&(V.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(q||null,ae)}catch(Y){ae(Y)}}function y(T,q){m(T,q),w(T)}function w(T){let q=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),q&&(q.closeEmitted=!0),(D!=null&&D.emitClose||q!=null&&q.emitClose)&&T.emit("close")}function m(T,q){let D=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||D!=null&&D.errorEmitted||(U&&(U.errorEmitted=!0),D&&(D.errorEmitted=!0),T.emit("error",q))}function k(){let T=this._readableState,q=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function x(T,q,D){let U=T._readableState,ae=T._writableState;if(ae!=null&&ae.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||ae!=null&&ae.autoDestroy?T.destroy(q):q&&(q.stack,ae&&!ae.errored&&(ae.errored=q),U&&!U.errored&&(U.errored=q),D?t.nextTick(m,T,q):m(T,q))}function v(T,q){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(f,q),!(T.listenerCount(f)>1)&&t.nextTick(E,T)}function E(T){let q=!1;function D(U){if(q){x(T,U??new o);return}q=!0;let ae=T._readableState,Y=T._writableState,V=Y||ae;ae&&(ae.constructed=!0),Y&&(Y.constructed=!0),V.destroyed?T.emit(d,U):U?x(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,U)}}function S(T){T.emit(f)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,q){T.emit("error",q),t.nextTick(P,T)}function j(T,q){!T||l(T)||(!q&&!c(T)&&(q=new n),u(T)?(T.socket=null,T.destroy(q)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(q):typeof T.close=="function"?T.close():q?t.nextTick(O,T,q):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:h,undestroy:k,errorOrDestroy:x}}),yi=pe((s,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:o}=(Ct(),Re(wt));function n(a){o.call(this,a)}r(n.prototype,o.prototype),r(n,o),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",h));let f=!1;function g(){f||(f=!0,a.end())}function h(){f||(f=!0,typeof a.destroy=="function"&&a.destroy())}function b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}i(c,"error",b),i(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",h),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function i(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:i}}),wr=pe((s,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:o}=Ke(),{isNodeStream:n,isWebStream:i,kControllerErrorFunction:a}=ht(),l=kt(),{ERR_INVALID_ARG_TYPE:c}=o,u,d=(f,g)=>{if(typeof f!="object"||!("aborted"in f))throw new c(g,"AbortSignal",f)};e.exports.addAbortSignal=function(f,g){if(d(f,"signal"),!n(g)&&!i(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(f,g)},e.exports.addAbortSignalNoValidate=function(f,g){if(typeof f!="object"||!("aborted"in f))return g;let h=n(g)?()=>{g.destroy(new r(void 0,{cause:f.reason}))}:()=>{g[a](new r(void 0,{cause:f.reason}))};if(f.aborted)h();else{u=u||Je().addAbortListener;let b=u(f,h);l(g,b[t])}return g}}),zc=pe((s,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Be(),{Buffer:i}=(Fe(),Re($e)),{inspect:a}=Je();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return i.alloc(0);let c=i.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)o(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let f=u.data;if(l>f.length)c+=f,l-=f.length;else{l===f.length?(c+=f,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(f,0,l),this.head=u,u.data=t(f,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=i.allocUnsafe(l),u=l,d=this.head,f=0;do{let g=d.data;if(l>g.length)o(c,g,u-l),l-=g.length;else{l===g.length?(o(c,g,u-l),++f,d.next?this.head=d.next:this.head=this.tail=null):(o(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++f}while((d=d.next)!==null);return this.length-=f,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),kr=pe((s,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:o}=nr(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,i=16*1024,a=16;function l(f,g,h){return f.highWaterMark!=null?f.highWaterMark:g?f[h]:null}function c(f){return f?a:i}function u(f,g){o(g,"value",0),f?a=g:i=g}function d(f,g,h,b){let y=l(g,b,h);if(y!=null){if(!r(y)||y<0){let w=b?`options.${h}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(f.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Vc=pe((s,e)=>{le(),ue(),ce();var t=(Fe(),Re($e)),r=t.Buffer;function o(i,a){for(var l in i)a[l]=i[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,s),s.Buffer=n);function n(i,a,l){return r(i,a,l)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(i,a,l){if(typeof i=="number")throw new TypeError("Argument must not be a number");return r(i,a,l)},n.alloc=function(i,a,l){if(typeof i!="number")throw new TypeError("Argument must be a number");var c=r(i);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return r(i)},n.allocUnsafeSlow=function(i){if(typeof i!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(i)}}),Kc=pe(s=>{le(),ue(),ce();var e=Vc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function o(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}s.StringDecoder=n;function n(m){this.encoding=o(m);var k;switch(this.encoding){case"utf16le":this.text=f,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=h,this.end=b,k=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function i(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,x){var v=k.length-1;if(v<x)return 0;var E=i(k[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=i(k[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=i(k[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function f(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function h(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-x))}function b(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),ps=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Be(),{Buffer:i}=(Fe(),Re($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,f){let g;if(typeof d=="string"||d instanceof i)return new u({objectMode:!0,...f,read(){this.push(d),this.push(null)}});let h;if(d&&d[o])h=!0,g=d[o]();else if(d&&d[n])h=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...f}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof g.throw=="function";if(x&&v){let{value:E,done:S}=await g.throw(k);if(await E,S)return}if(typeof g.return=="function"){let{value:E}=await g.return();await E}}async function m(){for(;;){try{let{value:k,done:x}=h?await g.next():g.next();if(x)b.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(k){b.destroy(k)}break}}return b}e.exports=c}),_r=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:i,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:f,SymbolAsyncIterator:g,Symbol:h}=Be();e.exports=se,se.ReadableState=ve;var{EventEmitter:b}=(Ct(),Re(wt)),{Stream:y,prependListener:w}=yi(),{Buffer:m}=(Fe(),Re($e)),{addAbortSignal:k}=wr(),x=kt(),v=Je().debuglog("stream",C=>{v=C}),E=zc(),S=Ft(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=kr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:q,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:ae}=Ke(),{validateObject:Y}=nr(),V=h("kPaused"),{StringDecoder:re}=Kc(),$=ps();c(se.prototype,y.prototype),c(se,y);var Z=()=>{},{errorOrDestroy:M}=S,Q=1,be=2,te=4,we=8,K=16,N=32,ne=64,W=128,G=256,J=512,ge=1024,oe=2048,R=4096,F=8192,ee=16384,he=32768,fe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(L){L?this.state|=C:this.state&=~C}}}a(ve.prototype,{objectMode:me(Q),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(K),sync:me(N),needReadable:me(ne),emittedReadable:me(W),readableListening:me(G),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(oe),autoDestroy:me(R),destroyed:me(F),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,L,ke){typeof ke!="boolean"&&(ke=L instanceof ft()),this.state=oe|R|K|N,C&&C.objectMode&&(this.state|=Q),ke&&C&&C.readableObjectMode&&(this.state|=Q),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[V]=null,C&&C.emitClose===!1&&(this.state&=~oe),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new re(C.encoding),this.encoding=C.encoding)}function se(C){if(!(this instanceof se))return new se(C);let L=this instanceof ft();this._readableState=new ve(C,this,L),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!L&&k(C.signal,this)),y.call(this,C),S.construct(this,()=>{this._readableState.needReadable&&z(this,this._readableState)})}se.prototype.destroy=S.destroy,se.prototype._undestroy=S.undestroy,se.prototype._destroy=function(C,L){L(C)},se.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},se.prototype[f]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new ae,this.destroy(C)),new u((L,ke)=>x(this,xe=>xe&&xe!==C?ke(xe):L(null)))},se.prototype.push=function(C,L){return Ce(this,C,L,!1)},se.prototype.unshift=function(C,L){return Ce(this,C,L,!0)};function Ce(C,L,ke,xe){v("readableAddChunk",L);let Se=C._readableState,De;if((Se.state&Q)===0&&(typeof L=="string"?(ke=ke||Se.defaultEncoding,Se.encoding!==ke&&(xe&&Se.encoding?L=m.from(L,ke).toString(Se.encoding):(L=m.from(L,ke),ke=""))):L instanceof m?ke="":y._isUint8Array(L)?(L=y._uint8ArrayToBuffer(L),ke=""):L!=null&&(De=new j("chunk",["string","Buffer","Uint8Array"],L))),De)M(C,De);else if(L===null)Se.state&=~we,X(C,Se);else if((Se.state&Q)!==0||L&&L.length>0)if(xe)if((Se.state&te)!==0)M(C,new U);else{if(Se.destroyed||Se.errored)return!1;p(C,Se,L,!0)}else if(Se.ended)M(C,new D);else{if(Se.destroyed||Se.errored)return!1;Se.state&=~we,Se.decoder&&!ke?(L=Se.decoder.write(L),Se.objectMode||L.length!==0?p(C,Se,L,!1):z(C,Se)):p(C,Se,L,!1)}else xe||(Se.state&=~we,z(C,Se));return!Se.ended&&(Se.length<Se.highWaterMark||Se.length===0)}function p(C,L,ke,xe){L.flowing&&L.length===0&&!L.sync&&C.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,C.emit("data",ke)):(L.length+=L.objectMode?1:ke.length,xe?L.buffer.unshift(ke):L.buffer.push(ke),(L.state&ne)!==0&&de(C)),z(C,L)}se.prototype.isPaused=function(){let C=this._readableState;return C[V]===!0||C.flowing===!1},se.prototype.setEncoding=function(C){let L=new re(C);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,xe="";for(let Se of ke)xe+=L.write(Se);return ke.clear(),xe!==""&&ke.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(C){if(C>_)throw new q("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,L){return C<=0||L.length===0&&L.ended?0:(L.state&Q)!==0?1:n(C)?L.flowing&&L.length?L.buffer.first().length:L.length:C<=L.length?C:L.ended?L.length:0}se.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=i(C,10));let L=this._readableState,ke=C;if(C>L.highWaterMark&&(L.highWaterMark=A(C)),C!==0&&(L.state&=~W),C===0&&L.needReadable&&((L.highWaterMark!==0?L.length>=L.highWaterMark:L.length>0)||L.ended))return v("read: emitReadable",L.length,L.ended),L.length===0&&L.ended?st(this):de(this),null;if(C=B(C,L),C===0&&L.ended)return L.length===0&&st(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-C<L.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),L.ended||L.reading||L.destroyed||L.errored||!L.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),L.state|=we|N,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(De){M(this,De)}L.state&=~N,L.reading||(C=B(ke,L))}let Se;return C>0?Se=Jt(C,L):Se=null,Se===null?(L.needReadable=L.length<=L.highWaterMark,C=0):(L.length-=C,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),ke!==C&&L.ended&&st(this)),Se!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Se)),Se};function X(C,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let ke=L.decoder.end();ke&&ke.length&&(L.buffer.push(ke),L.length+=L.objectMode?1:ke.length)}L.ended=!0,L.sync?de(C):(L.needReadable=!1,L.emittedReadable=!0,_e(C))}}function de(C){let L=C._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(_e,C))}function _e(C){let L=C._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(C.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,it(C)}function z(C,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,C,L))}function ie(C,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let ke=L.length;if(v("maybeReadMore read 0"),C.read(0),ke===L.length)break}L.readingMore=!1}se.prototype._read=function(C){throw new T("_read()")},se.prototype.pipe=function(C,L){let ke=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,L);let Se=(!L||L.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ge:Ut;xe.endEmitted?t.nextTick(Se):ke.once("end",Se),C.on("unpipe",De);function De(lt,yt){v("onunpipe"),lt===ke&&yt&&yt.hasUnpiped===!1&&(yt.hasUnpiped=!0,hr())}function Ge(){v("onend"),C.end()}let et,dr=!1;function hr(){v("cleanup"),C.removeListener("close",at),C.removeListener("finish",At),et&&C.removeListener("drain",et),C.removeListener("error",jt),C.removeListener("unpipe",De),ke.removeListener("end",Ge),ke.removeListener("end",Ut),ke.removeListener("data",rn),dr=!0,et&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&et()}function fr(){dr||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),ke.pause()),et||(et=Ee(ke,C),C.on("drain",et))}ke.on("data",rn);function rn(lt){v("ondata");let yt=C.write(lt);v("dest.write",yt),yt===!1&&fr()}function jt(lt){if(v("onerror",lt),Ut(),C.removeListener("error",jt),C.listenerCount("error")===0){let yt=C._writableState||C._readableState;yt&&!yt.errorEmitted?M(C,lt):C.emit("error",lt)}}w(C,"error",jt);function at(){C.removeListener("finish",At),Ut()}C.once("close",at);function At(){v("onfinish"),C.removeListener("close",at),Ut()}C.once("finish",At);function Ut(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?fr():xe.flowing||(v("pipe resume"),ke.resume()),C};function Ee(C,L){return function(){let ke=C._readableState;ke.awaitDrainWriters===L?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(L)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}se.prototype.unpipe=function(C){let L=this._readableState,ke={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!C){let Se=L.pipes;L.pipes=[],this.pause();for(let De=0;De<Se.length;De++)Se[De].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,C);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},se.prototype.on=function(C,L){let ke=y.prototype.on.call(this,C,L),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?de(this):xe.reading||t.nextTick(Te,this)),ke},se.prototype.addListener=se.prototype.on,se.prototype.removeListener=function(C,L){let ke=y.prototype.removeListener.call(this,C,L);return C==="readable"&&t.nextTick(Ae,this),ke},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(C){let L=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Ae,this),L};function Ae(C){let L=C._readableState;L.readableListening=C.listenerCount("readable")>0,L.resumeScheduled&&L[V]===!1?L.flowing=!0:C.listenerCount("data")>0?C.resume():L.readableListening||(L.flowing=null)}function Te(C){v("readable nexttick read 0"),C.read(0)}se.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Oe(this,C)),C[V]=!1,this};function Oe(C,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(nt,C,L))}function nt(C,L){v("resume",L.reading),L.reading||C.read(0),L.resumeScheduled=!1,C.emit("resume"),it(C),L.flowing&&!L.reading&&C.read(0)}se.prototype.pause=function(){return v("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(v("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[V]=!0,this};function it(C){let L=C._readableState;for(v("flow",L.flowing);L.flowing&&C.read()!==null;);}se.prototype.wrap=function(C){let L=!1;C.on("data",xe=>{!this.push(xe)&&C.pause&&(L=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{M(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&C.resume&&(L=!1,C.resume())};let ke=l(C);for(let xe=1;xe<ke.length;xe++){let Se=ke[xe];this[Se]===void 0&&typeof C[Se]=="function"&&(this[Se]=C[Se].bind(C))}return this},se.prototype[g]=function(){return Ve(this)},se.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ve(this,C)};function Ve(C,L){typeof C.read!="function"&&(C=se.wrap(C,{objectMode:!0}));let ke=ot(C,L);return ke.stream=C,ke}async function*ot(C,L){let ke=Z;function xe(Ge){this===C?(ke(),ke=Z):ke=Ge}C.on("readable",xe);let Se,De=x(C,{writable:!1},Ge=>{Se=Ge?O(Se,Ge):null,ke(),ke=Z});try{for(;;){let Ge=C.destroyed?null:C.read();if(Ge!==null)yield Ge;else{if(Se)throw Se;if(Se===null)return;await new u(xe)}}}catch(Ge){throw Se=O(Se,Ge),Se}finally{(Se||L?.destroyOnReturn!==!1)&&(Se===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",xe),De())}}a(se.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[V]!==!1},set(C){this[V]=!!C}}}),se._fromList=Jt;function Jt(C,L){if(L.length===0)return null;let ke;return L.objectMode?ke=L.buffer.shift():!C||C>=L.length?(L.decoder?ke=L.buffer.join(""):L.buffer.length===1?ke=L.buffer.first():ke=L.buffer.concat(L.length),L.buffer.clear()):ke=L.buffer.consume(C,L.decoder),ke}function st(C){let L=C._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ze,L,C))}function Ze(C,L){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(tn,L);else if(C.autoDestroy){let ke=L._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&L.destroy()}}}function tn(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}se.from=function(C,L){return $(se,C,L)};var Qt;function ur(){return Qt===void 0&&(Qt={}),Qt}se.fromWeb=function(C,L){return ur().newStreamReadableFromReadableStream(C,L)},se.toWeb=function(C,L){return ur().newReadableStreamFromStreamReadable(C,L)},se.wrap=function(C,L){var ke,xe;return new se({objectMode:(ke=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&ke!==void 0?ke:!0,...L,destroy(Se,De){S.destroyer(C,Se),De(Se)}}).wrap(C)}}),vi=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:i,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=U;var{EventEmitter:f}=(Ct(),Re(wt)),g=yi().Stream,{Buffer:h}=(Fe(),Re($e)),b=Ft(),{addAbortSignal:y}=wr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=kr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=b;l(Y.prototype,g.prototype),l(Y,g);function q(){}var D=u("kOnFinished");function U(R,F,ee){typeof ee!="boolean"&&(ee=F instanceof ft()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?w(this,R,"writableHighWaterMark",ee):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(R&&R.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=R&&R.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.bind(void 0,F),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,ae(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!R||R.emitClose!==!1,this.autoDestroy=!R||R.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[D]=[]}function ae(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},i(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let F=this instanceof ft();if(!F&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,F),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&y(R.signal,this)),g.call(this,R),b.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),W(this,ee)})}i(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new E)};function V(R,F,ee,he){let fe=R._writableState;if(typeof ee=="function")he=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!h.isEncoding(ee))throw new j(ee);typeof he!="function"&&(he=q)}if(F===null)throw new P;if(!fe.objectMode)if(typeof F=="string")fe.decodeStrings!==!1&&(F=h.from(F,ee),ee="buffer");else if(F instanceof h)ee="buffer";else if(g._isUint8Array(F))F=g._uint8ArrayToBuffer(F),ee="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],F);let ye;return fe.ending?ye=new O:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(he,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,F,ee,he))}Y.prototype.write=function(R,F,ee){return V(this,R,F,ee)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=c(R)),!h.isEncoding(R))throw new j(R);return this._writableState.defaultEncoding=R,this};function re(R,F,ee,he,fe){let ye=F.objectMode?1:ee.length;F.length+=ye;let H=F.length<F.highWaterMark;return H||(F.needDrain=!0),F.writing||F.corked||F.errored||!F.constructed?(F.buffered.push({chunk:ee,encoding:he,callback:fe}),F.allBuffers&&he!=="buffer"&&(F.allBuffers=!1),F.allNoop&&fe!==q&&(F.allNoop=!1)):(F.writelen=ye,F.writecb=fe,F.writing=!0,F.sync=!0,R._write(ee,he,F.onwrite),F.sync=!1),H&&!F.errored&&!F.destroyed}function $(R,F,ee,he,fe,ye,H){F.writelen=he,F.writecb=H,F.writing=!0,F.sync=!0,F.destroyed?F.onwrite(new S("write")):ee?R._writev(fe,F.onwrite):R._write(fe,ye,F.onwrite),F.sync=!1}function Z(R,F,ee,he){--F.pendingcb,he(ee),te(F),T(R,ee)}function M(R,F){let ee=R._writableState,he=ee.sync,fe=ee.writecb;if(typeof fe!="function"){T(R,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,F?(F.stack,ee.errored||(ee.errored=F),R._readableState&&!R._readableState.errored&&(R._readableState.errored=F),he?t.nextTick(Z,R,ee,F,fe):Z(R,ee,F,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),he?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(Q,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function Q({stream:R,state:F,count:ee,cb:he}){return F.afterWriteTickInfo=null,be(R,F,ee,he)}function be(R,F,ee,he){for(!F.ending&&!R.destroyed&&F.length===0&&F.needDrain&&(F.needDrain=!1,R.emit("drain"));ee-- >0;)F.pendingcb--,he();F.destroyed&&te(F),W(R,F)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var F;let{chunk:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H((F=R.errored)!==null&&F!==void 0?F:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=R.errored)!==null&&he!==void 0?he:new S("end"))}ae(R)}function we(R,F){if(F.corked||F.bufferProcessing||F.destroyed||!F.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=F,ye=ee.length-he;if(!ye)return;let H=he;if(F.bufferProcessing=!0,ye>1&&R._writev){F.pendingcb-=ye-1;let me=F.allNoop?q:se=>{for(let Ce=H;Ce<ee.length;++Ce)ee[Ce].callback(se)},ve=F.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=F.allBuffers,$(R,F,!0,F.length,ve,"",me),ae(F)}else{do{let{chunk:me,encoding:ve,callback:se}=ee[H];ee[H++]=null;let Ce=fe?1:me.length;$(R,F,!1,Ce,me,ve,se)}while(H<ee.length&&!F.writing);H===ee.length?ae(F):H>256?(ee.splice(0,H),F.bufferedIndex=0):F.bufferedIndex=H}F.bufferProcessing=!1}Y.prototype._write=function(R,F,ee){if(this._writev)this._writev([{chunk:R,encoding:F}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,F,ee){let he=this._writableState;typeof R=="function"?(ee=R,R=null,F=null):typeof F=="function"&&(ee=F,F=null);let fe;if(R!=null){let ye=V(this,R,F);ye instanceof o&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,W(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||he.finished?t.nextTick(ee,fe):he[D].push(ee)),this};function K(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function N(R,F){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,F.pendingcb--,fe){let ye=F[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,F.sync)}else K(F)&&(F.prefinished=!0,R.emit("prefinish"),F.pendingcb++,t.nextTick(G,R,F))}F.sync=!0,F.pendingcb++;try{R._final(he)}catch(fe){he(fe)}F.sync=!1}function ne(R,F){!F.prefinished&&!F.finalCalled&&(typeof R._final=="function"&&!F.destroyed?(F.finalCalled=!0,N(R,F)):(F.prefinished=!0,R.emit("prefinish")))}function W(R,F,ee){K(F)&&(ne(R,F),F.pendingcb===0&&(ee?(F.pendingcb++,t.nextTick((he,fe)=>{K(fe)?G(he,fe):fe.pendingcb--},R,F)):K(F)&&(F.pendingcb++,G(R,F))))}function G(R,F){F.pendingcb--,F.finished=!0;let ee=F[D].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(R.emit("finish"),F.autoDestroy){let he=R._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&R.destroy()}}a(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var J=b.destroy;Y.prototype.destroy=function(R,F){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,F),this},Y.prototype._undestroy=b.undestroy,Y.prototype._destroy=function(R,F){F(R)},Y.prototype[f.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function oe(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,F){return oe().newStreamWritableFromWritableStream(R,F)},Y.toWeb=function(R){return oe().newWritableStreamFromStreamWritable(R)}}),Gc=pe((s,e)=>{le(),ue(),ce();var t=Pt(),r=(Fe(),Re($e)),{isReadable:o,isWritable:n,isIterable:i,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:f}=ht(),g=kt(),{AbortError:h,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Ft(),m=ft(),k=_r(),x=vi(),{createDeferredPromise:v}=Je(),E=ps(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},P=globalThis.AbortController||tr().AbortController,{FunctionPrototypeCall:O}=Be(),j=class extends m{constructor(D){super(D),D?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),D?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function D(U,ae){if(u(U))return U;if(l(U))return q({readable:U});if(c(U))return q({writable:U});if(a(U))return q({writable:!1,readable:!1});if(d(U))return q({readable:k.fromWeb(U)});if(f(U))return q({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:V,write:re,final:$,destroy:Z}=T(U);if(i(V))return E(j,V,{objectMode:!0,write:re,final:$,destroy:Z});let M=V?.then;if(typeof M=="function"){let Q,be=O(M,V,te=>{if(te!=null)throw new y("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){$(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new y("Iterable, AsyncIterable or AsyncFunction",ae,V)}if(I(U))return D(U.arrayBuffer());if(i(U))return E(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&f(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let V=U!=null&&U.readable?l(U?.readable)?U?.readable:D(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:D(U.writable):void 0;return q({readable:V,writable:re})}let Y=U?.then;if(typeof Y=="function"){let V;return O(Y,U,re=>{re!=null&&V.push(re),V.push(null)},re=>{w(V,re)}),V=new j({objectMode:!0,writable:!1,read(){}})}throw new b(ae,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:ae}=v(),Y=new P,V=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:$,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(V.aborted)throw new h(void 0,{cause:V.reason});({promise:U,resolve:ae}=v()),yield $}})(),{signal:V}),write(re,$,Z){let M=ae;ae=null,M({chunk:re,done:!1,cb:Z})},final(re){let $=ae;ae=null,$({done:!0,cb:re})},destroy(re,$){Y.abort(),$(re)}}}function q(D){let U=D.readable&&typeof D.readable.read!="function"?k.wrap(D.readable):D.readable,ae=D.writable,Y=!!o(U),V=!!n(ae),re,$,Z,M,Q;function be(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(ae!=null&&ae.writableObjectMode),readable:Y,writable:V}),V&&(g(ae,te=>{V=!1,te&&w(U,te),be(te)}),Q._write=function(te,we,K){ae.write(te,we)?K():re=K},Q._final=function(te){ae.end(),$=te},ae.on("drain",function(){if(re){let te=re;re=null,te()}}),ae.on("finish",function(){if($){let te=$;$=null,te()}})),Y&&(g(U,te=>{Y=!1,te&&w(U,te),be(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){Q.push(null)}),Q._read=function(){for(;;){let te=U.read();if(te===null){Z=Q._read;return}if(!Q.push(te))return}}),Q._destroy=function(te,we){!te&&M!==null&&(te=new h),Z=null,re=null,$=null,M===null?we(te):(M=we,w(ae,te),w(U,te))},Q}}),ft=pe((s,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=Be();e.exports=l;var i=_r(),a=vi();n(l.prototype,i.prototype),n(l,i);{let f=o(a.prototype);for(let g=0;g<f.length;g++){let h=f[g];l.prototype[h]||(l.prototype[h]=a.prototype[h])}}function l(f){if(!(this instanceof l))return new l(f);i.call(this,f),a.call(this,f),f?(this.allowHalfOpen=f.allowHalfOpen!==!1,f.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),f.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(f){this._readableState&&this._writableState&&(this._readableState.destroyed=f,this._writableState.destroyed=f)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(f,g){return u().newStreamDuplexFromReadableWritablePair(f,g)},l.toWeb=function(f){return u().newReadableWritablePairFromDuplex(f)};var d;l.from=function(f){return d||(d=Gc()),d(f,"body")}}),ms=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ke().codes,n=ft(),{getHighWaterMark:i}=kr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let f=d?i(this,d,"readableHighWaterMark",!0):null;f===0&&(d={...d,highWaterMark:null,readableHighWaterMark:f,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((f,g)=>{if(f){d?d(f):this.destroy(f);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,f,g){throw new o("_transform()")},l.prototype._write=function(d,f,g){let h=this._readableState,b=this._writableState,y=h.length;this._transform(d,f,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===h.length||h.length<h.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),gs=pe((s,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=o;var r=ms();t(o.prototype,r.prototype),t(o,r);function o(n){if(!(this instanceof o))return new o(n);r.call(this,n)}o.prototype._transform=function(n,i,a){a(null,n)}}),wi=pe((s,e)=>{le(),ue(),ce();var t=Pt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:i}=Be(),a=kt(),{once:l}=Je(),c=Ft(),u=ft(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:f,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:h,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:k}=nr(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:j}=ht(),T=globalThis.AbortController||tr().AbortController,q,D,U;function ae(te,we,K){let N=!1;te.on("close",()=>{N=!0});let ne=a(te,{readable:we,writable:K},W=>{N=!W});return{destroy:W=>{N||(N=!0,c.destroyer(te,W||new b("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function V(te){if(x(te))return te;if(E(te))return re(te);throw new f("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=_r()),yield*D.prototype[n].call(te)}async function $(te,we,K,{end:N}){let ne,W=null,G=oe=>{if(oe&&(ne=oe),W){let R=W;W=null,R()}},J=()=>new o((oe,R)=>{ne?R(ne):W=()=>{ne?R(ne):oe()}});we.on("drain",G);let ge=a(we,{readable:!1},G);try{we.writableNeedDrain&&await J();for await(let oe of te)we.write(oe)||await J();N&&(we.end(),await J()),K()}catch(oe){K(ne!==oe?d(ne,oe):oe)}finally{ge(),we.off("drain",G)}}async function Z(te,we,K,{end:N}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let W of te)await ne.ready,ne.write(W).catch(()=>{});await ne.ready,N&&await ne.close(),K()}catch(W){try{await ne.abort(W),K(W)}catch(G){K(G)}}}function M(...te){return Q(te,l(Y(te)))}function Q(te,we,K){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new h("streams");let N=new T,ne=N.signal,W=K?.signal,G=[];k(W,"options.signal");function J(){fe(new w)}U=U||Je().addAbortListener;let ge;W&&(ge=U(W,J));let oe,R,F=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,se){var Ce;if(ve&&(!oe||oe.code==="ERR_STREAM_PREMATURE_CLOSE")&&(oe=ve),!(!oe&&!se)){for(;F.length;)F.shift()(oe);(Ce=ge)===null||Ce===void 0||Ce[i](),N.abort(),se&&(oe||G.forEach(p=>p()),t.nextTick(we,oe,R))}}let ye;for(let ve=0;ve<te.length;ve++){let se=te[ve],Ce=ve<te.length-1,p=ve>0,_=Ce||K?.end!==!1,A=ve===te.length-1;if(S(se)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(_){let{destroy:X,cleanup:de}=ae(se,Ce,p);F.push(X),v(se)&&A&&G.push(de)}se.on("error",B),v(se)&&A&&G.push(()=>{se.removeListener("error",B)})}if(ve===0)if(typeof se=="function"){if(ye=se({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(se)||E(se)||I(se)?ye=se:ye=u.from(se);else if(typeof se=="function"){if(I(ye)){var H;ye=V((H=ye)===null||H===void 0?void 0:H.readable)}else ye=V(ye);if(ye=se(ye,{signal:ne}),Ce){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;q||(q=gs());let B=new q({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,z=>{R=z,z!=null&&B.write(z),_&&B.end(),t.nextTick(he)},z=>{B.destroy(z),t.nextTick(he,z)});else if(x(ye,!0))ee++,$(ye,B,he,{end:_});else if(O(ye)||I(ye)){let z=ye.readable||ye;ee++,$(z,B,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:_e}=ae(ye,!1,!0);F.push(de),A&&G.push(_e)}}else if(S(se)){if(E(ye)){ee+=2;let B=be(ye,se,he,{end:_});v(se)&&A&&G.push(B)}else if(I(ye)||O(ye)){let B=ye.readable||ye;ee++,$(B,se,he,{end:_})}else if(x(ye))ee++,$(ye,se,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else if(P(se)){if(E(ye))ee++,Z(V(ye),se,he,{end:_});else if(O(ye)||x(ye))ee++,Z(ye,se,he,{end:_});else if(I(ye))ee++,Z(ye.readable,se,he,{end:_});else throw new f("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=se}else ye=u.from(se)}return(ne!=null&&ne.aborted||W!=null&&W.aborted)&&t.nextTick(J),ye}function be(te,we,K,{end:N}){let ne=!1;if(we.on("close",()=>{ne||K(new y)}),te.pipe(we,{end:!1}),N){let W=function(){ne=!0,we.end()};j(te)?t.nextTick(W):te.once("end",W)}else K();return a(te,{readable:!0,writable:!1},W=>{let G=te._readableState;W&&W.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",K).once("error",K):K(W)}),a(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:Q,pipeline:M}}),bs=pe((s,e)=>{le(),ue(),ce();var{pipeline:t}=wi(),r=ft(),{destroyer:o}=Ft(),{isNodeStream:n,isReadable:i,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=ht(),{AbortError:f,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:h}}=Ke(),b=kt();e.exports=function(...y){if(y.length===0)throw new h("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(i(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,x,v,E;function S(T){let q=v;v=null,q?q(T):T?E.destroy(T):!j&&!O&&E.destroy()}let I=y[0],P=t(y,S),O=!!(a(I)||u(I)||c(I)),j=!!(i(P)||d(P)||c(P));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:j}),O){if(n(I))E._write=function(q,D,U){I.write(q,D)?U():m=U},E._final=function(q){I.end(),k=q},I.on("drain",function(){if(m){let q=m;m=null,q()}});else if(l(I)){let q=(c(I)?I.writable:I).getWriter();E._write=async function(D,U,ae){try{await q.ready,q.write(D).catch(()=>{}),ae()}catch(Y){ae(Y)}},E._final=async function(D){try{await q.ready,q.close().catch(()=>{}),k=D}catch(U){D(U)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let q=k;k=null,q()}})}if(j){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=P.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();E._read=async function(){for(;;)try{let{value:q,done:D}=await T.read();if(!E.push(q))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,q){!T&&v!==null&&(T=new f),x=null,m=null,k=null,v===null?q(T):(v=q,n(P)&&o(P,T))},E}}),Yc=pe((s,e)=>{le(),ue(),ce();var t=globalThis.AbortController||tr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:i},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=nr(),d=Be().Symbol("kWeak"),f=Be().Symbol("kResistStopPropagation"),{finished:g}=kt(),h=bs(),{addAbortSignalNoValidate:b}=wr(),{isWritable:y,isNodeStream:w}=ht(),{deprecate:m}=Je(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=Be(),q=T("kEmpty"),D=T("kEof");function U(W,G){if(G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),w(W)&&!y(W))throw new r("stream",W,"must be writable");let J=h(this,W);return G!=null&&G.signal&&b(G.signal,J),J}function ae(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal");let J=1;G?.concurrency!=null&&(J=v(G.concurrency));let ge=J-1;return G?.highWaterMark!=null&&(ge=v(G.highWaterMark)),c(J,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=J,(async function*(){let oe=Je().AbortSignalAny([G?.signal].filter(x)),R=this,F=[],ee={signal:oe},he,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,se()}function se(){fe&&!ye&&H<J&&F.length<ge&&(fe(),fe=null)}async function Ce(){try{for await(let p of R){if(ye)return;if(oe.aborted)throw new a;try{if(p=W(p,ee),p===q)continue;p=O(p)}catch(_){p=P(_)}H+=1,j(p,ve,me),F.push(p),he&&(he(),he=null),!ye&&(F.length>=ge||H>=J)&&await new I(_=>{fe=_})}F.push(D)}catch(p){let _=P(p);j(_,ve,me),F.push(_)}finally{ye=!0,he&&(he(),he=null)}}Ce();try{for(;;){for(;F.length>0;){let p=await F[0];if(p===D)return;if(oe.aborted)throw new a;p!==q&&(yield p),F.shift(),se()}await new I(p=>{he=p})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(W=void 0){return W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal"),(async function*(){let G=0;for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new a({cause:W.signal.reason});yield[G++,ge]}}).call(this)}async function V(W,G=void 0){for await(let J of M.call(this,W,G))return!0;return!1}async function re(W,G=void 0){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);return!await V.call(this,async(...J)=>!await W(...J),G)}async function $(W,G){for await(let J of M.call(this,W,G))return J}async function Z(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe),q}for await(let ge of ae.call(this,J,G));}function M(W,G){if(typeof W!="function")throw new o("fn",["Function","AsyncFunction"],W);async function J(ge,oe){return await W(ge,oe)?ge:q}return ae.call(this,J,G)}var Q=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(W,G,J){var ge;if(typeof W!="function")throw new o("reducer",["Function","AsyncFunction"],W);J!=null&&u(J,"options"),J?.signal!=null&&l(J.signal,"options.signal");let oe=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new a(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let R=new t,F=R.signal;if(J!=null&&J.signal){let fe={once:!0,[d]:this,[f]:!0};J.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var he;if(ee=!0,J!=null&&(he=J.signal)!==null&&he!==void 0&&he.aborted)throw new a;oe?G=await W(G,fe,{signal:F}):(G=fe,oe=!0)}if(!ee&&!oe)throw new Q}finally{R.abort()}return G}async function te(W){W!=null&&u(W,"options"),W?.signal!=null&&l(W.signal,"options.signal");let G=[];for await(let ge of this){var J;if(W!=null&&(J=W.signal)!==null&&J!==void 0&&J.aborted)throw new a(void 0,{cause:W.signal.reason});k(G,ge)}return G}function we(W,G){let J=ae.call(this,W,G);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function K(W){if(W=E(W),S(W))return 0;if(W<0)throw new i("number",">= 0",W);return W}function N(W,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),W=K(W),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;W--<=0&&(yield oe)}}).call(this)}function ne(W,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),W=K(W),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let oe of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;if(W-- >0&&(yield oe),W<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:N,filter:M,flatMap:we,map:ae,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:V,find:$}}),ys=pe((s,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:o,isNodeStream:n,isWebStream:i}=ht(),{pipelineImpl:a}=wi(),{finished:l}=kt();vs();function c(...u){return new r((d,f)=>{let g,h,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!i(b)){let y=t(u);g=y.signal,h=y.end}a(u,(y,w)=>{y?f(y):d(w)},{signal:g,end:h})})}e.exports={finished:l,pipeline:c}}),vs=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Be(),{promisify:{custom:i}}=Je(),{streamReturningOperators:a,promiseReturningOperators:l}=Yc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=bs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:f}=kr(),{pipeline:g}=wi(),{destroyer:h}=Ft(),b=kt(),y=ys(),w=ht(),m=e.exports=yi().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=_r();for(let x of o(a)){let v=function(...S){if(new.target)throw c();return m.Readable.from(n(E,this,S))},E=a[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of o(l)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=l[x];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=vi(),m.Duplex=ft(),m.Transform=ms(),m.PassThrough=gs(),m.pipeline=g;var{addAbortSignal:k}=wr();m.addAbortSignal=k,m.finished=b,m.destroy=h,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=f,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,i,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,i,{__proto__:null,enumerable:!0,get(){return y.finished}}),m.Stream=m,m._isUint8Array=function(x){return x instanceof Uint8Array},m._uint8ArrayToBuffer=function(x){return t.from(x.buffer,x.byteOffset,x.byteLength)}}),Ot=pe((s,e)=>{le(),ue(),ce();var t=vs(),r=ys(),o=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=o,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),Jc=pe((s,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var o=function(){};o.prototype=r.prototype,t.prototype=new o,t.prototype.constructor=t}}}),Qc=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),r=Symbol.for("BufferList");function o(n){if(!(this instanceof o))return new o(n);o._init.call(this,n)}o._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},o.prototype._new=function(n){return new o(n)},o.prototype._offset=function(n){if(n===0)return[0,0];let i=0;for(let a=0;a<this._bufs.length;a++){let l=i+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-i];i=l}},o.prototype._reverseOffset=function(n){let i=n[0],a=n[1];for(let l=0;l<i;l++)a+=this._bufs[l].length;return a},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(n){if(n>this.length||n<0)return;let i=this._offset(n);return this._bufs[i[0]][i[1]]},o.prototype.slice=function(n,i){return typeof n=="number"&&n<0&&(n+=this.length),typeof i=="number"&&i<0&&(i+=this.length),this.copy(null,0,n,i)},o.prototype.copy=function(n,i,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,f=d,g=c&&i||0,h=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(f<=this._bufs[u[0]].length-h)return c?this._bufs[u[0]].copy(n,i,h,h+f):this._bufs[u[0]].slice(h,h+f);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-h;if(f>y)this._bufs[b].copy(n,g,h),g+=y;else{this._bufs[b].copy(n,g,h,h+f),g+=y;break}f-=y,h&&(h=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,i){if(n=n||0,i=typeof i!="number"?this.length:i,n<0&&(n+=this.length),i<0&&(i+=this.length),n===i)return this._new();let a=this._offset(n),l=this._offset(i),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},o.prototype.toString=function(n,i,a){return this.slice(i,a).toString(n)},o.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},o.prototype.duplicate=function(){let n=this._new();for(let i=0;i<this._bufs.length;i++)n.append(this._bufs[i]);return n},o.prototype.append=function(n){return this._attach(n,o.prototype._appendBuffer)},o.prototype.prepend=function(n){return this._attach(n,o.prototype._prependBuffer,!0)},o.prototype._attach=function(n,i,a){if(n==null)return this;if(n.buffer)i.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],i,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],i,a)}else typeof n=="number"&&(n=n.toString()),i.call(this,t.from(n));return this},o.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},o.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},o.prototype.indexOf=function(n,i,a){if(a===void 0&&typeof i=="string"&&(a=i,i=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),i=Number(i||0),isNaN(i)&&(i=0),i<0&&(i=this.length+i),i<0&&(i=0),n.length===0)return i>this.length?this.length:i;let l=this._offset(i),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let f=d.indexOf(n,u);if(f!==-1)return this._reverseOffset([c,f]);u=d.length-n.length+1}else{let f=this._reverseOffset([c,u]);if(this._match(f,n))return f;u++}u=0}return-1},o.prototype._match=function(n,i){if(this.length-n<i.length)return!1;for(let a=0;a<i.length;a++)if(this.get(n+a)!==i[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let i in n)(function(a){n[a]===null?o.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:o.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(i)})(),o.prototype._isBufferList=function(n){return n instanceof o||o.isBufferList(n)},o.isBufferList=function(n){return n!=null&&n[r]},e.exports=o}),Xc=pe((s,e)=>{le(),ue(),ce();var t=Ot().Duplex,r=Jc(),o=Qc();function n(i){if(!(this instanceof n))return new n(i);if(typeof i=="function"){this._callback=i;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),i=null}o._init.call(this,i),t.call(this)}r(n,t),Object.assign(n.prototype,o.prototype),n.prototype._new=function(i){return new n(i)},n.prototype._write=function(i,a,l){this._appendBuffer(i),typeof l=="function"&&l()},n.prototype._read=function(i){if(!this.length)return this.push(null);i=Math.min(i,this.length),this.push(this.slice(0,i)),this.consume(i)},n.prototype.end=function(i){t.prototype.end.call(this,i),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(i,a){this._bufs.length=0,this.length=0,a(i)},n.prototype._isBufferList=function(i){return i instanceof n||i instanceof o||n.isBufferList(i)},n.isBufferList=o.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=o}),Zc=pe((s,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),ws=pe((s,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(Fe(),Re($e));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let i=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+i.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let i=t.types[n];t.codes[i]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let i=t.properties[n];t.propertiesCodes[i]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function o(n){return[0,1,2].map(i=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|i<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=o("publish"),t.SUBSCRIBE_HEADER=o("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=o("unsubscribe"),t.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),eu=pe((s,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,i=n*7,a=n*365.25;e.exports=function(f,g){g=g||{};var h=typeof f;if(h==="string"&&f.length>0)return l(f);if(h==="number"&&isFinite(f))return g.long?u(f):c(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function l(f){if(f=String(f),!(f.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(g){var h=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return h*a;case"weeks":case"week":case"w":return h*i;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*o;case"minutes":case"minute":case"mins":case"min":case"m":return h*r;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function c(f){var g=Math.abs(f);return g>=n?Math.round(f/n)+"d":g>=o?Math.round(f/o)+"h":g>=r?Math.round(f/r)+"m":g>=t?Math.round(f/t)+"s":f+"ms"}function u(f){var g=Math.abs(f);return g>=n?d(f,g,n,"day"):g>=o?d(f,g,o,"hour"):g>=r?d(f,g,r,"minute"):g>=t?d(f,g,t,"second"):f+" ms"}function d(f,g,h,b){var y=g>=h*1.5;return Math.round(f/h)+" "+b+(y?"s":"")}}),tu=pe((s,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=eu(),n.destroy=f,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let h=0;for(let b=0;b<g.length;b++)h=(h<<5)-h+g.charCodeAt(b),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=o;function n(g){let h,b=null,y,w;function m(...k){if(!m.enabled)return;let x=m,v=Number(new Date),E=v-(h||v);x.diff=E,x.prev=h,x.curr=v,h=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let S=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";S++;let O=n.formatters[P];if(typeof O=="function"){let j=k[S];I=O.call(x,j),k.splice(S,1),S--}return I}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=i,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:k=>{b=k}}),typeof n.init=="function"&&n.init(m),m}function i(g,h){let b=n(this.namespace+(typeof h>"u"?":":h)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let h=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of h)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,h){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<h.length&&(h[y]===g[b]||h[y]==="*"))h[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function c(){let g=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),g}function u(g){for(let h of n.skips)if(l(g,h))return!1;for(let h of n.names)if(l(g,h))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),pt=pe((s,e)=>{le(),ue(),ce(),s.formatArgs=r,s.save=o,s.load=n,s.useColors=t,s.storage=i(),s.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),s.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(u++,f==="%c"&&(d=u))}),l.splice(d,0,c)}s.log=console.debug||console.log||(()=>{});function o(l){try{l?s.storage.setItem("debug",l):s.storage.removeItem("debug")}catch{}}function n(){let l;try{l=s.storage.getItem("debug")||s.storage.getItem("DEBUG")}catch{}return!l&&typeof Ne<"u"&&"env"in Ne&&(l=Ne.env.DEBUG),l}function i(){try{return localStorage}catch{}}e.exports=tu()(s);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),ru=pe((s,e)=>{le(),ue(),ce();var t=Xc(),{EventEmitter:r}=(Ct(),Re(wt)),o=Zc(),n=ws(),i=pt()("mqtt-packet:parser"),a=class No extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof No?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new No().parser(c)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),i("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=c&15,f=n.requiredHeaderFlags[u];return f!=null&&d!==f?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),i("_parseLength %d",c.value),!!c}_parsePayload(){i("_parsePayload: payload %O",this._list);let c=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}c=!0}return i("_parsePayload complete result: %s",c),c}_parseConnect(){i("_parseConnect");let c,u,d,f,g={},h=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(h.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(h.protocolVersion=this._list.readUInt8(this._pos),h.protocolVersion>=128&&(h.bridgeMode=!0,h.protocolVersion=h.protocolVersion-128),h.protocolVersion!==3&&h.protocolVersion!==4&&h.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let y=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)h.will={},h.will.retain=y,h.will.qos=w;else{if(y)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(h.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,h.keepalive=this._parseNum(),h.keepalive===-1)return this._emitError(new Error("Packet too short"));if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(h.clientId=m,i("_parseConnect: packet.clientId: %s",h.clientId),g.will){if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(h.will.topic=c,i("_parseConnect: packet.will.topic: %s",h.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));h.will.payload=u,i("_parseConnect: packet.will.paylaod: %s",h.will.payload)}if(g.username){if(f=this._parseString(),f===null)return this._emitError(new Error("Cannot parse username"));h.username=f,i("_parseConnect: packet.username: %s",h.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));h.password=d}return this.settings=h,i("_parseConnect: complete"),h}_parseConnack(){i("_parseConnack");let c=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),i("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){i("_parseSubscribe");let c=this.packet,u,d,f,g,h,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(f=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,f>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(b=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,h=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:f},this.settings.protocolVersion===5?(y.nl=b,y.rap=h,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){i("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){i("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){i("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}i("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(i("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),i("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let f=this._list.toString("utf8",this._pos,d);return this._pos+=u,i("_parseString: result: %s",f),f}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=c,i("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){i("_parseVarByteNum");let u=4,d=0,f=1,g=0,h=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=f*(b&n.VARBYTEINT_MASK),f*=128,(b&n.VARBYTEINT_FIN_MASK)===0){h=!0;break}if(this._list.length<=d)break}return!h&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),h?c?h={bytes:d,value:g}:h=g:h=!1,i("_parseVarByteNum: result: %o",h),h}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",c),c}_parseByType(c){switch(i("_parseByType: type: %s",c),c){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let f=this._parseByte();if(!f)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[f];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let h=this._parseByType(n.propertiesTypes[g]);if(d[g][h.name])if(Array.isArray(d[g][h.name]))d[g][h.name].push(h.value);else{let b=d[g][h.name];d[g][h.name]=[b],d[g][h.name].push(h.value)}else d[g][h.name]=h.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(c){i("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),nu=pe((s,e)=>{le(),ue(),ce();var{Buffer:t}=(Fe(),Re($e)),r=65536,o={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function i(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)o[u]=i(u)}function l(u){let d=0,f=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,f++);while(u>0&&f<4);return u>0&&(f=0),n?g.subarray(0,f):g.slice(0,f)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:o,generateCache:a,generateNumber:i,genBufVariableByteInt:l,generate4ByteBuffer:c}}),iu=pe((s,e)=>{le(),ue(),ce(),typeof Ne>"u"||!Ne.version||Ne.version.indexOf("v0.")===0||Ne.version.indexOf("v1.")===0&&Ne.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Ne;function t(r,o,n,i){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return Ne.nextTick(r);case 2:return Ne.nextTick(function(){r.call(null,o)});case 3:return Ne.nextTick(function(){r.call(null,o,n)});case 4:return Ne.nextTick(function(){r.call(null,o,n,i)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return Ne.nextTick(function(){r.apply(null,l)})}}}),ks=pe((s,e)=>{le(),ue(),ce();var t=ws(),{Buffer:r}=(Fe(),Re($e)),o=r.allocUnsafe(0),n=r.from([0]),i=nu(),a=iu().nextTick,l=pt()("mqtt-packet:writeToStream"),c=i.cache,u=i.generateNumber,d=i.generateCache,f=i.genBufVariableByteInt,g=i.generate4ByteBuffer,h=Y,b=!0;function y(K,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),b&&(b=!1,d()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,N);case"connack":return k(K,N,ne);case"publish":return x(K,N,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(K,N,ne);case"subscribe":return E(K,N,ne);case"suback":return S(K,N,ne);case"unsubscribe":return I(K,N,ne);case"unsuback":return P(K,N,ne);case"pingreq":case"pingresp":return O(K,N);case"disconnect":return j(K,N,ne);case"auth":return T(K,N,ne);default:return N.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return h===Y},set(K){K?((!c||Object.keys(c).length===0)&&(b=!0),h=Y):(b=!1,h=V)}});function w(K){K.uncork()}function m(K,N,ne){let W=K||{},G=W.protocolId||"MQTT",J=W.protocolVersion||4,ge=W.will,oe=W.clean,R=W.keepalive||0,F=W.clientId||"",ee=W.username,he=W.password,fe=W.properties;oe===void 0&&(oe=!0);let ye=0;if(typeof G!="string"&&!r.isBuffer(G))return N.destroy(new Error("Invalid protocolId")),!1;if(ye+=G.length+2,J!==3&&J!==4&&J!==5)return N.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof F=="string"||r.isBuffer(F))&&(F||J>=4)&&(F||oe))ye+=r.byteLength(F)+2;else{if(J<4)return N.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(oe*1===0)return N.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return N.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(J===5){if(H=Z(N,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return N.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return N.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return N.destroy(new Error("Invalid will payload")),!1;if(me={},J===5){if(me=Z(N,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return N.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return N.destroy(new Error("Username is required to use password")),!1;if(we(he))ye+=te(he)+2;else return N.destroy(new Error("Invalid password")),!1}N.write(t.CONNECT_HEADER),D(N,ye),$(N,G),W.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let se=0;return se|=ee!=null?t.USERNAME_MASK:0,se|=he!=null?t.PASSWORD_MASK:0,se|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,se|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,se|=ge?t.WILL_FLAG_MASK:0,se|=oe?t.CLEAN_SESSION_MASK:0,N.write(r.from([se])),h(N,R),J===5&&H.write(),$(N,F),ge&&(J===5&&me.write(),U(N,ge.topic),$(N,ge.payload)),ee!=null&&$(N,ee),he!=null&&$(N,he),!0}function k(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=W===5?G.reasonCode:G.returnCode,ge=G.properties,oe=2;if(typeof J!="number")return N.destroy(new Error("Invalid return code")),!1;let R=null;if(W===5){if(R=Z(N,ge),!R)return!1;oe+=R.length}return N.write(t.CONNACK_HEADER),D(N,oe),N.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),N.write(r.from([J])),R?.write(),!0}function x(K,N,ne){l("publish: packet: %o",K);let W=ne?ne.protocolVersion:4,G=K||{},J=G.qos||0,ge=G.retain?t.RETAIN_MASK:0,oe=G.topic,R=G.payload||o,F=G.messageId,ee=G.properties,he=0;if(typeof oe=="string")he+=r.byteLength(oe)+2;else if(r.isBuffer(oe))he+=oe.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof F!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(W===5){if(fe=Z(N,ee),!fe)return!1;he+=fe.length}return N.write(t.PUBLISH_HEADER[J][G.dup?1:0][ge?1:0]),D(N,he),h(N,te(oe)),N.write(oe),J>0&&h(N,F),fe?.write(),l("publish: payload: %o",R),N.write(R)}function v(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.cmd||"puback",ge=G.messageId,oe=G.dup&&J==="pubrel"?t.DUP_MASK:0,R=0,F=G.reasonCode,ee=G.properties,he=W===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(W===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][R][oe][0]),he===3&&(he+=F!==0?1:-1),D(N,he),h(N,ge),W===5&&he!==2&&N.write(r.from([F])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function E(K,N,ne){l("subscribe: packet: ");let W=ne?ne.protocolVersion:4,G=K||{},J=G.dup?t.DUP_MASK:0,ge=G.messageId,oe=G.subscriptions,R=G.properties,F=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;F+=2;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;F+=ee.length}if(typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){let ye=oe[fe].topic,H=oe[fe].qos;if(typeof ye!="string")return N.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return N.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(W===5){if(typeof(oe[fe].nl||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(oe[fe].rap||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=oe[fe].rh||0;if(typeof me!="number"||me>2)return N.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}F+=r.byteLength(ye)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(N,F),h(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of oe){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,se=fe.rh,Ce;U(N,ye),Ce=t.SUBSCRIBE_OPTIONS_QOS[H],W===5&&(Ce|=me?t.SUBSCRIBE_OPTIONS_NL:0,Ce|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Ce|=se?t.SUBSCRIBE_OPTIONS_RH[se]:0),he=N.write(r.from([Ce]))}return he}function S(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.granted,oe=G.properties,R=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return N.destroy(new Error("Invalid qos vector")),!1;R+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let F=null;if(W===5){if(F=M(N,oe,ne,R),!F)return!1;R+=F.length}return N.write(t.SUBACK_HEADER),D(N,R),h(N,J),F!==null&&F.write(),N.write(r.from(ge))}function I(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,oe=G.unsubscriptions,R=G.properties,F=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(F+=2,typeof oe=="object"&&oe.length)for(let fe=0;fe<oe.length;fe+=1){if(typeof oe[fe]!="string")return N.destroy(new Error("Invalid unsubscriptions")),!1;F+=r.byteLength(oe[fe])+2}else return N.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(W===5){if(ee=Z(N,R),!ee)return!1;F+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,F),h(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<oe.length;fe++)he=U(N,oe[fe]);return he}function P(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,oe=G.granted,R=G.properties,F=G.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(W===5)if(typeof oe=="object"&&oe.length)for(let ye=0;ye<oe.length;ye+=1){if(typeof oe[ye]!="number")return N.destroy(new Error("Invalid qos vector")),!1;he+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(W===5){if(fe=M(N,R,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[F][ee][ge][0]),D(N,he),h(N,J),fe!==null&&fe.write(),W===5&&N.write(r.from(oe)),!0}function O(K,N,ne){return N.write(t.EMPTY[K.cmd])}function j(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,oe=W===5?1:0,R=null;if(W===5){if(R=M(N,ge,ne,oe),!R)return!1;oe+=R.length}return N.write(r.from([t.codes.disconnect<<4])),D(N,oe),W===5&&N.write(r.from([J])),R!==null&&R.write(),!0}function T(K,N,ne){let W=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,oe=W===5?1:0;W!==5&&N.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(N,ge,ne,oe);return R?(oe+=R.length,N.write(r.from([t.codes.auth<<4])),D(N,oe),N.write(r.from([J])),R!==null&&R.write(),!0):!1}var q={};function D(K,N){if(N>t.VARBYTEINT_MAX)return K.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=q[N];return ne||(ne=f(N),N<16384&&(q[N]=ne)),l("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function U(K,N){let ne=r.byteLength(N);return h(K,ne),l("writeString: %s",N),K.write(N,"utf8")}function ae(K,N,ne){U(K,N),U(K,ne)}function Y(K,N){return l("writeNumberCached: number: %d",N),l("writeNumberCached: %o",c[N]),K.write(c[N])}function V(K,N){let ne=u(N);return l("writeNumberGenerated: %o",ne),K.write(ne)}function re(K,N){let ne=g(N);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,N){typeof N=="string"?U(K,N):N?(h(K,N.length),K.write(N)):h(K,0)}function Z(K,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){be(K,{},0)}};let ne=0;function W(G,J){let ge=t.propertiesTypes[G],oe=0;switch(ge){case"byte":{if(typeof J!="boolean")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=2;break}case"binary":{if(J&&J===null)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=1+r.byteLength(J)+2;break}case"int16":{if(typeof J!="number"||J<0||J>65535)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=1+r.byteLength(f(J));break}case"string":{if(typeof J!="string")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;oe+=Object.getOwnPropertyNames(J).reduce((R,F)=>{let ee=J[F];return Array.isArray(ee)?R+=ee.reduce((he,fe)=>(he+=3+r.byteLength(F.toString())+2+r.byteLength(fe.toString()),he),0):R+=3+r.byteLength(F.toString())+2+r.byteLength(J[F].toString()),R},0);break}default:return K.destroy(new Error(`Invalid property ${G}: ${J}`)),!1}return oe}if(N)for(let G in N){let J=0,ge=0,oe=N[G];if(oe!==void 0){if(Array.isArray(oe))for(let R=0;R<oe.length;R++){if(ge=W(G,oe[R]),!ge)return!1;J+=ge}else{if(ge=W(G,oe),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(f(ne))+ne,write(){be(K,N,ne)}}}function M(K,N,ne,W){let G=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(K,N);if(J)for(;W+ge.length>J;){let oe=G.shift();if(oe&&N[oe])delete N[oe],ge=Z(K,N);else return!1}return ge}function Q(K,N,ne){switch(t.propertiesTypes[N]){case"byte":{K.write(r.from([t.properties[N]])),K.write(r.from([+ne]));break}case"int8":{K.write(r.from([t.properties[N]])),K.write(r.from([ne]));break}case"binary":{K.write(r.from([t.properties[N]])),$(K,ne);break}case"int16":{K.write(r.from([t.properties[N]])),h(K,ne);break}case"int32":{K.write(r.from([t.properties[N]])),re(K,ne);break}case"var":{K.write(r.from([t.properties[N]])),D(K,ne);break}case"string":{K.write(r.from([t.properties[N]])),U(K,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(W=>{let G=ne[W];Array.isArray(G)?G.forEach(J=>{K.write(r.from([t.properties[N]])),ae(K,W.toString(),J.toString())}):(K.write(r.from([t.properties[N]])),ae(K,W.toString(),G.toString()))});break}default:return K.destroy(new Error(`Invalid property ${N} value: ${ne}`)),!1}}function be(K,N,ne){D(K,ne);for(let W in N)if(Object.prototype.hasOwnProperty.call(N,W)&&N[W]!=null){let G=N[W];if(Array.isArray(G))for(let J=0;J<G.length;J++)Q(K,W,G[J]);else Q(K,W,G)}}function te(K){return K?K instanceof r?K.length:r.byteLength(K):0}function we(K){return typeof K=="string"||K instanceof r}e.exports=y}),ou=pe((s,e)=>{le(),ue(),ce();var t=ks(),{EventEmitter:r}=(Ct(),Re(wt)),{Buffer:o}=(Fe(),Re($e));function n(a,l){let c=new i;return t(a,c,l),c.concat()}var i=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=o.byteLength(c[d]),a+=l[d];let f=o.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(f,u),u+=l[d]):(f.write(c[d],u),u+=l[d]);return f}destroy(a){a&&this.emit("error",a)}};e.exports=n}),su=pe(s=>{le(),ue(),ce(),s.parser=ru().parser,s.generate=ou(),s.writeToStream=ks()}),au=pe((s,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof vr?vr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return o(n);let i=new Map;if(i.set(Date,d=>new Date(d)),i.set(Map,(d,f)=>new Map(l(Array.from(d),f))),i.set(Set,(d,f)=>new Set(l(Array.from(d),f))),n.constructorHandlers)for(let d of n.constructorHandlers)i.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,f){let g=Object.keys(d),h=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?h[y]=w:w.constructor!==Object&&(a=i.get(w.constructor))?h[y]=a(w,f):ArrayBuffer.isView(w)?h[y]=t(w):h[y]=f(w)}return h}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=i.get(d.constructor)))return a(d,c);let f={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=i.get(h.constructor))?f[g]=a(h,c):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=c(h)}return f}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=i.get(d.constructor)))return a(d,u);let f={};for(let g in d){let h=d[g];typeof h!="object"||h===null?f[g]=h:h.constructor!==Object&&(a=i.get(h.constructor))?f[g]=a(h,u):ArrayBuffer.isView(h)?f[g]=t(h):f[g]=u(h)}return f}}function o(n){let i=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,h)=>new Map(u(Array.from(g),h))),l.set(Set,(g,h)=>new Set(u(Array.from(g),h))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?f:d;function u(g,h){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],k=g[m];if(typeof k!="object"||k===null)y[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))y[m]=c(k,h);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let x=i.indexOf(k);x!==-1?y[m]=a[x]:y[m]=h(k)}}return y}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let h={};i.push(g),a.push(h);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,d);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=i.indexOf(y);w!==-1?h[b]=a[w]:h[b]=d(y)}}return i.pop(),a.pop(),h}function f(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,f);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,f);let h={};i.push(g),a.push(h);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,f);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=i.indexOf(y);w!==-1?h[b]=a[w]:h[b]=f(y)}}return i.pop(),a.pop(),h}}}),lu=pe((s,e)=>{le(),ue(),ce(),e.exports=au()()}),_s=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.validateTopic=e,s.validateTopics=t;function e(r){let o=r.split("/");for(let n=0;n<o.length;n++)if(o[n]!=="+"){if(o[n]==="#")return n===o.length-1;if(o[n].indexOf("+")!==-1||o[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let o=0;o<r.length;o++)if(!e(r[o]))return r[o];return null}}),xs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Ot(),t={objectMode:!0},r={clean:!0},o=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,i){return this._inflights.set(n.messageId,n),i&&i(),this}createStream(){let n=new e.Readable(t),i=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{i.push(c)}),n._read=()=>{!a&&l<i.length?n.push(i[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,i){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),i(null,a)):i&&i(new Error("missing packet")),this}get(n,i){let a=this._inflights.get(n.messageId);return a?i(null,a):i&&i(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};s.default=o}),cu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,o,n)=>{r.log("handlePublish: packet %o",o),n=typeof n<"u"?n:r.noop;let i=o.topic.toString(),a=o.payload,{qos:l}=o,{messageId:c}=o,{options:u}=r;if(r.options.protocolVersion===5){let d;if(o.properties&&(d=o.properties.topicAlias),typeof d<"u")if(i.length===0)if(d>0&&d<=65535){let f=r.topicAliasRecv.getTopicByAlias(d);if(f)i=f,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(i,d))r.log("handlePublish :: registered topic: %s - alias: %d",i,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(i,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));f?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:f},n):r.incomingStore.put(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(i,a,o,(d,f)=>{if(typeof d=="number"&&(f=d,d=null),d)return r.emit("error",d);if(e.indexOf(f)===-1)return r.emit("error",new Error("Wrong reason code for puback"));f||r.emit("message",i,a,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:f},n)})});break}case 0:r.emit("message",i,a,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};s.default=t}),uu=pe((s,e)=>{e.exports={version:"5.15.0"}}),qt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.MQTTJS_VERSION=s.nextTick=s.ErrorWithSubackPacket=s.ErrorWithReasonCode=void 0,s.applyMixin=r;var e=class mc extends Error{code;constructor(n,i){super(n),this.code=i,Object.setPrototypeOf(this,mc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};s.ErrorWithReasonCode=e;var t=class gc extends Error{packet;constructor(n,i){super(n),this.packet=i,Object.setPrototypeOf(this,gc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};s.ErrorWithSubackPacket=t;function r(o,n,i=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(i||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}s.nextTick=typeof Ne?.nextTick=="function"?Ne.nextTick:o=>{setTimeout(o,0)},s.MQTTJS_VERSION=uu().version}),xr=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=void 0;var e=qt();s.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,o)=>{let{messageId:n}=o,i=o.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",i),i){case"pubcomp":case"puback":{let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${s.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=o.granted;for(let d=0;d<u.length;d++){let f=u[d];if((f&128)!==0){c=new Error(`Subscribe error: ${s.ReasonCodes[f]}`),c.code=f;let g=r.messageIdToTopic[n];g&&g.forEach(h=>{delete r._resubscribeTopics[h]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,o);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};s.default=t}),du=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=qt(),t=xr(),r=(o,n)=>{let{options:i}=o,a=i.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(l===24)o.reconnecting=!1,o._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",d)}})};s.default=r}),hu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Ne=="object"&&Ne?Ne:{},o=(g,h,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,h,b,y):console.error(`[${b}] ${h}: ${g}`)},n=globalThis.AbortController,i=globalThis.AbortSignal;if(typeof n>"u"){i=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){h()}signal=new i;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",h=()=>{g&&(g=!1,o("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",h))}}var a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class pr{heap;length;static#l=!1;static create(h){let b=c(h);if(!b)return[];pr.#l=!0;let y=new pr(h,b);return pr.#l=!1,y}constructor(h,b){if(!pr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(h),this.length=0}push(h){this.heap[this.length++]=h}pop(){return this.heap[--this.length]}},f=class bc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#f;#k;#A;#u;static unsafeExposeInternals(h){return{starts:h.#w,ttls:h.#f,sizes:h.#v,keyMap:h.#n,keyList:h.#r,valList:h.#e,next:h.#c,prev:h.#h,get head(){return h.#a},get tail(){return h.#o},free:h.#y,isBackgroundFetch:b=>h.#t(b),backgroundFetch:(b,y,w,m)=>h.#L(b,y,w,m),moveToTail:b=>h.#C(b),indexes:b=>h.#_(b),rindexes:b=>h.#x(b),isStale:b=>h.#p(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(h){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:q,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:ae,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:V,ignoreFetchAbort:re}=h;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let $=b?c(b):Array;if(!$)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=O,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!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(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=D,q!==void 0&&typeof q!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=q,this.#A=!!q,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new $(b),this.#h=new $(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!V,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!ae,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#d){let Z="LRU_CACHE_UNBOUNDED";a(Z)&&(t.add(Z),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,bc))}}getRemainingTTL(h){return this.#n.has(h)?1/0:0}#N(){let h=new u(this.#l),b=new u(this.#l);this.#f=h,this.#w=b,this.#j=(m,k,x=e.now())=>{if(b[m]=k!==0?x:0,h[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=h[m]!==0?e.now():0},this.#E=(m,k)=>{if(h[k]){let x=h[k],v=b[k];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let E=m.now-v;m.remainingTTL=x-E}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let k=setTimeout(()=>y=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=h[k],v=b[k];if(!x||!v)return 1/0;let E=(y||w())-v;return x-E},this.#p=m=>{let k=b[m],x=h[m];return!!x&&!!k&&(y||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#F(){let h=new u(this.#l);this.#b=0,this.#v=h,this.#T=b=>{this.#b-=h[b],h[b]=0},this.#U=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!l(w))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 w},this.#M=(b,y,w)=>{if(h[b]=y,this.#d){let m=this.#d-h[b];for(;this.#b>m;)this.#R(!0)}this.#b+=h[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=h=>{};#M=(h,b,y)=>{};#U=(h,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#B(b)||((h||!this.#p(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#B(b)||((h||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#B(h){return h!==void 0&&this.#n.get(this.#r[h])===h}*entries(){for(let h of this.#_())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*rentries(){for(let h of this.#x())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*keys(){for(let h of this.#_()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*rkeys(){for(let h of this.#x()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*values(){for(let h of this.#_())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}*rvalues(){for(let h of this.#x())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(h,b={}){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&h(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(h,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}rforEach(h,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}purgeStale(){let h=!1;for(let b of this.#x({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),h=!0);return h}info(h){let b=this.#n.get(h);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[b],x=this.#w[b];if(k&&x){let v=k-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let h=[];for(let b of this.#_({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let k={value:m};if(this.#f&&this.#w){k.ttl=this.#f[b];let x=e.now()-this.#w[b];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[b]),h.unshift([y,k])}return h}load(h){this.clear();for(let[b,y]of h){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(h,b,y={}){if(b===void 0)return this.delete(h),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#U(h,b,y.size||0,x);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(h,"set"),this;let I=this.#i===0?void 0:this.#n.get(h);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=h,this.#e[I]=b,this.#n.set(h,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#M(I,S,v),v&&(v.set="add"),E=!1;else{this.#C(I);let P=this.#e[I];if(b!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!k&&(this.#k&&this.#m?.(O,h,"set"),this.#u&&this.#s?.push([O,h,"set"]))}else k||(this.#k&&this.#m?.(P,h,"set"),this.#u&&this.#s?.push([P,h,"set"]));if(this.#T(I),this.#M(I,S,v),this.#e[I]=b,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(E||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.shift();)this.#g?.(...O)}return this}pop(){try{for(;this.#i;){let h=this.#e[this.#a];if(this.#R(!0),this.#t(h)){if(h.__staleWhileFetching)return h.__staleWhileFetching}else if(h!==void 0)return h}}finally{if(this.#u&&this.#s){let h=this.#s,b;for(;b=h?.shift();)this.#g?.(...b)}}}#R(h){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),h&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(h,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(h);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(h,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(h);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(h,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:x}=y;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},E=(T,q=!1)=>{let{aborted:D}=k.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!q?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!q)return I(k.signal.reason);let ae=O;return this.#e[b]===O&&(T===void 0?ae.__staleWhileFetching?this.#e[b]=ae.__staleWhileFetching:this.#S(h,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(h,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:q}=k.signal,D=q&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,ae=U||y.noDeleteOnFetchRejection,Y=O;if(this.#e[b]===O&&(!ae||Y.__staleWhileFetching===void 0?this.#S(h,"fetch"):D||(this.#e[b]=Y.__staleWhileFetching)),U)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},P=(T,q)=>{let D=this.#P?.(h,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),q),k.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let O=new Promise(P).then(E,S),j=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(h,j,{...v.options,status:void 0}),b=this.#n.get(h)):this.#e[b]=j,j}#t(h){if(!this.#A)return!1;let b=h;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:q=!1,status:D,signal:U}=b;if(!this.#A)return D&&(D.fetch="get"),this.get(h,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let ae={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:D,signal:U},Y=this.#n.get(h);if(Y===void 0){D&&(D.fetch="miss");let V=this.#L(h,Y,ae,T);return V.__returned=V}else{let V=this.#e[Y];if(this.#t(V)){let M=y&&V.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?V.__staleWhileFetching:V.__returned=V}let re=this.#p(Y);if(!q&&!re)return D&&(D.fetch="hit"),this.#C(Y),w&&this.#I(Y),D&&this.#E(D,Y),V;let $=this.#L(h,Y,ae,T),Z=$.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?$.__staleWhileFetching:$.__returned=$}}async forceFetch(h,b={}){let y=await this.fetch(h,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(h,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,x=this.get(h,k);if(!m&&x!==void 0)return x;let v=y(h,x,{options:k,context:w});return this.set(h,v,k),v}get(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,x=this.#n.get(h);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return k&&this.#E(k,x),this.#p(x)?(k&&(k.get="stale"),E?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(h,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#D(h,b){this.#h[b]=h,this.#c[h]=b}#C(h){h!==this.#o&&(h===this.#a?this.#a=this.#c[h]:this.#D(this.#h[h],this.#c[h]),this.#D(this.#o,h),this.#o=h)}delete(h){return this.#S(h,"delete")}#S(h,b){let y=!1;if(this.#i!==0){let w=this.#n.get(h);if(w!==void 0)if(y=!0,this.#i===1)this.#$(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,h,b),this.#u&&this.#s?.push([m,h,b])),this.#n.delete(h),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#$("delete")}#$(h){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#k&&this.#m?.(y,w,h),this.#u&&this.#s?.push([y,w,h])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#w&&(this.#f.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};s.LRUCache=f}),mt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.ContainerIterator=s.Container=s.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.o}};s.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};s.Base=t;var r=class extends t{};s.Container=r}),fu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.i=0,this.S=[]}push(o){return this.S.push(o),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;s.default=r}),pu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(i){n.push(i)})}clear(){this.q=[],this.i=this.j=0}push(o){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let i=this.i;for(let a=0;a<i;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=o}else this.q[this.j+this.i]=o;return++this.i}pop(){if(this.i===0)return;let o=this.q[this.j++];return this.i-=1,o}front(){if(this.i!==0)return this.q[this.j]}},r=t;s.default=r}),mu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Base{constructor(o=[],n=function(a,l){return a>l?-1:a<l?1:0},i=!0){if(super(),this.v=n,Array.isArray(o))this.C=i?[...o]:o;else{this.C=[];let l=this;o.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(o){let n=this.C[o];for(;o>0;){let i=o-1>>1,a=this.C[i];if(this.v(a,n)<=0)break;this.C[o]=a,o=i}this.C[o]=n}k(o,n){let i=this.C[o];for(;o<n;){let a=o<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,i)>=0)break;this.C[o]=c,o=a}this.C[o]=i}clear(){this.i=0,this.C.length=0}push(o){this.C.push(o),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let o=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),o}top(){return this.C[0]}find(o){return this.C.indexOf(o)>=0}remove(o){let n=this.C.indexOf(o);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(o){let n=this.C.indexOf(o);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;s.default=r}),ki=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=class extends e.Container{},r=t;s.default=r}),gt=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ss=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.RandomIterator=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(o,n){super(n),this.o=o,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(o){this.container.setElementByPos(this.o,o)}};s.RandomIterator=r}),gu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(ki()),t=Ss();function r(a){return a&&a.t?a:{default:a}}var o=class yc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new yc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new o(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},i=n;s.default=i}),bu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(ki()),t=mt(),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class vc extends t.ContainerIterator{constructor(c,u,d,f){super(f),this.o=c,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new vc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let f=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=f,f.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=i;s.default=a}),yu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=r(ki()),t=Ss();function r(a){return a&&a.t?a:{default:a}}var o=class wc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new wc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let f=0;f<this.P;++f)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(f){d.pushBack(f)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new o(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},i=n;s.default=i}),vu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.TreeNodeEnableIndex=s.TreeNode=void 0;var e=class{constructor(r,o){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=o}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let o=r.tt;for(;o.U===r;)r=o,o=r.tt;r=o}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let o=r.tt;for(;o.W===r;)r=o,o=r.tt;return r.W!==o?o:r}}te(){let r=this.tt,o=this.W,n=o.U;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.U=this,this.tt=o,this.W=n,n&&(n.tt=this),o}se(){let r=this.tt,o=this.U,n=o.W;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.W=this,this.tt=o,this.U=n,n&&(n.tt=this),o}};s.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};s.TreeNodeEnableIndex=t}),Es=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=vu(),t=mt(),r=gt(),o=class extends t.Container{constructor(i=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=i,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let f=d.tt;for(;f!==this.h;)f.rt+=1,f=f.tt;let g=this.he(d);if(g){let{parentNode:h,grandParent:b,curNode:y}=g;h.ie(),b.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(i,a){let l=this.h;for(;i;){let c=this.v(i.u,a);if(c<0)i=i.W;else if(c>0)l=i,i=i.U;else return i}return l}Z(i,a){let l=this.h;for(;i;)this.v(i.u,a)<=0?i=i.W:(l=i,i=i.U);return l}$(i,a){let l=this.h;for(;i;){let c=this.v(i.u,a);if(c<0)l=i,i=i.W;else if(c>0)i=i.U;else return i}return l}rr(i,a){let l=this.h;for(;i;)this.v(i.u,a)<0?(l=i,i=i.W):i=i.U;return l}ue(i){for(;;){let a=i.tt;if(a===this.h)return;if(i.ee===1){i.ee=0;return}if(i===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,i=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,i=a)}}}fe(i){if(this.i===1)return this.clear(),this.h;let a=i;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[i.u,a.u]=[a.u,i.u],[i.l,a.l]=[a.l,i.l],i=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(i,a){return i===void 0?!1:this.oe(i.U,a)||a(i)?!0:this.oe(i.W,a)}he(i){for(;;){let a=i.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,i=l;continue}else if(i===a.W){if(i.ee=0,i.U&&(i.U.tt=a),i.W&&(i.W.tt=l),a.W=i.U,l.U=i.W,i.U=a,i.W=l,l===this.Y)this.Y=i,this.h.tt=i;else{let u=l.tt;u.U===l?u.U=i:u.W=i}return i.tt=l.tt,a.tt=i,l.tt=i,l.ee=1,{parentNode:a,grandParent:l,curNode:i}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,i=l;continue}else if(i===a.U){if(i.ee=0,i.U&&(i.U.tt=l),i.W&&(i.W.tt=a),l.W=i.U,a.U=i.W,i.U=l,i.W=a,l===this.Y)this.Y=i,this.h.tt=i;else{let u=l.tt;u.U===l?u.U=i:u.W=i}return i.tt=l.tt,a.tt=i,l.tt=i,l.ee=1,{parentNode:a,grandParent:l,curNode:i}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(i,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(i,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,i);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(i,a),u.U.tt=u,c=u.U,this.h.U=c;else{let f=this.h.W,g=this.v(f.u,i);if(g===0){f.l=a;return}else if(g<0)f.W=new this.re(i,a),f.W.tt=f,c=f.W,this.h.W=c;else{if(l!==void 0){let h=l.o;if(h!==this.h){let b=this.v(h.u,i);if(b===0){h.l=a;return}else if(b>0){let y=h.L(),w=this.v(y.u,i);if(w===0){y.l=a;return}else w<0&&(c=new this.re(i,a),y.W===void 0?(y.W=c,c.tt=y):(h.U=c,c.tt=h))}}}if(c===void 0)for(c=this.Y;;){let h=this.v(c.u,i);if(h>0){if(c.U===void 0){c.U=new this.re(i,a),c.U.tt=c,c=c.U;break}c=c.U}else if(h<0){if(c.W===void 0){c.W=new this.re(i,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(i,a){for(;i;){let l=this.v(i.u,a);if(l<0)i=i.W;else if(l>0)i=i.U;else return i}return i||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(i,a){let l=i.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return i===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(i){if(this.i===0)return!1;let a=this.I(this.Y,i);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(i){let a=i.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return i.iteratorType===0?l&&i.next():(!l||a.U===void 0)&&i.next(),this.V(a),i}forEach(i){let a=0;for(let l of this)i(l,a++,this)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===i){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let i=function(a){return a?Math.max(i(a.U),i(a.W))+1:0};return i(this.Y)}},n=o;s.default=n}),As=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(n,i,a){super(a),this.o=n,this.h=i,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,i=this.h.tt;if(n===this.h)return i?i.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==i;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},o=r;s.default=o}),wu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Es()),t=o(As()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class kc extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new kc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.insert(f)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=i;s.default=a}),ku=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=o(Es()),t=o(As()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class _c extends t.default{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new _c(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(f){d.setElement(f[0],f[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=i;s.default=a}),Is=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ts=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.HashContainerIterator=s.HashContainer=void 0;var e=mt(),t=o(Is()),r=gt();function o(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};s.HashContainerIterator=n;var i=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};s.HashContainer=i}),_u=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ts(),t=gt(),r=class xc extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new xc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(i=[]){super();let a=this;i.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(i,a){return this.M(i,void 0,a)}getElementByPos(i){if(i<0||i>this.i-1)throw new RangeError;let a=this.p;for(;i--;)a=a.B;return a.u}find(i,a){let l=this.I(i,a);return new r(l,this.h,this)}forEach(i){let a=0,l=this.p;for(;l!==this.h;)i(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let i=this.p;for(;i!==this.h;)yield i.u,i=i.B}).bind(this)()}},n=o;s.default=n}),xu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),s.default=void 0;var e=Ts(),t=o(Is()),r=gt();function o(l){return l&&l.t?l:{default:l}}var n=class Sc extends e.HashContainerIterator{constructor(c,u,d,f){super(c,u,f),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,f){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=f,!0}})}copy(){return new Sc(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=i;s.default=a}),Su=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"t",{value:!0}),Object.defineProperty(s,"Deque",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(s,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(s,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(s,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(s,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(s,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(s,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(s,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(s,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(s,"Vector",{enumerable:!0,get:function(){return o.default}});var e=d(fu()),t=d(pu()),r=d(mu()),o=d(gu()),n=d(bu()),i=d(yu()),a=d(wu()),l=d(ku()),c=d(_u()),u=d(xu());function d(f){return f&&f.t?f:{default:f}}}),Eu=pe((s,e)=>{le(),ue(),ce();var t=Su().OrderedSet,r=pt()("number-allocator:trace"),o=pt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function i(a,l){if(!(this instanceof i))return new i(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}i.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},i.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},i.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},i.prototype.free=function(a){if(a<this.min||a>this.max){o("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let f=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(f,d))):this.ss.updateKeyByIterator(c,new n(f,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},i.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=i}),Cs=pe((s,e)=>{le(),ue(),ce();var t=Eu();e.exports.NumberAllocator=t}),Au=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=hu(),t=Cs(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(o){o>0&&(this.aliasToTopic=new e.LRUCache({max:o}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,o),this.max=o,this.length=0)}put(o,n){if(n===0||n>this.max)return!1;let i=this.aliasToTopic.get(n);return i&&delete this.topicToAlias[i],this.aliasToTopic.set(n,o),this.topicToAlias[o]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(o){return this.aliasToTopic.get(o)}getAliasByTopic(o){let n=this.topicToAlias[o];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};s.default=r}),Iu=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(s,"__esModule",{value:!0});var t=xr(),r=e(Au()),o=qt(),n=(i,a)=>{i.log("_handleConnack");let{options:l}=i,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(i.connackTimer),delete i.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){i.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(i.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)i.reconnecting=!1,i._onConnect(a);else if(c>0){let u=new o.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);i.emit("error",u),i.options.reconnectOnConnackError&&i._cleanUp(!0)}};s.default=n}),Tu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(t,r,o)=>{t.log("handling pubrel packet");let n=typeof o<"u"?o:t.noop,{messageId:i}=r,a={cmd:"pubcomp",messageId:i};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};s.default=e}),Cu=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(s,"__esModule",{value:!0});var t=e(cu()),r=e(du()),o=e(Iu()),n=e(xr()),i=e(Tu()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,i.default)(l,c,u);break;case"connack":(0,o.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};s.default=a}),Ps=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};s.default=e}),Pu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};s.default=e}),Ou=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(s,"__esModule",{value:!0}),s.TypedEventEmitter=void 0;var t=e((Ct(),Re(wt))),r=qt(),o=class{};s.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Sr=pe((s,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o){return typeof o}:function(o){return o&&typeof Symbol=="function"&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Mu=pe((s,e)=>{le(),ue(),ce();var t=Sr().default;function r(o,n){if(t(o)!="object"||!o)return o;var i=o[Symbol.toPrimitive];if(i!==void 0){var a=i.call(o,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(o)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ru=pe((s,e)=>{le(),ue(),ce();var t=Sr().default,r=Mu();function o(n){var i=r(n,"string");return t(i)=="symbol"?i:i+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Lu=pe((s,e)=>{le(),ue(),ce();var t=Ru();function r(o,n,i){return(n=t(n))in o?Object.defineProperty(o,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):o[n]=i,o}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Nu=pe((s,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ju=pe((s,e)=>{le(),ue(),ce();function t(r,o){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var i,a,l,c,u=[],d=!0,f=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(i=l.call(n)).done)&&(u.push(i.value),u.length!==o);d=!0);}catch(g){f=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(f)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Uu=pe((s,e)=>{le(),ue(),ce();function t(r,o){(o==null||o>r.length)&&(o=r.length);for(var n=0,i=Array(o);n<o;n++)i[n]=r[n];return i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((s,e)=>{le(),ue(),ce();var t=Uu();function r(o,n){if(o){if(typeof o=="string")return t(o,n);var i={}.toString.call(o).slice(8,-1);return i==="Object"&&o.constructor&&(i=o.constructor.name),i==="Map"||i==="Set"?Array.from(o):i==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(o,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((s,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((s,e)=>{le(),ue(),ce();var t=Nu(),r=ju(),o=Bu(),n=Du();function i(a,l){return t(a)||r(a,l)||o(a,l)||n()}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Os=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(s,function(t){var r=function(g){return function(h){var b=g(h);return h.add(b),b}},o=function(g){return function(h,b){return g.set(h,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,a=i*2,l=function(g,h){return function(b){var y=h.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<i){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),d=l(u,c),f=r(d);t.addUniqueNumber=f,t.generateUniqueNumber=d})}),Fu=pe((s,e)=>{le(),ue(),ce();function t(o,n,i,a,l,c,u){try{var d=o[c](u),f=d.value}catch(g){return void i(g)}d.done?n(f):Promise.resolve(f).then(a,l)}function r(o){return function(){var n=this,i=arguments;return new Promise(function(a,l){var c=o.apply(n,i);function u(f){t(c,a,l,u,d,"next",f)}function d(f){t(c,a,l,u,d,"throw",f)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ms=pe((s,e)=>{le(),ue(),ce();function t(r,o){this.v=r,this.k=o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((s,e)=>{le(),ue(),ce();function t(r,o,n,i){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function f(g,h){t(l,g,function(b){return this._invoke(g,h,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(f("next",0),f("throw",1),f("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,o,n,i)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((s,e)=>{le(),ue(),ce();var t=Rs();function r(){var o,n,i=typeof Symbol=="function"?Symbol:{},a=i.iterator||"@@iterator",l=i.toStringTag||"@@toStringTag";function c(w,m,k,x){var v=m&&m.prototype instanceof d?m:d,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,P){var O,j,T,q=0,D=P||[],U=!1,ae={p:0,n:0,v:o,a:Y,f:Y.bind(o,4),d:function(V,re){return O=V,j=0,T=o,ae.n=re,u}};function Y(V,re){for(j=V,T=re,n=0;!U&&q&&!$&&n<D.length;n++){var $,Z=D[n],M=ae.p,Q=Z[2];V>3?($=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=o):Z[0]<=M&&(($=V<2&&M<Z[1])?(j=0,ae.v=re,ae.n=Z[1]):M<Q&&($=V<3||Z[0]>re||re>Q)&&(Z[4]=V,Z[5]=re,ae.n=Q,j=0))}if($||V>1)return u;throw U=!0,re}return function(V,re,$){if(q>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,$),j=re,T=$;(n=j<2?o:T)||!U;){O||(j?j<3?(j>1&&(ae.n=-1),Y(j,T)):ae.n=T:ae.v=T);try{if(q=2,O){if(j||(V="next"),n=O[V]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=O.return)&&n.call(O),j<2&&(T=TypeError("The iterator does not provide a '"+V+"' method"),j=1);O=o}else if((n=(U=ae.n<0)?T:S.call(I,ae))!==u)break}catch(Z){O=o,j=1,T=Z}finally{q=1}}return{value:n,done:U}}})(w,k,x),!0),E}var u={};function d(){}function f(){}function g(){}n=Object.getPrototypeOf;var h=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(h);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return f.prototype=g,t(b,"constructor",g),t(g,"constructor",f),f.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ns=pe((s,e)=>{le(),ue(),ce();var t=Ms(),r=Rs();function o(n,i){function a(c,u,d,f){try{var g=n[c](u),h=g.value;return h instanceof t?i.resolve(h.v).then(function(b){a("next",b,d,f)},function(b){a("throw",b,d,f)}):i.resolve(h).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,f)})}catch(b){f(b)}}var l;this.next||(r(o.prototype),r(o.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function f(){return new i(function(g,h){a(c,d,g,h)})}return l=l?l.then(f,f):f()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),js=pe((s,e)=>{le(),ue(),ce();var t=Ls(),r=Ns();function o(n,i,a,l,c){return new r(t().w(n,i,a,l),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((s,e)=>{le(),ue(),ce();var t=js();function r(o,n,i,a,l){var c=t(o,n,i,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((s,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var i in o)n.unshift(i);return function a(){for(;n.length;)if((i=n.pop())in o)return a.value=i,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((s,e)=>{le(),ue(),ce();var t=Sr().default;function r(o){if(o!=null){var n=o[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],i=0;if(n)return n.call(o);if(typeof o.next=="function")return o;if(!isNaN(o.length))return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}}}throw new TypeError(t(o)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=pe((s,e)=>{le(),ue(),ce();var t=Ms(),r=Ls(),o=qu(),n=js(),i=Ns(),a=Hu(),l=Wu();function c(){var u=r(),d=u.m(c),f=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===f||(w.displayName||w.name)==="GeneratorFunction")}var h={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,h[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(k.d,l(x),E)},finish:function(x){return m(k.f,x)}},m=function(x,v,E){k.p=w.prev,k.n=w.next;try{return x(v,E)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return y.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,k){return u.w(b(y),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:i,async:function(y,w,m,k,x){return(g(w)?n:o)(b(y),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Vu=pe((s,e)=>{le(),ue(),ce();var t=zu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Ku=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Lu(),$u(),Os(),Fu(),Vu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(s,function(t,r,o,n,i,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var f=function(m){return d(d({},m),{},{connect:function(k){var x=k.call;return i(a.mark(function v(){var E,S,I,P;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,O.next=1,x("connect",{port:S},[S]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(k){var x=k.call;return(function(){var v=i(a.mark(function E(S){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(S),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,x("disconnect",{portId:I});case 2:case"end":return P.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(k){var x=k.call;return function(){return x("isSupported")}}})};function g(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function h(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var k=new Map;return b.set(m,k),k},w=function(m){var k=f(m);return function(x){var v=y(x);x.addEventListener("message",function(D){var U=D.data,ae=U.id;if(ae!==null&&v.has(ae)){var Y=v.get(ae),V=Y.reject,re=Y.resolve;v.delete(ae),U.error===void 0?re(U.result):V(new Error(U.error.message))}}),l(x)&&x.start();for(var E=function(D){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,V){var re=n.generateUniqueNumber(v);v.set(re,{reject:V,resolve:Y}),U===null?x.postMessage({id:re,method:D},ae):x.postMessage({id:re,method:D,params:U},ae)})},S=function(D,U){var ae=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},ae)},I={},P=0,O=Object.entries(k);P<O.length;P++){var j=o(O[P],2),T=j[0],q=j[1];I=h(h({},I),{},r({},T,q({call:E,notify:S})))}return h({},I)}};t.createBroker=w})}),Gu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Sr(),Ku(),Os()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(s,function(t,r,o,n){var i=new Map([[0,null]]),a=new Map([[0,null]]),l=o.createBroker({clearInterval:function(u){var d=u.call;return function(f){r(i.get(f))==="symbol"&&(i.set(f,null),d("clear",{timerId:f,timerType:"interval"}).then(function(){i.delete(f)}))}},clearTimeout:function(u){var d=u.call;return function(f){r(a.get(f))==="symbol"&&(a.set(f,null),d("clear",{timerId:f,timerType:"timeout"}).then(function(){a.delete(f)}))}},setInterval:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(i);i.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=i.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(f.apply(void 0,b),i.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(f){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),f.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),Yu=pe((s,e)=>{le(),ue(),ce(),(function(t,r){typeof s=="object"&&typeof e<"u"?r(s,Gu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(s,function(t,r){var o=function(d,f){var g=null;return function(){if(g!==null)return g;var h=new Blob([f],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(h);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=o(r.load,n),a=function(d){return i().clearInterval(d)},l=function(d){return i().clearTimeout(d)},c=function(){var d;return(d=i()).setInterval.apply(d,arguments)},u=function(){var d;return(d=i()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Er=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.isReactNativeBrowser=s.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Ne?.versions?!Object.prototype.hasOwnProperty.call(Ne.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",o=e()||t()||r();s.isWebWorker=t(),s.isReactNativeBrowser=r(),s.default=o}),Ju=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(c,u,d,f){f===void 0&&(f=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,f,g)}:function(c,u,d,f){f===void 0&&(f=d),c[f]=u[d]}),t=s&&s.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=s&&s.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var f=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(f[f.length]=g);return f},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var f=c(u),g=0;g<f.length;g++)f[g]!=="default"&&e(d,u,f[g]);return t(d,u),d}})();Object.defineProperty(s,"__esModule",{value:!0});var o=Yu(),n=r(Er()),i={set:o.setInterval,clear:o.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return i;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?i:a}};s.default=l}),Us=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(s,"__esModule",{value:!0});var t=e(Ju()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(o,n){this.client=o,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(o.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(o){if(o*=1e3,isNaN(o)||o<=0||o>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${o}`);this._keepalive=o,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${o}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let o=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+o,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};s.default=r}),_i=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var P=Object.getOwnPropertyDescriptor(E,S);(!P||("get"in P?!E.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,P)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=s&&s.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=s&&s.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var P in S)Object.prototype.hasOwnProperty.call(S,P)&&(I[I.length]=P);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),P=0;P<I.length;P++)I[P]!=="default"&&e(S,E,I[P]);return t(S,E),S}})(),o=s&&s.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(s,"__esModule",{value:!0});var n=o(su()),i=Ot(),a=o(lu()),l=o(pt()),c=r(_s()),u=o(xs()),d=o(Cu()),f=o(Ps()),g=o(Pu()),h=qt(),b=Ou(),y=o(Us()),w=r(Er()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,h.nextTick)(()=>{E(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class jo extends b.TypedEventEmitter{static VERSION=h.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(E,S){super(),this.options=S||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=S[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",jo.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",S.protocol),this.log("MqttClient :: options.protocolVersion",S.protocolVersion),this.log("MqttClient :: options.username",S.username),this.log("MqttClient :: options.keepalive",S.keepalive),this.log("MqttClient :: options.reconnectPeriod",S.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",S.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",S.properties?S.properties.topicAliasMaximum:void 0),this.options.clientId=typeof S.clientId=="string"?S.clientId:jo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new f.default:this.options.messageIdProvider,this.outgoingStore=S.outgoingStore||new u.default,this.incomingStore=S.incomingStore||new u.default,this.queueQoSZero=S.queueQoSZero===void 0?!0:S.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,S.properties&&S.properties.topicAliasMaximum>0&&(S.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let j=null;if(!O){this._resubscribe();return}j=O.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,q=>{O.cb&&O.cb(q),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),P())};this.log("connect :: sending queued packets"),P()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new i.Writable,S=n.default.parser(this.options),I=null,P=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),S.on("packet",D=>{this.log("parser :: on packet push to packets array."),P.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=P.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,j);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(P.length)(0,h.nextTick)(O);else{let D=I;I=null,D()}};E._write=(D,U,ae)=>{I=ae,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(E),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let q={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(q.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(q.properties||(q.properties={}),this.topicAliasRecv&&(q.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(q),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let D={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(D)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(E,S,I,P){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:j,retain:T,dup:q,properties:D,cbStorePut:U}=I;if(this._checkDisconnecting(P))return this;let ae=()=>{let Y=0;if((j===1||j===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let V={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:Y,dup:q};switch(O.protocolVersion===5&&(V.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[V.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",V.cmd),this._sendPacket(V,P,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!ae())&&this._storeProcessingQueue.push({invoke:ae,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(E,S,I){return new Promise((P,O)=>{this.publish(E,S,I,(j,T)=>{j?O(j):P(T)})})}subscribe(E,S,I){let P=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let O=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,j=Object.keys(E));let T=c.validateTopics(j);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let q={qos:0};P===5&&(q.nl=!1,q.rap=!1,q.rh=0),S={...q,...S};let{properties:D}=S,U=[],ae=(re,$)=>{if($=$||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<$.qos||O){let Z={topic:re,qos:$.qos};P===5&&(Z.nl=$.nl,Z.rap=$.rap,Z.rh=$.rh,Z.properties=D),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),U.push(Z)}};if(Array.isArray(E)?E.forEach(re=>{this.log("subscribe: array topic %s",re),ae(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),ae(re,E[re])}),!U.length)return I(null,[]),this;let Y=(re,$)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:$};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};P===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,Q.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:K}=we;for(let N=0;N<K.length;N+=1)re[N].qos=K[N]}te?be(new h.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},V=()=>{let re=this.options.subscribeBatchSize??U.length,$=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;$.push(Y(M,Q))}return Promise.all($).then(Z=>{I(null,U,Z.at(-1))}).catch(Z=>{I(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!V())&&this._storeProcessingQueue.push({invoke:V,callback:I}),this}subscribeAsync(E,S){return new Promise((I,P)=>{this.subscribe(E,S,(O,j)=>{O?P(O):I(j)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let P=c.validateTopics(E);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(q=>{delete this._resubscribeTopics[q]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,P)=>{this.unsubscribe(E,S,(O,j)=>{O?P(O):I(j)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let q=j||T;this.log("end :: closeStores: invoking callback with args"),I(q)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,h.nextTick)(P)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(E,S){return new Promise((I,P)=>{this.end(E,S,O=>{O?P(O):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let P={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(P,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let P=E,O;if(P.cmd==="publish"&&(P=(0,a.default)(E),O=this._removeTopicAliasAndRecoverTopicName(P),O))return S&&S(O);this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(E,S,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let O=this._applyTopicAlias(E);if(O){S(O);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(P){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let P=E;if(P.cmd==="publish"){P=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(P);if(j)return S&&S(j)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:S}):O>0?(S=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let j=()=>{if(!I)return;let T=I.read(1),q;if(!T){I.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(q=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){q&&q(D,U),j()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let q in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[q]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),j()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,P)=>{S(I,P),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};s.default=x}),Qu=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=Cs(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};s.default=t});function Xu(){if(xi)return Ar;xi=!0;let s=2147483647,e=36,t=1,r=26,o=38,n=700,i=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,h=Math.floor,b=String.fromCharCode;function y(O){throw new RangeError(f[O])}function w(O,j){let T=[],q=O.length;for(;q--;)T[q]=j(O[q]);return T}function m(O,j){let T=O.split("@"),q="";T.length>1&&(q=T[0]+"@",O=T[1]),O=O.replace(d,".");let D=O.split("."),U=w(D,j).join(".");return q+U}function k(O){let j=[],T=0,q=O.length;for(;T<q;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<q){let U=O.charCodeAt(T++);(U&64512)==56320?j.push(((D&1023)<<10)+(U&1023)+65536):(j.push(D),T--)}else j.push(D)}return j}let x=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},E=function(O,j){return O+22+75*(O<26)-((j!=0)<<5)},S=function(O,j,T){let q=0;for(O=T?h(O/n):O>>1,O+=h(O/j);O>g*r>>1;q+=e)O=h(O/g);return h(q+(g+1)*O/(O+o))},I=function(O){let j=[],T=O.length,q=0,D=a,U=i,ae=O.lastIndexOf(l);ae<0&&(ae=0);for(let Y=0;Y<ae;++Y)O.charCodeAt(Y)>=128&&y("not-basic"),j.push(O.charCodeAt(Y));for(let Y=ae>0?ae+1:0;Y<T;){let V=q;for(let $=1,Z=e;;Z+=e){Y>=T&&y("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&y("invalid-input"),M>h((s-q)/$)&&y("overflow"),q+=M*$;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let be=e-Q;$>h(s/be)&&y("overflow"),$*=be}let re=j.length+1;U=S(q-V,re,V==0),h(q/re)>s-D&&y("overflow"),D+=h(q/re),q%=re,j.splice(q++,0,D)}return String.fromCodePoint(...j)},P=function(O){let j=[];O=k(O);let T=O.length,q=a,D=0,U=i;for(let V of O)V<128&&j.push(b(V));let ae=j.length,Y=ae;for(ae&&j.push(l);Y<T;){let V=s;for(let $ of O)$>=q&&$<V&&(V=$);let re=Y+1;V-q>h((s-D)/re)&&y("overflow"),D+=(V-q)*re,q=V;for(let $ of O)if($<q&&++D>s&&y("overflow"),$===q){let Z=D;for(let M=e;;M+=e){let Q=M<=U?t:M>=U+r?r:M-U;if(Z<Q)break;let be=Z-Q,te=e-Q;j.push(b(E(Q+be%te,0))),Z=h(be/te)}j.push(b(E(Z,0))),U=S(D,re,Y===ae),D=0,++Y}++D,++q}return j.join("")};return Ar={version:"2.3.1",ucs2:{decode:k,encode:x},decode:I,encode:P,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+P(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},Ar}var Ar,xi,_t,Zu=Ye(()=>{le(),ue(),ce(),Ar={},xi=!1,_t=Xu(),_t.decode,_t.encode,_t.toASCII,_t.toUnicode,_t.ucs2,_t.version});function ed(){return Ii||(Ii=!0,Ai=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var s={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;s[e]=r;for(e in s)return!1;if(typeof Object.keys=="function"&&Object.keys(s).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(s).length!==0)return!1;var o=Object.getOwnPropertySymbols(s);if(o.length!==1||o[0]!==e||!Object.prototype.propertyIsEnumerable.call(s,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(s,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ai}function td(){return Ci||(Ci=!0,Ti=Error),Ti}function rd(){return Oi||(Oi=!0,Pi=EvalError),Pi}function nd(){return Ri||(Ri=!0,Mi=RangeError),Mi}function id(){return Ni||(Ni=!0,Li=ReferenceError),Li}function Bs(){return Ui||(Ui=!0,ji=SyntaxError),ji}function ir(){return Di||(Di=!0,Bi=TypeError),Bi}function od(){return Fi||(Fi=!0,$i=URIError),$i}function sd(){if(qi)return Ir;qi=!0;var s=typeof Symbol<"u"&&Symbol,e=ed();return Ir=function(){return typeof s!="function"||typeof Symbol!="function"||typeof s("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Ir}function ad(){if(Hi)return Tr;Hi=!0;var s={__proto__:null,foo:{}},e=Object;return Tr=function(){return{__proto__:s}.foo===s.foo&&!(s instanceof e)},Tr}function ld(){if(Wi)return Cr;Wi=!0;var s="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},i=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Cr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(s+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,o(c,arguments));return Object(y)===y?y:this}return l.apply(a,o(c,arguments))},f=t(0,l.length-c.length),g=[],h=0;h<f;h++)g[h]="$"+h;if(u=Function("binder","return function ("+i(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},Cr}function Si(){if(zi)return Pr;zi=!0;var s=ld();return Pr=Function.prototype.bind||s,Pr}function cd(){if(Vi)return Or;Vi=!0;var s=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Si();return Or=t.call(s,e),Or}function Ht(){if(Ki)return Mr;Ki=!0;var s,e=td(),t=rd(),r=nd(),o=id(),n=Bs(),i=ir(),a=od(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new i},f=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=sd()(),h=ad()(),b=Object.getPrototypeOf||(h?function(Y){return Y.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?s:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?s:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?s:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):s,"%AsyncFromSyncIteratorPrototype%":s,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?s:Atomics,"%BigInt%":typeof BigInt>"u"?s:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?s:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?s:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?s:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?s:Float32Array,"%Float64Array%":typeof Float64Array>"u"?s:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?s:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?s:Int8Array,"%Int16Array%":typeof Int16Array>"u"?s:Int16Array,"%Int32Array%":typeof Int32Array>"u"?s:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):s,"%JSON%":typeof JSON=="object"?JSON:s,"%Map%":typeof Map>"u"?s:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?s:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?s:Promise,"%Proxy%":typeof Proxy>"u"?s:Proxy,"%RangeError%":r,"%ReferenceError%":o,"%Reflect%":typeof Reflect>"u"?s:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?s:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?s:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?s:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):s,"%Symbol%":g?Symbol:s,"%SyntaxError%":n,"%ThrowTypeError%":f,"%TypedArray%":w,"%TypeError%":i,"%Uint8Array%":typeof Uint8Array>"u"?s:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?s:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?s:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?s:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?s:WeakMap,"%WeakRef%":typeof WeakRef>"u"?s:WeakRef,"%WeakSet%":typeof WeakSet>"u"?s:WeakSet};if(b)try{null.error}catch(Y){var k=b(b(Y));m["%Error.prototype%"]=k}var x=function Y(V){var re;if(V==="%AsyncFunction%")re=c("async function () {}");else if(V==="%GeneratorFunction%")re=c("function* () {}");else if(V==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(V==="%AsyncGenerator%"){var $=Y("%AsyncGeneratorFunction%");$&&(re=$.prototype)}else if(V==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&b&&(re=b(Z.prototype))}return m[V]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},E=Si(),S=cd(),I=E.call(Function.call,Array.prototype.concat),P=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),j=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var V=j(Y,0,1),re=j(Y,-1);if(V==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&V!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var $=[];return O(Y,q,function(Z,M,Q,be){$[$.length]=Q?O(be,D,"$1"):M||Z}),$},ae=function(Y,V){var re=Y,$;if(S(v,re)&&($=v[re],re="%"+$[0]+"%"),S(m,re)){var Z=m[re];if(Z===y&&(Z=x(re)),typeof Z>"u"&&!V)throw new i("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:$,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return Mr=function(Y,V){if(typeof Y!="string"||Y.length===0)throw new i("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof V!="boolean")throw new i('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=U(Y),$=re.length>0?re[0]:"",Z=ae("%"+$+"%",V),M=Z.name,Q=Z.value,be=!1,te=Z.alias;te&&($=te[0],P(re,I([0,1],te)));for(var we=1,K=!0;we<re.length;we+=1){var N=re[we],ne=j(N,0,1),W=j(N,-1);if((ne==='"'||ne==="'"||ne==="`"||W==='"'||W==="'"||W==="`")&&ne!==W)throw new n("property names with quotes must have matching quotes");if((N==="constructor"||!K)&&(be=!0),$+="."+N,M="%"+$+"%",S(m,M))Q=m[M];else if(Q!=null){if(!(N in Q)){if(!V)throw new i("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var G=u(Q,N);K=!!G,K&&"get"in G&&!("originalValue"in G.get)?Q=G.get:Q=Q[N]}else K=S(Q,N),Q=Q[N];K&&!be&&(m[M]=Q)}}return Q},Mr}function Ei(){if(Gi)return Rr;Gi=!0;var s=Ht(),e=s("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Rr=e,Rr}function Ds(){if(Yi)return Lr;Yi=!0;var s=Ht(),e=s("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Lr=e,Lr}function ud(){if(Ji)return Nr;Ji=!0;var s=Ei(),e=Bs(),t=ir(),r=Ds();return Nr=function(o,n,i){if(!o||typeof o!="object"&&typeof o!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(o,n);if(s)s(o,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:i,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)o[n]=i;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Nr}function dd(){if(Qi)return jr;Qi=!0;var s=Ei(),e=function(){return!!s};return e.hasArrayLengthDefineBug=function(){if(!s)return null;try{return s([],"length",{value:1}).length!==1}catch{return!0}},jr=e,jr}function hd(){if(Xi)return Ur;Xi=!0;var s=Ht(),e=ud(),t=dd()(),r=Ds(),o=ir(),n=s("%Math.floor%");return Ur=function(i,a){if(typeof i!="function")throw new o("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new o("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in i&&r){var d=r(i,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(i,"length",a,!0,!0):e(i,"length",a)),i},Ur}function fd(){if(Zi)return Wt;Zi=!0;var s=Si(),e=Ht(),t=hd(),r=ir(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),i=e("%Reflect.apply%",!0)||s.call(n,o),a=Ei(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var d=i(s,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return i(s,o,arguments)};return a?a(Wt,"apply",{value:c}):Wt.apply=c,Wt}function pd(){if(eo)return Br;eo=!0;var s=Ht(),e=fd(),t=e(s("String.prototype.indexOf"));return Br=function(r,o){var n=s(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Br}var Ai,Ii,Ti,Ci,Pi,Oi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,$i,Fi,Ir,qi,Tr,Hi,Cr,Wi,Pr,zi,Or,Vi,Mr,Ki,Rr,Gi,Lr,Yi,Nr,Ji,jr,Qi,Ur,Xi,Wt,Zi,Br,eo,md=Ye(()=>{le(),ue(),ce(),Ai={},Ii=!1,Ti={},Ci=!1,Pi={},Oi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,$i={},Fi=!1,Ir={},qi=!1,Tr={},Hi=!1,Cr={},Wi=!1,Pr={},zi=!1,Or={},Vi=!1,Mr={},Ki=!1,Rr={},Gi=!1,Lr={},Yi=!1,Nr={},Ji=!1,jr={},Qi=!1,Ur={},Xi=!1,Wt={},Zi=!1,Br={},eo=!1});function to(s){throw new Error("Node.js process "+s+" is not supported by JSPM core outside of Node.js")}function gd(){!Mt||!Rt||(Mt=!1,Rt.length?rt=Rt.concat(rt):or=-1,rt.length&&$s())}function $s(){if(!Mt){var s=setTimeout(gd,0);Mt=!0;for(var e=rt.length;e;){for(Rt=rt,rt=[];++or<e;)Rt&&Rt[or].run();or=-1,e=rt.length}Rt=null,Mt=!1,clearTimeout(s)}}function bd(s){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new Fs(s,e)),rt.length===1&&!Mt&&setTimeout($s,0)}function Fs(s,e){this.fun=s,this.array=e}function We(){}function yd(s){to("_linkedBinding")}function vd(s){to("dlopen")}function wd(){return[]}function kd(){return[]}function _d(s,e){if(!s)throw new Error(e||"assertion error")}function xd(){return!1}function Sd(){return bt.now()/1e3}function ro(s){var e=Math.floor((Date.now()-bt.now())*.001),t=bt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return s&&(r=r-s[0],o=o-s[1],o<0&&(r--,o+=$r)),[r,o]}function xt(){return io}function Ed(s){return[]}var rt,Mt,Rt,or,qs,Hs,Ws,zs,Vs,Ks,Gs,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,Dr,ca,ua,da,ha,fa,pa,ma,ga,ba,ya,va,wa,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,Ma,Ra,bt,no,$r,La,Na,ja,Ua,Ba,Da,$a,Fa,qa,Ha,Wa,io,za=Ye(()=>{le(),ue(),ce(),rt=[],Mt=!1,or=-1,Fs.prototype.run=function(){this.fun.apply(null,this.array)},qs="browser",Hs="x64",Ws="browser",zs={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Vs=["/usr/bin/node"],Ks=[],Gs="v16.8.0",Ys={},Js=function(s,e){console.warn((e?e+": ":"")+s)},Qs=function(s){to("binding")},Xs=function(s){return 0},Zs=function(){return"/"},ea=function(s){},ta={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ra=We,na=[],ia={},oa=!1,sa={},aa=We,la=We,Dr=function(){return{}},ca=Dr,ua=Dr,da=We,ha=We,fa=We,pa={},ma={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ga=We,ba=We,ya=We,va=We,wa=We,ka=We,_a=We,xa=void 0,Sa=void 0,Ea=void 0,Aa=We,Ia=2,Ta=1,Ca="/bin/usr/node",Pa=9229,Oa="node",Ma=[],Ra=We,bt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},bt.now===void 0&&(no=Date.now(),bt.timing&&bt.timing.navigationStart&&(no=bt.timing.navigationStart),bt.now=()=>Date.now()-no),$r=1e9,ro.bigint=function(s){var e=ro(s);return typeof BigInt>"u"?e[0]*$r+e[1]:BigInt(e[0]*$r)+BigInt(e[1])},La=10,Na={},ja=0,Ua=xt,Ba=xt,Da=xt,$a=xt,Fa=xt,qa=We,Ha=xt,Wa=xt,io={version:Gs,versions:Ys,arch:Hs,platform:Ws,release:ta,_rawDebug:ra,moduleLoadList:na,binding:Qs,_linkedBinding:yd,_events:Na,_eventsCount:ja,_maxListeners:La,on:xt,addListener:Ua,once:Ba,off:Da,removeListener:$a,removeAllListeners:Fa,emit:qa,prependListener:Ha,prependOnceListener:Wa,listeners:Ed,domain:ia,_exiting:oa,config:sa,dlopen:vd,uptime:Sd,_getActiveRequests:wd,_getActiveHandles:kd,reallyExit:aa,_kill:la,cpuUsage:Dr,resourceUsage:ca,memoryUsage:ua,kill:da,exit:ha,openStdin:fa,allowedNodeEnvironmentFlags:pa,assert:_d,features:ma,_fatalExceptions:ga,setUncaughtExceptionCaptureCallback:ba,hasUncaughtExceptionCaptureCallback:xd,emitWarning:Js,nextTick:bd,_tickCallback:ya,_debugProcess:va,_debugEnd:wa,_startProfilerIdleNotifier:ka,_stopProfilerIdleNotifier:_a,stdout:xa,stdin:Ea,stderr:Sa,abort:Aa,umask:Xs,chdir:ea,cwd:Zs,env:zs,title:qs,argv:Vs,execArgv:Ks,pid:Ia,ppid:Ta,execPath:Ca,debugPort:Pa,hrtime:ro,argv0:Oa,_preload_modules:Ma,setSourceMapsEnabled:Ra}});function Ad(){if(oo)return Fr;oo=!0;var s=io;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,i){for(var a="",l=0,c=-1,u=0,d,f=0;f<=n.length;++f){if(f<n.length)d=n.charCodeAt(f);else{if(d===47)break;d=47}if(d===47){if(!(c===f-1||u===1))if(c!==f-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=f,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=f,u=0;continue}}i&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,f):a=n.slice(c+1,f),l=f-c-1;c=f,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,i){var a=i.dir||i.root,l=i.base||(i.name||"")+(i.ext||"");return a?a===i.root?a+l:a+n+l:l}var o={resolve:function(){for(var n="",i=!1,a,l=arguments.length-1;l>=-1&&!i;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=s.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,i=c.charCodeAt(0)===47)}return n=t(n,!i),i?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var i=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!i),n.length===0&&!i&&(n="."),n.length>0&&a&&(n+="/"),i?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,i=0;i<arguments.length;++i){var a=arguments[i];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":o.normalize(n)},relative:function(n,i){if(e(n),e(i),n===i||(n=o.resolve(n),i=o.resolve(i),n===i))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<i.length&&i.charCodeAt(u)===47;++u);for(var d=i.length,f=d-u,g=c<f?c:f,h=-1,b=0;b<=g;++b){if(b===g){if(f>g){if(i.charCodeAt(u+b)===47)return i.slice(u+b+1);if(b===0)return i.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?h=b:b===0&&(h=0));break}var y=n.charCodeAt(a+b),w=i.charCodeAt(u+b);if(y!==w)break;y===47&&(h=b)}var m="";for(b=a+h+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+i.slice(u+h):(u+=h,i.charCodeAt(u)===47&&++u,i.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var i=n.charCodeAt(0),a=i===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(i=n.charCodeAt(u),i===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(i!==void 0&&i.length>0&&i.length<=n.length){if(i.length===n.length&&i===n)return"";var d=i.length-1,f=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else f===-1&&(c=!1,f=u+1),d>=0&&(g===i.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=f))}return a===l?l=f:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var i=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var f=n.charCodeAt(d);if(f===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),f===46?i===-1?i=d:u!==1&&(u=1):i!==-1&&(u=-1)}return i===-1||l===-1||u===0||u===1&&i===l-1&&i===a+1?"":n.slice(i,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var i={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return i;var a=n.charCodeAt(0),l=a===47,c;l?(i.root="/",c=1):c=0;for(var u=-1,d=0,f=-1,g=!0,h=n.length-1,b=0;h>=c;--h){if(a=n.charCodeAt(h),a===47){if(!g){d=h+1;break}continue}f===-1&&(g=!1,f=h+1),a===46?u===-1?u=h:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||f===-1||b===0||b===1&&u===f-1&&u===d+1?f!==-1&&(d===0&&l?i.base=i.name=n.slice(1,f):i.base=i.name=n.slice(d,f)):(d===0&&l?(i.name=n.slice(1,u),i.base=n.slice(1,f)):(i.name=n.slice(d,u),i.base=n.slice(d,f)),i.ext=n.slice(u,f)),d>0?i.dir=n.slice(0,d-1):l&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Fr=o,Fr}var Fr,oo,so,Id=Ye(()=>{le(),ue(),ce(),za(),Fr={},oo=!1,so=Ad()}),Va={};Bt(Va,{URL:()=>nl,Url:()=>Xa,default:()=>ze,fileURLToPath:()=>Ga,format:()=>Za,parse:()=>rl,pathToFileURL:()=>Ya,resolve:()=>el,resolveObject:()=>tl});function Td(){if(lo)return qr;lo=!0;var s=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=s&&e&&typeof e.get=="function"?e.get:null,r=s&&Map.prototype.forEach,o=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,i=o&&n&&typeof n.get=="function"?n.get:null,a=o&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,f=typeof WeakRef=="function"&&WeakRef.prototype,g=f?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,q=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,D=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===D||!0)?Symbol.toStringTag:null,ae=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(z){return z.__proto__}:null);function V(z,ie){if(z===1/0||z===-1/0||z!==z||z&&z>-1e3&&z<1e3||E.call(/e/,ie))return ie;var Ee=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof z=="number"){var Ae=z<0?-O(-z):O(z);if(Ae!==z){var Te=String(Ae),Oe=m.call(ie,Te.length+1);return k.call(Te,Ee,"$&_")+"."+k.call(k.call(Oe,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ee,"$&_")}var re=Ja,$=re.custom,Z=G($)?$:null;qr=function z(ie,Ee,Ae,Te){var Oe=Ee||{};if(oe(Oe,"quoteStyle")&&Oe.quoteStyle!=="single"&&Oe.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(oe(Oe,"maxStringLength")&&(typeof Oe.maxStringLength=="number"?Oe.maxStringLength<0&&Oe.maxStringLength!==1/0:Oe.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var nt=oe(Oe,"customInspect")?Oe.customInspect:!0;if(typeof nt!="boolean"&&nt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(oe(Oe,"indent")&&Oe.indent!==null&&Oe.indent!==" "&&!(parseInt(Oe.indent,10)===Oe.indent&&Oe.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(oe(Oe,"numericSeparator")&&typeof Oe.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var it=Oe.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return se(ie,Oe);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ve=String(ie);return it?V(ie,Ve):Ve}if(typeof ie=="bigint"){var ot=String(ie)+"n";return it?V(ie,ot):ot}var Jt=typeof Oe.depth>"u"?5:Oe.depth;if(typeof Ae>"u"&&(Ae=0),Ae>=Jt&&Jt>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var st=X(Oe,Ae);if(typeof Te>"u")Te=[];else if(ee(Te,ie)>=0)return"[Circular]";function Ze(at,At,Ut){if(At&&(Te=P.call(Te),Te.push(At)),Ut){var lt={depth:Oe.depth};return oe(Oe,"quoteStyle")&&(lt.quoteStyle=Oe.quoteStyle),z(at,lt,Ae+1,Te)}return z(at,Oe,Ae+1,Te)}if(typeof ie=="function"&&!we(ie)){var tn=F(ie),Qt=_e(ie,Ze);return"[Function"+(tn?": "+tn:" (anonymous)")+"]"+(Qt.length>0?" { "+I.call(Qt,", ")+" }":"")}if(G(ie)){var ur=D?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):q.call(ie);return typeof ie=="object"&&!D?p(ur):ur}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],ke=0;ke<L.length;ke++)C+=" "+L[ke].name+"="+M(Q(L[ke].value),"double",Oe);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var xe=_e(ie,Ze);return st&&!B(xe)?"["+de(xe,st)+"]":"[ "+I.call(xe,", ")+" ]"}if(K(ie)){var Se=_e(ie,Ze);return!("cause"in Error.prototype)&&"cause"in ie&&!ae.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(S.call("[cause]: "+Ze(ie.cause),Se),", ")+" }":Se.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Se,", ")+" }"}if(typeof ie=="object"&&nt){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Jt-Ae});if(nt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var De=[];return r&&r.call(ie,function(at,At){De.push(Ze(At,ie,!0)+" => "+Ze(at,ie))}),A("Map",t.call(ie),De,st)}if(H(ie)){var Ge=[];return a&&a.call(ie,function(at){Ge.push(Ze(at,ie))}),A("Set",i.call(ie),Ge,st)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return p(Ze(Number(ie)));if(J(ie))return p(Ze(j.call(ie)));if(W(ie))return p(h.call(ie));if(N(ie))return p(Ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Hr<"u"&&ie===Hr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=_e(ie,Ze),dr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,hr=ie instanceof Object?"":"null prototype",fr=!dr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):hr?"Object":"",rn=dr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",jt=rn+(fr||hr?"["+I.call(S.call([],fr||[],hr||[]),": ")+"] ":"");return et.length===0?jt+"{}":st?jt+"{"+de(et,st)+"}":jt+"{ "+I.call(et,", ")+" }"}return String(ie)};function M(z,ie,Ee){var Ae=(Ee.quoteStyle||ie)==="double"?'"':"'";return Ae+z+Ae}function Q(z){return k.call(String(z),/"/g,""")}function be(z){return R(z)==="[object Array]"&&(!U||!(typeof z=="object"&&U in z))}function te(z){return R(z)==="[object Date]"&&(!U||!(typeof z=="object"&&U in z))}function we(z){return R(z)==="[object RegExp]"&&(!U||!(typeof z=="object"&&U in z))}function K(z){return R(z)==="[object Error]"&&(!U||!(typeof z=="object"&&U in z))}function N(z){return R(z)==="[object String]"&&(!U||!(typeof z=="object"&&U in z))}function ne(z){return R(z)==="[object Number]"&&(!U||!(typeof z=="object"&&U in z))}function W(z){return R(z)==="[object Boolean]"&&(!U||!(typeof z=="object"&&U in z))}function G(z){if(D)return z&&typeof z=="object"&&z instanceof Symbol;if(typeof z=="symbol")return!0;if(!z||typeof z!="object"||!q)return!1;try{return q.call(z),!0}catch{}return!1}function J(z){if(!z||typeof z!="object"||!j)return!1;try{return j.call(z),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(z){return z in(this||Hr)};function oe(z,ie){return ge.call(z,ie)}function R(z){return b.call(z)}function F(z){if(z.name)return z.name;var ie=w.call(y.call(z),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(z,ie){if(z.indexOf)return z.indexOf(ie);for(var Ee=0,Ae=z.length;Ee<Ae;Ee++)if(z[Ee]===ie)return Ee;return-1}function he(z){if(!t||!z||typeof z!="object")return!1;try{t.call(z);try{i.call(z)}catch{return!0}return z instanceof Map}catch{}return!1}function fe(z){if(!c||!z||typeof z!="object")return!1;try{c.call(z,c);try{d.call(z,d)}catch{return!0}return z instanceof WeakMap}catch{}return!1}function ye(z){if(!g||!z||typeof z!="object")return!1;try{return g.call(z),!0}catch{}return!1}function H(z){if(!i||!z||typeof z!="object")return!1;try{i.call(z);try{t.call(z)}catch{return!0}return z instanceof Set}catch{}return!1}function me(z){if(!d||!z||typeof z!="object")return!1;try{d.call(z,d);try{c.call(z,c)}catch{return!0}return z instanceof WeakSet}catch{}return!1}function ve(z){return!z||typeof z!="object"?!1:typeof HTMLElement<"u"&&z instanceof HTMLElement?!0:typeof z.nodeName=="string"&&typeof z.getAttribute=="function"}function se(z,ie){if(z.length>ie.maxStringLength){var Ee=z.length-ie.maxStringLength,Ae="... "+Ee+" more character"+(Ee>1?"s":"");return se(m.call(z,0,ie.maxStringLength),ie)+Ae}var Te=k.call(k.call(z,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Ce);return M(Te,"single",ie)}function Ce(z){var ie=z.charCodeAt(0),Ee={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ee?"\\"+Ee:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function p(z){return"Object("+z+")"}function _(z){return z+" { ? }"}function A(z,ie,Ee,Ae){var Te=Ae?de(Ee,Ae):I.call(Ee,", ");return z+" ("+ie+") {"+Te+"}"}function B(z){for(var ie=0;ie<z.length;ie++)if(ee(z[ie],`
|
|
4
4
|
`)>=0)return!1;return!0}function X(z,ie){var Ee;if(z.indent===" ")Ee=" ";else if(typeof z.indent=="number"&&z.indent>0)Ee=I.call(Array(z.indent+1)," ");else return null;return{base:Ee,prev:I.call(Array(ie+1),Ee)}}function de(z,ie){if(z.length===0)return"";var Ee=`
|
|
5
5
|
`+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
|
|
6
|
-
`+ie.prev}function _e(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Te=0;Te<z.length;Te++)Ae[Te]=oe(z,Te)?ie(z[Te],z):""}var Oe=typeof T=="function"?T(z):[],nt;if(D){nt={};for(var it=0;it<Oe.length;it++)nt["$"+Oe[it]]=Oe[it]}for(var Ve in z)oe(z,Ve)&&(Ee&&String(Number(Ve))===Ve&&Ve<z.length||D&&nt["$"+Ve]instanceof Symbol||(E.call(/[^\w$]/,Ve)?Ae.push(ie(Ve,z)+": "+ie(z[Ve],z)):Ae.push(Ve+": "+ie(z[Ve],z))));if(typeof T=="function")for(var ot=0;ot<Oe.length;ot++)ae.call(z,Oe[ot])&&Ae.push("["+ie(Oe[ot])+"]: "+ie(z[Oe[ot]],z));return Ae}return qr}function Td(){if(co)return Wr;co=!0;var s=Ht(),e=fd(),t=Id(),r=ir(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),f=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=f(y,w);return m&&m.value},h=function(y,w,m){var k=f(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!f(y,w)};return Wr=function(){var y,w,m,k={assert:function(x){if(!k.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return i(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),h(m,x,v))}};return k},Wr}function ao(){if(uo)return zr;uo=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return zr={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},zr}function Ka(){if(ho)return Vr;ho=!0;var s=ao(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},i=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,k):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,k):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,P=[],O=0;O<I.length;++O){var j=I.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===s.RFC1738&&(j===40||j===41)){P[P.length]=I.charAt(O);continue}if(j<128){P[P.length]=r[j];continue}if(j<2048){P[P.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){P[P.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=P.join("")}return E},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},f=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},h=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Vr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:f,maybeMap:b,merge:i},Vr}function Cd(){if(fo)return Kr;fo=!0;var s=Td(),e=Ka(),t=ao(),r=Object.prototype.hasOwnProperty,o={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,i=Array.prototype.push,a=function(b,y){i.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},f={},g=function b(y,w,m,k,x,v,E,S,I,P,O,j,T,q,D,U,ae,Y){for(var V=y,re=Y,$=0,Z=!1;(re=re.get(f))!==void 0&&!Z;){var M=re.get(y);if($+=1,typeof M<"u"){if(M===$)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(f)>"u"&&($=0)}if(typeof P=="function"?V=P(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(d(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var K=S?w.replace(/\./g,"%2E"):w,N=k&&n(V)&&V.length===1?K+"[]":K;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],G=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&G===null)){var J=j&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,$);var oe=s();oe.set(f,Y),a(be,b(G,ge,m,k,x,v,E,S,m==="comma"&&U&&n(V)?null:I,P,O,j,T,q,D,U,ae,oe))}}return be},h=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return Kr=function(b,y){var w=b,m=h(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=s(),P=0;P<k.length;++P){var O=k[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},Kr}function Pd(){if(po)return Gr;po=!0;var s=Ka(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:s.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(f){return f.replace(/&#(\d+);/g,function(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(f,g){return f&&typeof f=="string"&&g.comma&&f.indexOf(",")>-1?f.split(","):f},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,g){var h={__proto__:null},b=g.ignoreQueryPrefix?f.replace(/^\?/,""):f;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===i&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,P;S===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,x,"key"),P=s.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(h,I);O&&g.duplicates==="combine"?h[I]=s.combine(h[I],P):(!O||g.duplicates==="last")&&(h[I]=P)}return h},c=function(f,g,h,b){for(var y=b?g:n(g,h),w=f.length-1;w>=0;--w){var m,k=f[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(E)&&k!==v&&String(E)===v&&E>=0&&h.parseArrays&&E<=h.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(f,g,h,b){if(f){var y=h.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!h.plainObjects&&e.call(Object.prototype,x)&&!h.allowPrototypes)return;v.push(x)}for(var E=0;h.depth>0&&(k=m.exec(y))!==null&&E<h.depth;){if(E+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=function(f){if(!f)return r;if(typeof f.allowEmptyArrays<"u"&&typeof f.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof f.decodeDotInKeys<"u"&&typeof f.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(f.decoder!==null&&typeof f.decoder<"u"&&typeof f.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof f.charset<"u"&&f.charset!=="utf-8"&&f.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof f.charset>"u"?r.charset:f.charset,h=typeof f.duplicates>"u"?r.duplicates:f.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:r.allowDots:!!f.allowDots;return{allowDots:b,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:r.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:r.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:r.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:r.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:r.decoder,delimiter:typeof f.delimiter=="string"||s.isRegExp(f.delimiter)?f.delimiter:r.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:r.depth,duplicates:h,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:r.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:r.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:r.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:r.strictNullHandling}};return Gr=function(f,g){var h=d(g);if(f===""||f===null||typeof f>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof f=="string"?l(f,h):f,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],h,typeof f=="string");y=s.merge(y,x,h)}return h.allowSparse===!0?y:s.compact(y)},Gr}function Od(){if(mo)return Yr;mo=!0;var s=Cd(),e=Pd(),t=ao();return Yr={formats:t,parse:e,stringify:s},Yr}function Md(){if(go)return St;go=!0;var s=_t;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
-
`," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,f=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},h={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=
|
|
8
|
-
`)&&(e=e.replace(dl,"%0A")),e.includes("\r")&&(e=e.replace(hl,"%0D")),e.includes(" ")&&(e=e.replace(fl,"%09")),r.pathname=e,r}var Ja,qr,lo,Hr,Wr,co,zr,uo,Vr,ho,Kr,fo,Gr,po,Yr,mo,St,go,ze,Qa,Xa,Za,el,tl,rl,nl,il,ol,sl,al,Jr,ll,cl,ul,dl,hl,fl,Nd=Ye(()=>{le(),ue(),ce(),Xu(),pd(),Ad(),za(),Ja=Object.freeze(Object.create(null)),qr={},lo=!1,Hr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Wr={},co=!1,zr={},uo=!1,Vr={},ho=!1,Kr={},fo=!1,Gr={},po=!1,Yr={},mo=!1,St={},go=!1,ze=Md(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Qa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Ya,ze.fileURLToPath=Ga,Xa=ze.Url,Za=ze.format,el=ze.resolve,tl=ze.resolveObject,rl=ze.parse,nl=ze.URL,il=92,ol=47,sl=97,al=122,Jr=Qa==="win32",ll=/\//g,cl=/%/g,ul=/\\/g,dl=/\n/g,hl=/\r/g,fl=/\t/g}),jd=pe((s,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),bo=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Ot(),t=(Fe(),Re($e));function r(n,i){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),Qr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=(Fe(),Re($e)),r=e(jd()),o=e(pt()),n=Ot(),i=e(Er()),a=bo(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function f(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=f(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=I,k.socket=S):(k=new a.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function O(Y,V,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=V,$._flush=re,$}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,k.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function ae(Y){S.close(),Y()}return k};s.browserStreamBuilder=y}),yo={};Bt(yo,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>pl,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var pl,ml=Ye(()=>{le(),ue(),ce(),pl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),gl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),bl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((ml(),Re(yo))),r=e(pt()),o=e(gl()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};s.default=i}),yl={};Bt(yl,{default:()=>vl});var vl,Ud=Ye(()=>{le(),ue(),ce(),vl={}}),wl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(Ud(),Re(yl)),r=e((ml(),Re(yo))),o=e(pt()),n=e(gl()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:f,...g}=c;if(f!==void 0){let h=(0,n.default)(u,d,f,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",f)});function f(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",f),d};s.default=l}),kl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i;function a(){let f=new t.Transform;return f._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},f._flush=g=>{o.close({success(){g()}})},f}function l(f){f.hostname||(f.hostname="localhost"),f.path||(f.path="/"),f.wsOptions||(f.wsOptions={})}function c(f,g){let h=f.protocol==="wxs"?"wss":"ws",b=`${h}://${f.hostname}${f.path}`;return f.port&&f.port!==80&&f.port!==443&&(b=`${h}://${f.hostname}:${f.port}${f.path}`),typeof f.transformWsUrl=="function"&&(b=f.transformWsUrl(b,f,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(f=>{let{data:g}=f;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(f=>{let g=new Error(f.errMsg);i.destroy(g)})}var d=(f,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,f);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),i=new r.BufferedDuplex(g,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=d}),_l=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var f=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(h,n,o),d(),i};s.default=f}),Bd=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Nd(),Re(Va))),o=e(_i()),n=e(Er());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(d){let f;if(d.auth)if(f=d.auth.match(/^(.+):(.+)$/),f){let[,g,h]=f;d.username=g,d.password=h}else d.username=d.auth}function c(d,f){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!f&&(f=d,d=""),f=f||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,f={...y,...f},!f.protocol)throw new Error("Missing protocol");f.protocol=f.protocol.replace(/:$/,"")}if(f.unixSocket=f.unixSocket||f.protocol?.includes("+unix"),f.unixSocket?f.protocol=f.protocol.replace("+unix",""):!f.protocol?.startsWith("ws")&&!f.protocol?.startsWith("wx")&&delete f.path,l(f),f.query&&typeof f.query.clientId=="string"&&(f.clientId=f.query.clientId),n.default||f.unixSocket?f.socksProxy=void 0:f.socksProxy===void 0&&typeof Ne<"u"&&(f.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),f.cert&&f.key)if(f.protocol){if(["mqtts","wss","wxs","alis"].indexOf(f.protocol)===-1)switch(f.protocol){case"mqtt":f.protocol="mqtts";break;case"ws":f.protocol="wss";break;case"wx":f.protocol="wxs";break;case"ali":f.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${f.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!f.forceNativeWebSocket?(a.ws=Qr().streamBuilder,a.wss=Qr().streamBuilder,a.mqtt=bl().default,a.tcp=bl().default,a.ssl=wl().default,a.tls=a.ssl,a.mqtts=wl().default):(a.ws=Qr().browserStreamBuilder,a.wss=Qr().browserStreamBuilder,a.wx=kl().default,a.wxs=kl().default,a.ali=_l().default,a.alis=_l().default)),!a[f.protocol]){let b=["mqtts","wss"].indexOf(f.protocol)!==-1;f.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(f.clean===!1&&!f.clientId)throw new Error("Missing clientId for unclean clients");f.protocol&&(f.defaultProtocol=f.protocol);function g(b){return f.servers&&((!b._reconnectCount||b._reconnectCount===f.servers.length)&&(b._reconnectCount=0),f.host=f.servers[b._reconnectCount].host,f.port=f.servers[b._reconnectCount].port,f.protocol=f.servers[b._reconnectCount].protocol?f.servers[b._reconnectCount].protocol:f.defaultProtocol,f.hostname=f.host,b._reconnectCount++),i("calling streambuilder for",f.protocol),a[f.protocol](b,f)}let h=new o.default(g,f);return h.on("error",()=>{}),h}function u(d,f,g=!0){return new Promise((h,b)=>{let y=c(d,f),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}s.default=c}),xl=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=s&&s.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=s&&s.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),o=s&&s.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Ps());s.DefaultMessageIdProvider=a.default;var l=n(Ju());s.UniqueMessageIdProvider=l.default;var c=n(xs());s.Store=c.default;var u=r(Bd());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Us());s.KeepaliveManager=d.default,s.Client=i.default,o(_i(),s),o(qt(),s),o(_s(),s);var f=xr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return f.ReasonCodes}})}),Dd=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(xl());s.default=n,o(xl(),s)});const $d=Dd();const Fd={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},qd=300,Hd={templateId:"7",type:"link",isDeepLink:!0},Wd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Sl{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Fd,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,f)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:f?.message}),l(()=>i(f??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=$d.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,f)=>{this.dispatchInbound(d,f)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Hd,...this.config.fileTemplate??{},...zd(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=qd){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),f={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(f)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Wd,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function zd(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function El(s,e){return(s.sender??"").toString()===e}function Al(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function vo(s){const e={raw:s},t=s.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Il(s){const e=vo(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Tl(s,e,t){const r=Al(s,t),o=vo(s),n=Il(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Vd(s.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function Vd(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class Cl extends mr{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Fo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new qo,this.conversationManager=new Ko(e.conversationId),this.usesAikaara()&&(this.connection=new $o(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Sl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Tl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Tl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(El(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Kd extends mr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Pl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Gd(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Yd(s,e,t){const r=Gd(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Pl[r]?Pl[r]:t}function wo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Jd(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Ol(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Yd(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=wo(c,i),d=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const f=await d.json().catch(()=>({})),g=Jd(f,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(wo(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:s.viewerTemplate?wo(s.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function ko(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[f,g]of Object.entries(n))r.append(f,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Qd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Ml(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Qd;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const f=await s.getToken();f&&(l.authorization=f)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Xd=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function Zd(s,e){const t=s||{},r={userId:zt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=_o(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Me(t.bizName)!==void 0||o>0;r.businessName=Me(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const a={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=xo(t.hpDetails,eh);l.length&&(r.hpDetails=l);const c=xo(t.salaryDetails,th);if(c.length){r.salaryIncome=c;const u=xo(t.salaryDetails,f=>({grossSalary:Ie(f.grossSalary),employerName:Me(f.employerName)}));u.length&&(r.salary=u);const d=Rl(t.salaryDetails)[0]??{};r.hraAmount=Ie(d.hraReceived),r.leaveTravelAllowanceAmount=Ie(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(d.leaveEncashment),r.anyOtherAllowanceAmount=Ie(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return Xr(r)}function eh(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:ah(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:_o(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:_o(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function th(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function rh(s,e){const t=[];for(const r of s){const o=Me(r.employerName),n=Me(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function nh(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),o=Me(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function ih(s,e){return{userId:zt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function oh(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function sh(s,e){const t=(o,n,i,a)=>{const l=Me(s[o]),c=Me(s[n]),u=Ie(s[i]),d=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function zt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function _o(s){return s===!0||s===!1?s:void 0}function ah(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Rl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function xo(s,e){return Rl(s).map(t=>Xr(e(t))).filter(t=>t!==void 0)}function Xr(s){if(Array.isArray(s)){const e=s.map(Xr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=Xr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function lh(s){const e=s&&typeof s=="object"?s:{},t={},r=qe(e.employers),o=qe(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(d=>{const f=So(d.salary),g=So(d.perquisites),h=So(d.profitsInLieuOfSalaryType),b=f+g+h,y=uh(d.allowance);return{employerName:Le(d.employerName),employerTan:Le(d.employerTAN),basicSalary:f||void 0,grossSalary:b||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:ch(d,o,r)??Ue(d.totalTdsDeposited)}}));const n=qe(e.houseProperties);n.length&&(t.hpDetails=n.map(d=>{const f=qe(d.loanDetails),g=f.length?f[0]:void 0,h=Ue(d.grossAnnualRentReceived),b=f.length?f.reduce((x,v)=>x+(Ue(v.interest)??0),0):void 0,y=qe(d.tenant),w=qe(d.coOwners),m=y[0],k=w[0];return{typeOfHouseProperty:Le(d.propertyType),loanTakenFrom:Le(g?.loanTakenFrom),lenderName:Le(g?.bankOrInstituteName),loanAccountNumber:Le(g?.loanAccountNo),sanctionDate:Le(g?.loanSanctionDate),totalLoanAmount:Ue(g?.totalLoanAmount),outstandingAmount:Ue(g?.loanOutstandingAmount),homeLoanInterest:b,homeLoanPrinciple:void 0,housePropertyAddress:Le(d.address),housePropertyPincode:Le(d.pinCode),rentalIncome:h,nameOfTenant:Le(m?.name),propertyTax:Ue(d.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Le(k?.name),coOwnerPan:Le(k?.panNumber),coOwnerShare:Ue(k?.share)?.toString()}})),t.us80cAmount=Lt(qe(e.deductionUS80CDetails).map(d=>Ue(d.amount))),t.us80dForSelfAndFamilyAmount=Lt(qe(e.deductionUS80DDetails).map(d=>Ue(d.healthInsuranceAmount)));const i=qe(e.incomes),a=d=>Lt(i.filter(f=>Le(f.incomeType)===d).map(f=>Ue(f.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Lt(qe(e.dividendIncomes).map(d=>Ue(d.income)));const l=e.business;if(l){const d=qe(l.presumptiveIncomes),f=b=>{const y=qe(b.incomes),w=m=>Ue(y.find(k=>Le(k.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Le(b.businessType)?.toUpperCase().includes("PROFESSION")},g=b=>d.find(y=>f(y)===b),h=(b,y)=>{if(!b)return;const w=qe(b.incomes),m=x=>Ue(w.find(v=>Le(v.incomeType)===x)?.receipts),k=m("BANK")||m("ANY_OTHER");t[y.name]=Le(b.businessType),t[y.nature]=Le(b.natureOfBusiness),t[y.bank]=k||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Lt(w.map(x=>Ue(x.presumptiveIncome)))||void 0};h(g(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),h(g(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=qe(e.capitalGain).filter(d=>Le(d.assetType)?.toUpperCase()==="VDA").flatMap(d=>qe(d.assetDetails));c.length&&(t.cryptoSellPrice=Lt(c.map(d=>Ue(d.sellValue))),t.cryptoPurchasePrice=Lt(c.map(d=>Ue(d.purchaseCost)))),t.agricultureIncome=Ue(e.agriculturalDetails?.income),t.aadhaarNumber=Le(e.aadharNumber);const u=qe(e.bankDetails)[0];return u&&(t.bankAccountNumber=Le(u.accountNumber),t.bankIfscCode=Le(u.ifsCode)),Ll(t)}function So(s){return qe(s).reduce((e,t)=>e+(Ue(t.taxableAmount)??0),0)}function ch(s,e,t){if(!e.length)return;const r=Le(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Le(n.deductorTAN)?.trim().toUpperCase()===r)return Ue(n.totalTdsDeposited)}const o=Le(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Le(n.deductorName)?.trim().toLowerCase()===o)return Ue(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ue(e[0].totalTdsDeposited)}function uh(s){const e=qe(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ue(i.exemptAmount)??Ue(i.allowanceAmount);switch(Le(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ue(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Lt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function qe(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ue(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Le(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Ll(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Ll(o):o):e[t]=r);return e}function Eo(){if(typeof window>"u")return null;const s=window,e=s.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=s.__aikaara_descriptor__??{},r=yh(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=vh(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):kh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:wh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||_h(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function dh(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return lh(Ao(await r.json().catch(()=>({}))))}async function hh(s,e){const t=await s.getToken(),r=s.userId,o={...Zd(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ao(await a.json().catch(()=>({})))}async function fh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function ph(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function mh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function gh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function bh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function sr(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Ao(await n.json().catch(()=>({})))}function yh(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function vh(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function wh(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function kh(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Ao(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function _h(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class xh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Cl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Xd,data:{}});const t=Eo();if(!(!t||!t.baseUrl))try{const r=await dh(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=Eo();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=rh(n,o);i&&await fh(r,i)}else if(e==="bank-details"){const n=nh(t,o);n&&await ph(r,n)}else if(e==="other-sources")await mh(r,ih(t,o));else if(e==="business-profession"){const n=sh(t,o);n&&await gh(r,n)}else if(e==="crypto-income"){const n=oh(t,o);n&&await bh(r,n)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Eo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await hh(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class Nl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Oc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Bo,position:this.getAttribute("position")||this._config.position||Pc,width:Number(this.getAttribute("width"))||this._config.width||Ac,height:Number(this.getAttribute("height"))||this._config.height||Ic,fontFamily:this._config.fontFamily||Cc,borderRadius:this._config.borderRadius??Tc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Do,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Mc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
6
|
+
`+ie.prev}function _e(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Te=0;Te<z.length;Te++)Ae[Te]=oe(z,Te)?ie(z[Te],z):""}var Oe=typeof T=="function"?T(z):[],nt;if(D){nt={};for(var it=0;it<Oe.length;it++)nt["$"+Oe[it]]=Oe[it]}for(var Ve in z)oe(z,Ve)&&(Ee&&String(Number(Ve))===Ve&&Ve<z.length||D&&nt["$"+Ve]instanceof Symbol||(E.call(/[^\w$]/,Ve)?Ae.push(ie(Ve,z)+": "+ie(z[Ve],z)):Ae.push(Ve+": "+ie(z[Ve],z))));if(typeof T=="function")for(var ot=0;ot<Oe.length;ot++)ae.call(z,Oe[ot])&&Ae.push("["+ie(Oe[ot])+"]: "+ie(z[Oe[ot]],z));return Ae}return qr}function Cd(){if(co)return Wr;co=!0;var s=Ht(),e=pd(),t=Td(),r=ir(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),f=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=f(y,w);return m&&m.value},h=function(y,w,m){var k=f(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!f(y,w)};return Wr=function(){var y,w,m,k={assert:function(x){if(!k.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return i(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),h(m,x,v))}};return k},Wr}function ao(){if(uo)return zr;uo=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return zr={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},zr}function Ka(){if(ho)return Vr;ho=!0;var s=ao(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},i=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,k):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,k):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,P=[],O=0;O<I.length;++O){var j=I.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===s.RFC1738&&(j===40||j===41)){P[P.length]=I.charAt(O);continue}if(j<128){P[P.length]=r[j];continue}if(j<2048){P[P.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){P[P.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=P.join("")}return E},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},f=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},h=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Vr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:f,maybeMap:b,merge:i},Vr}function Pd(){if(fo)return Kr;fo=!0;var s=Cd(),e=Ka(),t=ao(),r=Object.prototype.hasOwnProperty,o={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,i=Array.prototype.push,a=function(b,y){i.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},f={},g=function b(y,w,m,k,x,v,E,S,I,P,O,j,T,q,D,U,ae,Y){for(var V=y,re=Y,$=0,Z=!1;(re=re.get(f))!==void 0&&!Z;){var M=re.get(y);if($+=1,typeof M<"u"){if(M===$)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(f)>"u"&&($=0)}if(typeof P=="function"?V=P(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(d(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var K=S?w.replace(/\./g,"%2E"):w,N=k&&n(V)&&V.length===1?K+"[]":K;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],G=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&G===null)){var J=j&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,$);var oe=s();oe.set(f,Y),a(be,b(G,ge,m,k,x,v,E,S,m==="comma"&&U&&n(V)?null:I,P,O,j,T,q,D,U,ae,oe))}}return be},h=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return Kr=function(b,y){var w=b,m=h(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=s(),P=0;P<k.length;++P){var O=k[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},Kr}function Od(){if(po)return Gr;po=!0;var s=Ka(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:s.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(f){return f.replace(/&#(\d+);/g,function(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(f,g){return f&&typeof f=="string"&&g.comma&&f.indexOf(",")>-1?f.split(","):f},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,g){var h={__proto__:null},b=g.ignoreQueryPrefix?f.replace(/^\?/,""):f;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===i&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,P;S===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,x,"key"),P=s.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(h,I);O&&g.duplicates==="combine"?h[I]=s.combine(h[I],P):(!O||g.duplicates==="last")&&(h[I]=P)}return h},c=function(f,g,h,b){for(var y=b?g:n(g,h),w=f.length-1;w>=0;--w){var m,k=f[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(E)&&k!==v&&String(E)===v&&E>=0&&h.parseArrays&&E<=h.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(f,g,h,b){if(f){var y=h.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!h.plainObjects&&e.call(Object.prototype,x)&&!h.allowPrototypes)return;v.push(x)}for(var E=0;h.depth>0&&(k=m.exec(y))!==null&&E<h.depth;){if(E+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=function(f){if(!f)return r;if(typeof f.allowEmptyArrays<"u"&&typeof f.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof f.decodeDotInKeys<"u"&&typeof f.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(f.decoder!==null&&typeof f.decoder<"u"&&typeof f.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof f.charset<"u"&&f.charset!=="utf-8"&&f.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof f.charset>"u"?r.charset:f.charset,h=typeof f.duplicates>"u"?r.duplicates:f.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:r.allowDots:!!f.allowDots;return{allowDots:b,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:r.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:r.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:r.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:r.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:r.decoder,delimiter:typeof f.delimiter=="string"||s.isRegExp(f.delimiter)?f.delimiter:r.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:r.depth,duplicates:h,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:r.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:r.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:r.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:r.strictNullHandling}};return Gr=function(f,g){var h=d(g);if(f===""||f===null||typeof f>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof f=="string"?l(f,h):f,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],h,typeof f=="string");y=s.merge(y,x,h)}return h.allowSparse===!0?y:s.compact(y)},Gr}function Md(){if(mo)return Yr;mo=!0;var s=Pd(),e=Od(),t=ao();return Yr={formats:t,parse:e,stringify:s},Yr}function Rd(){if(go)return St;go=!0;var s=_t;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
+
`," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,f=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},h={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=Md();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(P);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=o.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&h[D])&&(T=T.substr(2),this.slashes=!0)}if(!h[D]&&(ae||D&&!b[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var $,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&($=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent($)),Y=-1;for(var V=0;V<l.length;V++){var re=T.indexOf(l[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,be=Q.length;V<be;V++){var te=Q[V];if(te&&!te.match(d)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(d)){var ne=Q.slice(0,V),W=Q.slice(V+1),G=te.match(f);G&&(ne.push(G[1]),W.unshift(G[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var V=0,be=a.length;V<be;V++){var oe=a[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var F=T.indexOf("#");F!==-1&&(this.hash=T.substr(F),T=T.slice(0,F));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),b[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",he=this.search||"";this.path=J+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",I=this.hash||"",P=!1,O="";this.host?P=v+this.host:this.hostname&&(P=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(P+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||O&&"?"+O||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||b[E])&&P!==!1?(P="//"+(P||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+P+S+j+I};function k(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var q=j[T];q!=="protocol"&&(S[q]=v[q])}return b[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!b[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!h[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",$=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=$||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!b[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||Q[0]==="")),$)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Q=be;else if(be.length)Q||(Q=[]),Q.pop(),Q=Q.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,W=Q.length;W>=0;W--)K=Q[W],K==="."?Q.splice(W,1):K===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},St.parse=w,St.resolve=k,St.resolveObject=x,St.format=m,St.Url=e,St}function Ga(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Jr?Ld(s):Nd(s)}function Ld(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(ll,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<sl||r>al||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Nd(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function Ya(s){let e=so.resolve(s),t=s.charCodeAt(s.length-1);(t===ol||Jr&&t===il)&&e[e.length-1]!==so.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(cl,"%25")),!Jr&&e.includes("\\")&&(e=e.replace(ul,"%5C")),e.includes(`
|
|
8
|
+
`)&&(e=e.replace(dl,"%0A")),e.includes("\r")&&(e=e.replace(hl,"%0D")),e.includes(" ")&&(e=e.replace(fl,"%09")),r.pathname=e,r}var Ja,qr,lo,Hr,Wr,co,zr,uo,Vr,ho,Kr,fo,Gr,po,Yr,mo,St,go,ze,Qa,Xa,Za,el,tl,rl,nl,il,ol,sl,al,Jr,ll,cl,ul,dl,hl,fl,jd=Ye(()=>{le(),ue(),ce(),Zu(),md(),Id(),za(),Ja=Object.freeze(Object.create(null)),qr={},lo=!1,Hr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Wr={},co=!1,zr={},uo=!1,Vr={},ho=!1,Kr={},fo=!1,Gr={},po=!1,Yr={},mo=!1,St={},go=!1,ze=Rd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Qa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Ya,ze.fileURLToPath=Ga,Xa=ze.Url,Za=ze.format,el=ze.resolve,tl=ze.resolveObject,rl=ze.parse,nl=ze.URL,il=92,ol=47,sl=97,al=122,Jr=Qa==="win32",ll=/\//g,cl=/%/g,ul=/\\/g,dl=/\n/g,hl=/\r/g,fl=/\t/g}),Ud=pe((s,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),bo=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Ot(),t=(Fe(),Re($e));function r(n,i){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),Qr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=(Fe(),Re($e)),r=e(Ud()),o=e(pt()),n=Ot(),i=e(Er()),a=bo(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function f(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=f(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=I,k.socket=S):(k=new a.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function O(Y,V,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=V,$._flush=re,$}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,k.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function ae(Y){S.close(),Y()}return k};s.browserStreamBuilder=y}),yo={};Bt(yo,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>pl,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var pl,ml=Ye(()=>{le(),ue(),ce(),pl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),gl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),bl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((ml(),Re(yo))),r=e(pt()),o=e(gl()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};s.default=i}),yl={};Bt(yl,{default:()=>vl});var vl,Bd=Ye(()=>{le(),ue(),ce(),vl={}}),wl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(Bd(),Re(yl)),r=e((ml(),Re(yo))),o=e(pt()),n=e(gl()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:f,...g}=c;if(f!==void 0){let h=(0,n.default)(u,d,f,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",f)});function f(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",f),d};s.default=l}),kl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i;function a(){let f=new t.Transform;return f._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},f._flush=g=>{o.close({success(){g()}})},f}function l(f){f.hostname||(f.hostname="localhost"),f.path||(f.path="/"),f.wsOptions||(f.wsOptions={})}function c(f,g){let h=f.protocol==="wxs"?"wss":"ws",b=`${h}://${f.hostname}${f.path}`;return f.port&&f.port!==80&&f.port!==443&&(b=`${h}://${f.hostname}:${f.port}${f.path}`),typeof f.transformWsUrl=="function"&&(b=f.transformWsUrl(b,f,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(f=>{let{data:g}=f;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(f=>{let g=new Error(f.errMsg);i.destroy(g)})}var d=(f,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,f);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),i=new r.BufferedDuplex(g,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=d}),_l=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,h)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var f=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(h,n,o),d(),i};s.default=f}),Dd=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((jd(),Re(Va))),o=e(_i()),n=e(Er());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(d){let f;if(d.auth)if(f=d.auth.match(/^(.+):(.+)$/),f){let[,g,h]=f;d.username=g,d.password=h}else d.username=d.auth}function c(d,f){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!f&&(f=d,d=""),f=f||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,f={...y,...f},!f.protocol)throw new Error("Missing protocol");f.protocol=f.protocol.replace(/:$/,"")}if(f.unixSocket=f.unixSocket||f.protocol?.includes("+unix"),f.unixSocket?f.protocol=f.protocol.replace("+unix",""):!f.protocol?.startsWith("ws")&&!f.protocol?.startsWith("wx")&&delete f.path,l(f),f.query&&typeof f.query.clientId=="string"&&(f.clientId=f.query.clientId),n.default||f.unixSocket?f.socksProxy=void 0:f.socksProxy===void 0&&typeof Ne<"u"&&(f.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),f.cert&&f.key)if(f.protocol){if(["mqtts","wss","wxs","alis"].indexOf(f.protocol)===-1)switch(f.protocol){case"mqtt":f.protocol="mqtts";break;case"ws":f.protocol="wss";break;case"wx":f.protocol="wxs";break;case"ali":f.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${f.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!f.forceNativeWebSocket?(a.ws=Qr().streamBuilder,a.wss=Qr().streamBuilder,a.mqtt=bl().default,a.tcp=bl().default,a.ssl=wl().default,a.tls=a.ssl,a.mqtts=wl().default):(a.ws=Qr().browserStreamBuilder,a.wss=Qr().browserStreamBuilder,a.wx=kl().default,a.wxs=kl().default,a.ali=_l().default,a.alis=_l().default)),!a[f.protocol]){let b=["mqtts","wss"].indexOf(f.protocol)!==-1;f.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(f.clean===!1&&!f.clientId)throw new Error("Missing clientId for unclean clients");f.protocol&&(f.defaultProtocol=f.protocol);function g(b){return f.servers&&((!b._reconnectCount||b._reconnectCount===f.servers.length)&&(b._reconnectCount=0),f.host=f.servers[b._reconnectCount].host,f.port=f.servers[b._reconnectCount].port,f.protocol=f.servers[b._reconnectCount].protocol?f.servers[b._reconnectCount].protocol:f.defaultProtocol,f.hostname=f.host,b._reconnectCount++),i("calling streambuilder for",f.protocol),a[f.protocol](b,f)}let h=new o.default(g,f);return h.on("error",()=>{}),h}function u(d,f,g=!0){return new Promise((h,b)=>{let y=c(d,f),w={connect:k=>{m(),h(y)},end:()=>{m(),h(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}s.default=c}),xl=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=s&&s.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=s&&s.__importStar||(function(){var g=function(h){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),o=s&&s.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Ps());s.DefaultMessageIdProvider=a.default;var l=n(Qu());s.UniqueMessageIdProvider=l.default;var c=n(xs());s.Store=c.default;var u=r(Dd());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Us());s.KeepaliveManager=d.default,s.Client=i.default,o(_i(),s),o(qt(),s),o(_s(),s);var f=xr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return f.ReasonCodes}})}),$d=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(xl());s.default=n,o(xl(),s)});const Fd=$d();const qd={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},Hd=300,Wd={templateId:"7",type:"link",isDeepLink:!0},zd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Sl{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...qd,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,f)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:f?.message}),l(()=>i(f??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Fd.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,f)=>{this.dispatchInbound(d,f)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Wd,...this.config.fileTemplate??{},...Vd(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Hd){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),f={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(f)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...zd,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Vd(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function El(s,e){return(s.sender??"").toString()===e}function Al(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function vo(s){const e={raw:s},t=s.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Il(s){const e=vo(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Tl(s,e,t){const r=Al(s,t),o=vo(s),n=Il(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Kd(s.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function Kd(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class Cl extends mr{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Fo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new qo,this.conversationManager=new Ko(e.conversationId),this.usesAikaara()&&(this.connection=new $o(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Sl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Tl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Tl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(El(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Gd extends mr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Pl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Yd(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Jd(s,e,t){const r=Yd(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Pl[r]?Pl[r]:t}function wo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Qd(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Ol(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Jd(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=wo(c,i),d=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const f=await d.json().catch(()=>({})),g=Qd(f,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(wo(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:s.viewerTemplate?wo(s.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function ko(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[f,g]of Object.entries(n))r.append(f,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Xd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Ml(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Xd;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const f=await s.getToken();f&&(l.authorization=f)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Zd=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name",required:!0},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account No.",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function eh(s,e){const t=s||{},r={userId:zt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Me(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:lh()};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=_o(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Me(t.bizName)!==void 0||o>0;r.businessName=Me(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const a={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=xo(t.hpDetails,th);l.length&&(r.hpDetails=l);const c=xo(t.salaryDetails,rh);if(c.length){r.salaryIncome=c;const u=xo(t.salaryDetails,f=>({grossSalary:Ie(f.grossSalary),employerName:Me(f.employerName)}));u.length&&(r.salary=u);const d=Rl(t.salaryDetails)[0]??{};r.hraAmount=Ie(d.hraReceived),r.leaveTravelAllowanceAmount=Ie(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(d.leaveEncashment),r.anyOtherAllowanceAmount=Ie(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return Xr(r)}function th(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:ch(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),loanOutstandingAmount:Ie(s.outstandingAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:_o(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:_o(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function rh(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function nh(s,e){const t=[];for(const r of s){const o=Me(r.employerName),n=Me(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function ih(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),o=Me(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function oh(s,e){return{userId:zt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function sh(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function ah(s,e){const t=(o,n,i,a)=>{const l=Me(s[o]),c=Me(s[n]),u=Ie(s[i]),d=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function zt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function _o(s){return s===!0||s===!1?s:void 0}function lh(){const s=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${s.getFullYear()}-${e(s.getMonth()+1)}-${e(s.getDate())}T${e(s.getHours())}:${e(s.getMinutes())}:${e(s.getSeconds())}.${e(s.getMilliseconds(),3)}`}function ch(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Rl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function xo(s,e){return Rl(s).map(t=>Xr(e(t))).filter(t=>t!==void 0)}function Xr(s){if(Array.isArray(s)){const e=s.map(Xr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=Xr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function uh(s){const e=s&&typeof s=="object"?s:{},t={},r=qe(e.employers),o=qe(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(d=>{const f=So(d.salary),g=So(d.perquisites),h=So(d.profitsInLieuOfSalaryType),b=f+g+h,y=fh(d.allowance);return{employerName:Le(d.employerName),employerTan:Le(d.employerTAN),basicSalary:f||void 0,grossSalary:b||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:hh(d,o,r)??Ue(d.totalTdsDeposited)}}));const n=qe(e.houseProperties);n.length&&(t.hpDetails=n.map(d=>{const f=qe(d.loanDetails),g=f.length?f[0]:void 0,h=Ue(d.grossAnnualRentReceived),b=f.length?f.reduce((x,v)=>x+(Ue(v.interest)??0),0):void 0,y=qe(d.tenant),w=qe(d.coOwners),m=y[0],k=w[0];return{typeOfHouseProperty:Le(d.propertyType),loanTakenFrom:Le(g?.loanTakenFrom),lenderName:Le(g?.bankOrInstituteName),loanAccountNumber:Le(g?.loanAccountNo),sanctionDate:dh(g?.loanSanctionDate),totalLoanAmount:Ue(g?.totalLoanAmount),outstandingAmount:Ue(g?.loanOutstandingAmount),homeLoanInterest:b,homeLoanPrinciple:void 0,housePropertyAddress:Le(d.address),housePropertyPincode:Le(d.pinCode),rentalIncome:h,nameOfTenant:Le(m?.name),propertyTax:Ue(d.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Le(k?.name),coOwnerPan:Le(k?.panNumber),coOwnerShare:Ue(k?.share)?.toString()}})),t.us80cAmount=Lt(qe(e.deductionUS80CDetails).map(d=>Ue(d.amount))),t.us80dForSelfAndFamilyAmount=Lt(qe(e.deductionUS80DDetails).map(d=>Ue(d.healthInsuranceAmount)));const i=qe(e.incomes),a=d=>Lt(i.filter(f=>Le(f.incomeType)===d).map(f=>Ue(f.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Lt(qe(e.dividendIncomes).map(d=>Ue(d.income)));const l=e.business;if(l){const d=qe(l.presumptiveIncomes),f=b=>{const y=qe(b.incomes),w=m=>Ue(y.find(k=>Le(k.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Le(b.businessType)?.toUpperCase().includes("PROFESSION")},g=b=>d.find(y=>f(y)===b),h=(b,y)=>{if(!b)return;const w=qe(b.incomes),m=x=>Ue(w.find(v=>Le(v.incomeType)===x)?.receipts),k=m("BANK")||m("ANY_OTHER");t[y.name]=Le(b.businessType),t[y.nature]=Le(b.natureOfBusiness),t[y.bank]=k||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Lt(w.map(x=>Ue(x.presumptiveIncome)))||void 0};h(g(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),h(g(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=qe(e.capitalGain).filter(d=>Le(d.assetType)?.toUpperCase()==="VDA").flatMap(d=>qe(d.assetDetails));c.length&&(t.cryptoSellPrice=Lt(c.map(d=>Ue(d.sellValue))),t.cryptoPurchasePrice=Lt(c.map(d=>Ue(d.purchaseCost)))),t.agricultureIncome=Ue(e.agriculturalDetails?.income),t.aadhaarNumber=Le(e.aadharNumber);const u=qe(e.bankDetails)[0];return u&&(t.bankAccountNumber=Le(u.accountNumber),t.bankIfscCode=Le(u.ifsCode)),Ll(t)}function dh(s){const e=Le(s);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function So(s){return qe(s).reduce((e,t)=>e+(Ue(t.taxableAmount)??0),0)}function hh(s,e,t){if(!e.length)return;const r=Le(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Le(n.deductorTAN)?.trim().toUpperCase()===r)return Ue(n.totalTdsDeposited)}const o=Le(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Le(n.deductorName)?.trim().toLowerCase()===o)return Ue(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ue(e[0].totalTdsDeposited)}function fh(s){const e=qe(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ue(i.exemptAmount)??Ue(i.allowanceAmount);switch(Le(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ue(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Lt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function qe(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ue(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Le(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Ll(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Ll(o):o):e[t]=r);return e}function Eo(){if(typeof window>"u")return null;const s=window,e=s.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=s.__aikaara_descriptor__??{},r=wh(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=kh(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):xh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:_h(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Sh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function ph(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return uh(Ao(await r.json().catch(()=>({}))))}async function Nl(s,e){const t=await s.getToken(),r=s.userId,o={...eh(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ao(await a.json().catch(()=>({})))}async function mh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function gh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function bh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function yh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function vh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function sr(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Ao(await n.json().catch(()=>({})))}function wh(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function kh(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function _h(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function xh(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Ao(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Sh(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class Eh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Cl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Zd,data:{}});const t=Eo();if(!(!t||!t.baseUrl))try{const r=await ph(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=Eo();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=nh(n,o);i&&await mh(r,i)}else if(e==="bank-details"){const n=ih(t,o);n&&await gh(r,n)}else if(e==="other-sources")await bh(r,oh(t,o));else if(e==="business-profession"){const n=ah(t,o);n&&await yh(r,n)}else if(e==="crypto-income"){const n=sh(t,o);n&&await vh(r,n)}else e==="house-property"&&await Nl(r,t)}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Eo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Nl(t,e)}catch(r){console.warn("[smart-edit] save failed",r),this.errorBanner.show("Failed to save your ITR details. Please try again.",4e3)}}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class jl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Mc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Bo,position:this.getAttribute("position")||this._config.position||Oc,width:Number(this.getAttribute("width"))||this._config.width||Ic,height:Number(this.getAttribute("height"))||this._config.height||Tc,fontFamily:this._config.fontFamily||Pc,borderRadius:this._config.borderRadius??Cc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Do,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Rc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
|
@@ -119,7 +119,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
119
119
|
></aikaara-chat-input>
|
|
120
120
|
<aikaara-error-banner></aikaara-error-banner>
|
|
121
121
|
</div>
|
|
122
|
-
`;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new
|
|
122
|
+
`;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new Eh(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),o=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|o<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Ul extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
|
|
123
123
|
<style>
|
|
124
124
|
.bubble {
|
|
125
125
|
width: var(--aikaara-bubble-size, 60px);
|
|
@@ -154,7 +154,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
154
154
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
|
155
155
|
</svg>
|
|
156
156
|
</button>
|
|
157
|
-
`}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const
|
|
157
|
+
`}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const Ah=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Bl extends HTMLElement{shadow;actions=Ah;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const o=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:o,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),o=this.getAttribute("status")||"connected",n=o==="connected"?"#10b981":o==="connecting"||o==="reconnecting"?"#f59e0b":"#ef4444",i=this.actions.map(a=>`
|
|
158
158
|
<button class="menu-item" type="button" data-action-id="${a.id}" data-action-label="${a.label}">
|
|
159
159
|
<span class="menu-item-icon">${this.iconSvg(a.icon)}</span>
|
|
160
160
|
<span class="menu-item-label">${a.label}</span>
|
|
@@ -314,7 +314,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
314
314
|
</button>
|
|
315
315
|
</div>
|
|
316
316
|
</div>
|
|
317
|
-
`}setStatus(e){this.setAttribute("status",e)}}const
|
|
317
|
+
`}setStatus(e){this.setAttribute("status",e)}}const Ih=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Th=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Ch={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function Ph(s){return s.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Ch[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&/gi,"&")}function Vt(s){if(Ih.test(s))return s;const e=Th.test(s)?Ph(s):s;let t=Oh(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,o,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,o,n)=>{const i=/[.,!?;:]+$/.exec(n),a=i?i[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function Oh(s){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return s.replace(/[&<>"']/g,t=>e[t])}const Mh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Rh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Kt(s){const e=document.createElement("template");return e.innerHTML=s,Dl(e.content),e.innerHTML}function Dl(s){const e=Array.from(s.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!Mh.has(o)){const a=document.createTextNode(r.textContent||"");s.replaceChild(a,t);continue}const n=Rh[o]||new Set,i=Array.from(r.attributes);for(const a of i)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}Dl(t)}}function $l(s,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),i=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(s,"aikaara_popup",`width=${t},height=${r},left=${n},top=${i},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const d=u.data?.type;o&&typeof d=="string"&&!o.includes(d)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function Lh(s){const e=Date.now()-s.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const o=Math.round(r/60);if(o<24)return`${o} hr ago`;const n=Math.round(o/24);return n===1?"Yesterday":n<7?`${n} d ago`:s.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Fl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(o=>r.includes(o)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(i=>i&&i.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(i=>ql(r.href,i.match));r.target==="_self"&&!o||t.some(i=>{if(!i||!i.classList)return!1;const a=i.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
|
|
318
318
|
<style>
|
|
319
319
|
:host {
|
|
320
320
|
display: flex;
|
|
@@ -475,7 +475,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
475
475
|
}
|
|
476
476
|
</style>
|
|
477
477
|
<div class="message-list"></div>
|
|
478
|
-
`,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Kt(Vt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const a=
|
|
478
|
+
`,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Kt(Vt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const i=n.metadata?.attributes?.action;if(i){const a=Nh(i);if(i.message_id&&t.set(i.message_id,a),Object.keys(a).length>0)for(let l=o-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,d=t.get(u);(!d||Object.keys(d).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&o<r){const i=n.externalId??n.id;t.has(i)||t.set(i,{})}}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Kt(Vt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const d=document.createElement("div");d.classList.add("message-wrap","system"),d.dataset.messageId=e.id,e.externalId&&(d.dataset.externalId=e.externalId);const f=document.createElement("aikaara-system-pill");f.setAttribute("text",e.content),d.appendChild(f),this.container.appendChild(d);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const o=document.createElement("div");o.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:i?e.content&&(o.innerHTML=Kt(Vt(e.content))):(o.innerHTML=Kt(Vt(e.content||"")),e.status==="streaming"&&o.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const d=document.createElement("aikaara-template-renderer");d.setAttribute("content-type",e.template.contentType),e.template.templateId&&d.setAttribute("template-id",e.template.templateId);const f=e.externalId??e.id;f&&d.setAttribute("message-id",f),d.setPayload(e.template.payload),t!==void 0&&(d.dataset.consumed="true",Object.keys(t).length>0&&d.setConsumedValues?.(t)),this.templateLayout==="outside"?(d.classList.add("template-outside"),a=d):o.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const f of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const h={elements:[{description:f.fileName,action:{url:f.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(h,""),d.appendChild(g)}o.appendChild(d)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const d=document.createElement("div");if(d.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(d.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const f=document.createElement("span");f.classList.add("status-tick"),e.status==="read"&&f.classList.add("read"),f.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(f)}r.appendChild(d)}r.childNodes.length>0&&this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return Lh(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(g=>ql(e,g.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){$l(e);return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const a=jh(e),l=Hl(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const g=await this.getLinkBearer(u);g&&(c.authorization=`Bearer ${g}`)}const d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify(Io(r.fetch.body,a)));let f=null;try{const g=await fetch(l,d);g.ok&&(f=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,g=>{const h=r.props??{setData:f};for(const[y,w]of Object.entries(h)){const m=g[y];typeof m=="function"&&m.call(g,w)}const b=y=>{const w=y,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};g.addEventListener("aikaara-plan-select",b),g.addEventListener("aikaara-select",b)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Nh(s){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function ql(s,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(s)}function jh(s){try{const e=new URL(s),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function Hl(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Io(s,e){if(typeof s=="string")return Hl(s,e);if(Array.isArray(s))return s.map(t=>Io(t,e));if(s&&typeof s=="object"){const t={};for(const[r,o]of Object.entries(s))t[r]=Io(o,e);return t}return s}class Wl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",o=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Kt(Vt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
479
479
|
<style>
|
|
480
480
|
:host { display: flex; flex-direction: column; }
|
|
481
481
|
:host([role="user"]) { align-items: flex-end; }
|
|
@@ -543,7 +543,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
543
543
|
${n?`<aikaara-template-renderer
|
|
544
544
|
content-type="${n}"
|
|
545
545
|
template-id="${i}"
|
|
546
|
-
inner-message="${
|
|
546
|
+
inner-message="${zl(a)}"
|
|
547
547
|
></aikaara-template-renderer>`:""}
|
|
548
548
|
${this.renderAttachments()}
|
|
549
549
|
</div>
|
|
@@ -552,9 +552,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
552
552
|
${r}${c?`<span class="status">${u}</span>`:""}
|
|
553
553
|
</div>
|
|
554
554
|
`:""}
|
|
555
|
-
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",f=>{this.dispatchEvent(new CustomEvent("message-action",{detail:f.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${
|
|
556
|
-
📎 ${
|
|
557
|
-
</a>`).join("")}</div>`:""}}function
|
|
555
|
+
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",f=>{this.dispatchEvent(new CustomEvent("message-action",{detail:f.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${zl(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
|
+
📎 ${Uh(t.fileName)}
|
|
557
|
+
</a>`).join("")}</div>`:""}}function zl(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Uh(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Vl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",o=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",a=t?`
|
|
558
558
|
<button class="attach-btn" aria-label="Attach file" type="button">
|
|
559
559
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
560
560
|
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
|
|
@@ -632,7 +632,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
632
632
|
${n?a:""}
|
|
633
633
|
${l}
|
|
634
634
|
</div>
|
|
635
|
-
`,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class
|
|
635
|
+
`,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class Kl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
636
636
|
<style>
|
|
637
637
|
:host { display: none; }
|
|
638
638
|
:host([visible]) { display: block; }
|
|
@@ -666,7 +666,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
666
666
|
<span class="dot"></span>
|
|
667
667
|
<span class="dot"></span>
|
|
668
668
|
</div>
|
|
669
|
-
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class
|
|
669
|
+
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Gl extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
670
670
|
<style>
|
|
671
671
|
:host {
|
|
672
672
|
display: flex;
|
|
@@ -715,7 +715,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
715
715
|
}
|
|
716
716
|
</style>
|
|
717
717
|
<div class="bubble cursor"></div>
|
|
718
|
-
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Kt(Vt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class
|
|
718
|
+
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Kt(Vt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Yl extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
719
719
|
<style>
|
|
720
720
|
.banner {
|
|
721
721
|
display: none;
|
|
@@ -743,7 +743,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
743
743
|
<span class="message"></span>
|
|
744
744
|
<button class="dismiss">Dismiss</button>
|
|
745
745
|
</div>
|
|
746
|
-
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const To=new Map;function
|
|
746
|
+
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const To=new Map;function Jl(s){const e=To.get(s);if(e)return e;const t=new Promise((r,o)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(s)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error(`Failed to load ${s}`)),{once:!0}));return}const i=document.createElement("script");i.src=s,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=s,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{To.delete(s),o(new Error(`Failed to load ${s}`))},{once:!0}),document.head.appendChild(i)});return To.set(s,t),t}function Bh(s,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${s}> not registered within ${e}ms`)),e);customElements.whenDefined(s).then(()=>{clearTimeout(o),t()})})}const Dh={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>$f).then(({registerAikaaraPaymentLink:s})=>s())};function $h(s){const e=`template:${s}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[s]}class Fh extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const o=Wh(t.attributes.action);if(Object.keys(o).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(o))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const o=localStorage.getItem(`aikaara_form:${r}`);o&&(e=JSON.parse(o))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o,i=n.getName?.();i&&r[i]?.length&&n.setPreSelected?.(r[i])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
|
|
747
747
|
<style>
|
|
748
748
|
:host { display: block; }
|
|
749
749
|
::slotted(*) { display: block; }
|
|
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
757
757
|
}
|
|
758
758
|
</style>
|
|
759
759
|
<slot></slot>
|
|
760
|
-
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t
|
|
760
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?$h(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Dh[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&Jl(r.scriptUrl).then(()=>Bh(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof i[a]=="function")try{i[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:i.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of i)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>Wf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Hh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const qh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Hh(s){const e={};for(const[t,r]of Object.entries(s))qh.has(t)||(e[t]=r);return e}function Wh(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class zh extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
|
|
761
761
|
<style>
|
|
762
762
|
:host {
|
|
763
763
|
display: flex;
|
|
@@ -782,9 +782,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
782
782
|
color: var(--aikaara-text-secondary, #9ca3af);
|
|
783
783
|
}
|
|
784
784
|
</style>
|
|
785
|
-
<span class="pill">${
|
|
786
|
-
${t?`<span class="sub">${
|
|
787
|
-
`}}function
|
|
785
|
+
<span class="pill">${Ql(e)}</span>
|
|
786
|
+
${t?`<span class="sub">${Ql(t)}</span>`:""}
|
|
787
|
+
`}}function Ql(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Vh extends HTMLElement{shadow;data=null;selected=new Set;preSelectedDisabled=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.preSelectedDisabled=!1,this.render()}getName(){return this.data?.name??""}setPreSelected(e){this.selected=new Set(e),this.preSelectedDisabled=!0,this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,o=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],a=this.selected.has(i.value),l=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
|
|
788
788
|
<style>
|
|
789
789
|
:host { display: block; margin: 8px 0; }
|
|
790
790
|
.row {
|
|
@@ -921,7 +921,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
921
921
|
${Nt(i.label)}
|
|
922
922
|
</button>`).join("")}
|
|
923
923
|
</div>
|
|
924
|
-
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Nt(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function Co(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class
|
|
924
|
+
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Nt(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function Co(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Kh extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;if(!t)return e;let r=!0;return t.querySelectorAll("aikaara-text-input").forEach(o=>{(o.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(o=>{const n=o.getValues?.();n?.name&&(e[n.name]=n.values[0]??"")}),e):null}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues();if(t===null)return;const r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
|
|
925
925
|
<style>
|
|
926
926
|
:host { display: block; margin: 12px 0 4px; }
|
|
927
927
|
button {
|
|
@@ -939,8 +939,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
939
939
|
button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
|
|
940
940
|
button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
|
|
941
941
|
</style>
|
|
942
|
-
<button type="button">${
|
|
943
|
-
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function
|
|
942
|
+
<button type="button">${Gh(e)}</button>
|
|
943
|
+
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Gh(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Yh extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
|
|
944
944
|
<style>
|
|
945
945
|
:host { all: initial; }
|
|
946
946
|
.overlay {
|
|
@@ -988,7 +988,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
988
988
|
</div>
|
|
989
989
|
</div>
|
|
990
990
|
</div>
|
|
991
|
-
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Po(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class
|
|
991
|
+
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Po(s){return String(s).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Jh extends HTMLElement{shadow;data=null;_value="";_error="";_touched=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}getValues(){return{name:this.data?.label??"",values:[this._value],type:"text"}}validate(){this._touched=!0;const e=this._computeError(this._value);return this._error=e,this._updateError(),!e}_computeError(e){if(!this.data)return"";if(this.data.required&&!e.trim())return this.data.validation?.errorText??`${this.data.label} is required`;if(e&&this.data.validation?.regex)try{if(!new RegExp(this.data.validation.regex).test(e))return this.data.validation.errorText}catch{}return""}_updateError(){const e=this.shadow.querySelector(".error");e&&(e.textContent=this._error);const t=this.shadow.querySelector("input");t&&t.setAttribute("aria-invalid",this._error?"true":"false")}render(){if(!this.data){this.shadow.innerHTML="";return}const{label:e,placeholder:t="",required:r=!1}=this.data,o=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
|
|
992
992
|
<style>
|
|
993
993
|
:host { display: block; margin-bottom: 12px; }
|
|
994
994
|
label {
|
|
@@ -1031,7 +1031,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1031
1031
|
aria-invalid="false"
|
|
1032
1032
|
/>
|
|
1033
1033
|
<div class="error" role="alert">${ar(this._error)}</div>
|
|
1034
|
-
`;const n=this.shadow.querySelector("input");n.addEventListener("input",()=>{this._value=n.value,this._touched&&(this._error=this._computeError(this._value),this._updateError())}),n.addEventListener("blur",()=>{!this._touched&&this._value&&(this._touched=!0,this._error=this._computeError(this._value),this._updateError())})}}function ar(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class
|
|
1034
|
+
`;const n=this.shadow.querySelector("input");n.addEventListener("input",()=>{this._value=n.value,this._touched&&(this._error=this._computeError(this._value),this._updateError())}),n.addEventListener("blur",()=>{!this._touched&&this._value&&(this._touched=!0,this._error=this._computeError(this._value),this._updateError())})}}function ar(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Qh extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),o=this.tokenGetter??r;if(!o){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);a&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await hc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:l,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:o,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Xh extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let o=!1;this.iframe.addEventListener("load",()=>{o=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{o||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const o=this.shadow.querySelector(".modal-title");o&&(o.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
|
|
1035
1035
|
<style>
|
|
1036
1036
|
:host { display: block; }
|
|
1037
1037
|
.backdrop {
|
|
@@ -1081,7 +1081,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1081
1081
|
<div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
|
|
1082
1082
|
</div>
|
|
1083
1083
|
</div>
|
|
1084
|
-
`,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const
|
|
1084
|
+
`,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const Zh=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],ef=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class tf extends HTMLElement{shadow;data=null;columns=ef;features=Zh;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
|
|
1085
1085
|
<style>
|
|
1086
1086
|
:host {
|
|
1087
1087
|
display: block;
|
|
@@ -1158,14 +1158,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1158
1158
|
<small>Tap to select</small>
|
|
1159
1159
|
</button>`}).join("")}
|
|
1160
1160
|
</div>
|
|
1161
|
-
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const o=Number(r.dataset.col),n=e[o];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Oo(s){return s.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class
|
|
1161
|
+
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const o=Number(r.dataset.col),n=e[o];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Oo(s){return s.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class rf extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),o=r?t.slice(0,-2):t,n=this.data[o];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(o=>o.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
|
|
1162
1162
|
<span class="header-spacer"></span>
|
|
1163
1163
|
<div class="modal-title">Correct Your ITR Details</div>
|
|
1164
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1164
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${Xl}</button>
|
|
1165
1165
|
`;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(i=>`
|
|
1166
|
-
<button class="chip" type="button" data-section-id="${
|
|
1166
|
+
<button class="chip" type="button" data-section-id="${of(i.id)}">
|
|
1167
1167
|
<span class="chip-icon">${i.icon??"📄"}</span>
|
|
1168
|
-
<span class="chip-label">${
|
|
1168
|
+
<span class="chip-label">${Zl(i.title)}</span>
|
|
1169
1169
|
</button>`).join("");r.innerHTML=`
|
|
1170
1170
|
<div class="picker">
|
|
1171
1171
|
<div class="intro-card">
|
|
@@ -1180,9 +1180,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1180
1180
|
`;const n=this.shadow.querySelector(".modal-footer");n.style.display="",n.innerHTML=`
|
|
1181
1181
|
<button class="primary-btn" type="button" data-action="recalculate">Save & Recalculate</button>
|
|
1182
1182
|
`,this.bindCommon(),r.querySelectorAll(".chip").forEach(i=>{i.addEventListener("click",()=>{const a=i.dataset.sectionId;a&&this.openSection(a)})}),n.querySelector('[data-action="recalculate"]')?.addEventListener("click",()=>this.handleRecalculate())}renderForm(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-picker"),e.classList.add("view-form");const t=this.schemas.find(n=>n.id===this.activeSectionId),r=this.shadow.querySelector(".modal-header");r.innerHTML=`
|
|
1183
|
-
<button class="icon-btn back-btn" type="button" aria-label="Back">${
|
|
1184
|
-
<div class="modal-title">${
|
|
1185
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1183
|
+
<button class="icon-btn back-btn" type="button" aria-label="Back">${nf}</button>
|
|
1184
|
+
<div class="modal-title">${Zl(t?.title??"Edit")}</div>
|
|
1185
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${Xl}</button>
|
|
1186
1186
|
`;const o=this.shadow.querySelector(".modal-footer");o.style.display="none",o.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(o=>o.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(o=>{const n=o.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
|
|
1187
1187
|
<style>${this.css()}</style>
|
|
1188
1188
|
<div class="backdrop" part="backdrop">
|
|
@@ -1321,7 +1321,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1321
1321
|
border-radius: 16px 16px 0 0;
|
|
1322
1322
|
}
|
|
1323
1323
|
}
|
|
1324
|
-
`}}const
|
|
1324
|
+
`}}const Xl='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',nf='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';function of(s){return s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Zl(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class sf extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const o=this.getEntries(),n={...o[e]||{}};n[t]=r,o[e]=n,this.isRepeatable()?this.value=o:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=i=>{if(!i)return null;const a=t[i.field];return"equals"in i?a===i.equals:Array.isArray(i.in)?i.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],o=>{if(!this.fieldVisible(o,t)||o.type==="group")return;const n=t[o.id],i=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(i,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(i,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(i,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=o;Number.isNaN(a)?this.errors.set(i,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(i,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(i,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((o,n)=>this.renderEntry(o,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
|
|
1325
1325
|
<style>${this.css()}</style>
|
|
1326
1326
|
<div class="container">
|
|
1327
1327
|
<div class="scroll">
|
|
@@ -1596,7 +1596,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1596
1596
|
}
|
|
1597
1597
|
.save-btn:hover { filter: brightness(1.07); }
|
|
1598
1598
|
.save-btn:active { filter: brightness(0.95); }
|
|
1599
|
-
`}}function Et(s){return s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qe(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Mo(){const s=[["aikaara-chat-widget",Nl],["aikaara-chat-bubble",jl],["aikaara-chat-header",Ul],["aikaara-message-list",$l],["aikaara-message-bubble",Hl],["aikaara-chat-input",zl],["aikaara-typing-indicator",Vl],["aikaara-streaming-message",Kl],["aikaara-error-banner",Gl],["aikaara-template-renderer",Dh],["aikaara-system-pill",Hh],["aikaara-option-list",Wh],["aikaara-submit-action",zh],["aikaara-modal-action",Kh],["aikaara-text-input",Gh],["aikaara-chat",Yh],["aikaara-link-modal",Jh],["aikaara-compare-plans",Zh],["aikaara-smart-edit-modal",ef],["aikaara-schema-form",nf]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}Mo();function Zr(s,e,t=""){if(!e)return t;const r=e.split(".");let o=s;for(const n of r)if(o&&typeof o=="object"&&n in o)o=o[n];else return t;return typeof o=="string"?o:t}function Zl(s){try{const e=s.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Gt(s){return typeof s=="function"?await s():s}class ec{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Zl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Gt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",o={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,i);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=Zr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const f=Zr(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||f||"",h=Zr(l,this.descriptor.fullNamePath??"data.fullName"),b=Zr(l,this.descriptor.userPath??"data.userId"),y=Zl(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:h,userId:b,expiresAt:y},this.cache}}async function tc(s){const e={};for(const t of s.spec){const r=await of(t,s.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function of(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return sf(t);case"localStorage":return en(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return en(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return en(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return en(()=>document.querySelector(`meta[name="${af(t)}"]`)?.content??void 0);case"callback":{const r=e?.[s.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function sf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function en(s){try{return s()}catch{return}}function af(s){return s.replace(/["\\]/g,"\\$&")}const lf=1800;class rc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await tc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??lf;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const cf=3e4,uf=2e3,df=100;async function nc(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:s.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=hf(r);if(!o)throw new Xe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=ff(r);if(!o)throw new Xe("hash",`#${r}= not present`);return{token:o,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",o=typeof t.key=="string"&&t.key?t.key:"token",n=yf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:cf;return{token:await bf({type:r,key:o,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const o=pf(r);if(!o)throw new Xe("cookie",`cookie "${r}" not set`);return{token:o,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",o=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!o)throw new Xe("storage","storage.key not configured");const i=mf(r,o,n);if(!i)throw new Xe("storage",`${r}Storage["${o}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:uf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:df,i=await gf(r,o,n);if(!i)throw new Xe("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class ic{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await nc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function hf(s){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===s)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function ff(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function pf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function mf(s,e,t){if(!(typeof window>"u"))try{const o=(s==="session"?window.sessionStorage:window.localStorage).getItem(e);if(o==null)return;if(!t)return o;let n;try{n=JSON.parse(o)}catch{return o}const i=oc(n,t);return typeof i=="string"?i:void 0}catch{return}}async function gf(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=oc(window,s);if(typeof o=="string"&&o.length>0)return o;if(typeof o=="function")try{const n=o();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function bf(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=i=>{if(s.origins.length>0&&!s.origins.includes(i.origin))return;const a=i.data;if(!a||typeof a!="object")return;const l=a;if(s.type&&l.type!==s.type)return;const c=l[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function yf(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function oc(s,e){if(!e)return s;const t=e.split(".").filter(Boolean);let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function vf(){const s=typeof crypto<"u"?crypto:null;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues){const e=new Uint8Array(16);s.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const wf="aikaara_chat:requestId";function Ro(s,e,t){const r=`${wf}:${s}:${e}`;return t?`${r}:${t}`:r}function sc(s,e,t){try{return localStorage.getItem(Ro(s,e,t))}catch{return null}}function kf(s,e,t,r){try{localStorage.setItem(Ro(s,e,r),t)}catch{}}function _f(s,e,t){try{localStorage.removeItem(Ro(s,e,t))}catch{}}async function Lo(s,e,t="before-chat"){const r=s.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(o[u]=d);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,f)=>f in o?o[f]:""),i=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(i);if(u&&typeof u=="object"){const d={};for(const[f,g]of Object.entries(u))d[f]=i(g);return d}return u},a=await Gt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],f=n(d.url),g=d.method??(d.body?"POST":"GET"),h={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";h.authorization=x.replace("{token}",a)}const b={method:g,headers:h};d.body&&(h["content-type"]="application/json",b.body=JSON.stringify(i(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const x=await fetch(f,b);if(x.ok){k=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Sf(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${f} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${g} ${f} → ${y} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const E of d.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;d.capture.stripPrefix&&E.startsWith(d.capture.stripPrefix)&&(E=E.slice(d.capture.stripPrefix.length)),l[d.capture.as]=E,o[d.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function xf(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Lo(e,{sessionToken:s.sessionToken,userId:s.userId,projectId:s.projectId??"",slug:s.slug??"",identity:s.identity,serviceType:s.serviceType,userType:s.userType},"on-method-select")).captured:{}}function Sf(s,e){if(s===503||s===504||s===502)return!0;if(s===401||s===403)return e.trim().length===0;if(s===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function ac(s,e){const t=await fetch(s,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function lc(s,e){return s.replace("{projectId}",e).replace("{uuid}",vf().replace(/-/g,""))}function cc(s){const e=s._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Yl(r)))}async function uc(s){const e={...s.config??(s.configUrl?await ac(s.configUrl,s.configHeaders):{}),...s.overrides??{}};cc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const o=r?.projectId??"",n=s.identity.userId,i=s.conversationScope||void 0,a=s.forceNewConversation?null:sc(n,o,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??a??lc(l,o);(s.conversationId||!a||s.forceNewConversation)&&o&&kf(n,o,c,i);const u=await s.tokenProvider(),d=s.tokenProvider,f=s.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:d}:void 0,h=s.uploadAdapter??(e.uploadEndpoint?ko({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=s.historyAdapter??(e.historyApiBase?Ml({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:f}):void 0),y={transport:t,baseUrl:"",userToken:s.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:s.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:h,historyAdapter:b,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),s.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Ef(s){if(typeof s!="string")return s;const e=document.querySelector(s);if(!e)throw new Error(`mountFromSlug: container "${s}" not found`);return e}async function dc(s){const e=(s.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(s.slug)}`;let r=null;try{r=await ac(t,s.configHeaders)}catch(I){if(!s.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${s.slug}" — using fallbackConfig.`,I)}const o={...s.fallbackConfig??{},...r??{},...s.overrides??{}};if(cc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,P]of Object.entries(o.templates)){const O=`template:${I}`;o.components[O]||!P?.scriptUrl||!P?.render||(o.components[O]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth},!o.auth)throw new Error(`mountFromSlug: widget_configs/${s.slug} descriptor must include "auth" block`);let i=null,a=s.user.id,l=s.user.name,c="",u=s.user.token,d=null;const f=await Gt(s.user.token).catch(()=>""),g=typeof f=="string"&&f.length>0;if(!g&&o.sso?.tokenSource){d=new ic({descriptor:{provider:o.sso.provider,flow:o.sso.flow,skipLogin:o.sso.skipLogin,autoRefresh:o.sso.autoRefresh,tokenSource:o.sso.tokenSource,tokenSourceConfig:o.sso.tokenSourceConfig,fallback:o.sso.fallback,map:o.sso.map},initToken:s.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!g&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;i=await new rc({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let h="",b="";if(o.preflight&&o.preflight.length){const I=await Lo(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){h=I.captured.sessionToken;const P=h;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new ec(o.auth,u);if(h){const I=o.tiledesk?.projectId??"",P=I?sc(a,I):null,O=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=P??(I?lc(O,I):"");y.prime(h,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Gt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const k=d&&o.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Gt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?Ol({...x,authHeader:v}):x&&x.mode==="direct"?ko({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await uc({container:Ef(s.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Gt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some(j=>j.trigger==="on-method-select")?(await Lo(P,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Af(s){Mo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,o]of Object.entries(t)){const n=s[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(s),document.body.appendChild(e),e}function If(){const s=document.querySelector("aikaara-chat-widget");s&&s.remove()}const Tf="https://checkout.razorpay.com/v1/checkout.js";let lr=null;function cr(){return window}class hc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,o)=>{const n=r.name||"Open link",i=!!this.paidIdx[o];return`<button class="link${i?" paid":""}" data-i="${o}" type="button"${i?" disabled":""}><span class="lbl">${Cf(i?"Paid":n)}</span>`+(i?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const o=Number(r.dataset.i||0),n=e[o];n&&this.handleClick(o,n)})})}handleClick(e,t){const r=Pf(t),o=cr().__aikaara_descriptor__,n=o?.partnerPayment,i=o?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!i?.keyId){jf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}Mf(i.preferredBanksUrl,r,i.preferredBanksMethod,i.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Of().then(()=>this.openRazorpay(e,r,i,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,o){Rf(t,o).then(n=>{if(!n){Yt("Failed to generate payment link, please try again later");return}const i=(n.paymentStatus??"").toLowerCase();if(i==="paid"||i==="success"||i==="completed"){this.paidIdx[e]=!0,this.render(),Yt("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){Yt("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Lf(a);if(!u){window.open(a,"_blank"),Yt("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Nf(u,o.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{Yt(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),Yt("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,o){const n=cr(),i=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof i.mobile=="string"?a.prefill.contact=i.mobile:typeof i.phone=="string"&&(a.prefill.contact=i.phone),typeof i.email=="string"&&(a.prefill.email=i.email),typeof i.name=="string"?a.prefill.name=i.name:typeof i.userName=="string"&&(a.prefill.name=i.userName),Array.isArray(o)&&o.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Cf(s){return String(s??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Pf(s){if(typeof s.orderId=="string"&&s.orderId)return s.orderId;try{const e=new URL(s.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),o=r.get("orderId")||r.get("order_id");if(o)return o}}catch{}return null}function Of(){return typeof cr().Razorpay=="function"?Promise.resolve():lr||(lr=new Promise((s,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>s()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Tf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>s(),r.onerror=()=>{lr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),lr)}function Mf(s,e,t,r){if(!s)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=s.includes("{orderId}")?s.replace("{orderId}",encodeURIComponent(e)):s+(s.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),i=cr().__aikaara_runtime__??{};return(typeof i.getSessionToken=="function"?i.getSessionToken():typeof i.getChatJwt=="function"?i.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(f=>{if(typeof f=="string")return f;if(f&&typeof f=="object"){const g=f;return g.code||g.bankCode||g.bank_code||null}return null}).filter(f=>!!f)})}async function Rf(s,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,o=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(s)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(s),n=cr().__aikaara_runtime__??{},i=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};i&&(a.Authorization=`Bearer ${i}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:s}));const c=await fetch(o,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Lf(s){const r=window.screenX+Math.round((window.outerWidth-520)/2),o=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(s,"taxbuddy_payment",`width=520,height=680,left=${r},top=${o},scrollbars=yes,resizable=yes`)}function Nf(s,e,t){let r=!1;function o(){clearInterval(a),window.removeEventListener("message",i)}function n(l){r||(r=!0,o(),l())}function i(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{s.closed&&n(()=>t.onClose())},500);window.addEventListener("message",i)}function Yt(s){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(s);return}}catch{}console.warn("[payment_link]",s)}function jf(s,e){if(!s)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(s,e):window.open(s,"_blank","noopener,noreferrer")}function Uf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",hc)}const Bf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:hc,registerAikaaraPaymentLink:Uf},Symbol.toStringTag,{value:"Module"}));class fc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1599
|
+
`}}function Et(s){return s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Qe(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Mo(){const s=[["aikaara-chat-widget",jl],["aikaara-chat-bubble",Ul],["aikaara-chat-header",Bl],["aikaara-message-list",Fl],["aikaara-message-bubble",Wl],["aikaara-chat-input",Vl],["aikaara-typing-indicator",Kl],["aikaara-streaming-message",Gl],["aikaara-error-banner",Yl],["aikaara-template-renderer",Fh],["aikaara-system-pill",zh],["aikaara-option-list",Vh],["aikaara-submit-action",Kh],["aikaara-modal-action",Yh],["aikaara-text-input",Jh],["aikaara-chat",Qh],["aikaara-link-modal",Xh],["aikaara-compare-plans",tf],["aikaara-smart-edit-modal",rf],["aikaara-schema-form",sf]];for(const[e,t]of s)customElements.get(e)||customElements.define(e,t)}Mo();function Zr(s,e,t=""){if(!e)return t;const r=e.split(".");let o=s;for(const n of r)if(o&&typeof o=="object"&&n in o)o=o[n];else return t;return typeof o=="string"?o:t}function ec(s){try{const e=s.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Gt(s){return typeof s=="function"?await s():s}class tc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=ec(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Gt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",o={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,i);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=Zr(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const f=Zr(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||f||"",h=Zr(l,this.descriptor.fullNamePath??"data.fullName"),b=Zr(l,this.descriptor.userPath??"data.userId"),y=ec(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:h,userId:b,expiresAt:y},this.cache}}async function rc(s){const e={};for(const t of s.spec){const r=await af(t,s.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function af(s,e){const t=s.key??s.name;switch(s.source){case"cookie":return lf(t);case"localStorage":return en(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return en(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return en(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return en(()=>document.querySelector(`meta[name="${cf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[s.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default:return}}function lf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function en(s){try{return s()}catch{return}}function cf(s){return s.replace(/["\\]/g,"\\$&")}const uf=1800;class nc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await rc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(o,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??uf;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const df=3e4,hf=2e3,ff=100;async function ic(s){const{descriptor:e}=s,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!s.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:s.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=pf(r);if(!o)throw new Xe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=mf(r);if(!o)throw new Xe("hash",`#${r}= not present`);return{token:o,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",o=typeof t.key=="string"&&t.key?t.key:"token",n=wf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:df;return{token:await vf({type:r,key:o,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const o=gf(r);if(!o)throw new Xe("cookie",`cookie "${r}" not set`);return{token:o,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",o=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!o)throw new Xe("storage","storage.key not configured");const i=bf(r,o,n);if(!i)throw new Xe("storage",`${r}Storage["${o}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:hf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:ff,i=await yf(r,o,n);if(!i)throw new Xe("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class oc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await ic(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function pf(s){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===s)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function mf(s){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(s)??void 0}catch{return}}function gf(s){if(typeof document>"u")return;const e=encodeURIComponent(s),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===s||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function bf(s,e,t){if(!(typeof window>"u"))try{const o=(s==="session"?window.sessionStorage:window.localStorage).getItem(e);if(o==null)return;if(!t)return o;let n;try{n=JSON.parse(o)}catch{return o}const i=sc(n,t);return typeof i=="string"?i:void 0}catch{return}}async function yf(s,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=sc(window,s);if(typeof o=="string"&&o.length>0)return o;if(typeof o=="function")try{const n=o();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function vf(s){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${s.timeoutMs}ms`))},s.timeoutMs),n=i=>{if(s.origins.length>0&&!s.origins.includes(i.origin))return;const a=i.data;if(!a||typeof a!="object")return;const l=a;if(s.type&&l.type!==s.type)return;const c=l[s.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function wf(s){return s?s.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function sc(s,e){if(!e)return s;const t=e.split(".").filter(Boolean);let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function kf(){const s=typeof crypto<"u"?crypto:null;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues){const e=new Uint8Array(16);s.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const _f="aikaara_chat:requestId";function Ro(s,e,t){const r=`${_f}:${s}:${e}`;return t?`${r}:${t}`:r}function ac(s,e,t){try{return localStorage.getItem(Ro(s,e,t))}catch{return null}}function xf(s,e,t,r){try{localStorage.setItem(Ro(s,e,r),t)}catch{}}function Sf(s,e,t){try{localStorage.removeItem(Ro(s,e,t))}catch{}}async function Lo(s,e,t="before-chat"){const r=s.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(o[u]=d);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,f)=>f in o?o[f]:""),i=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(i);if(u&&typeof u=="object"){const d={};for(const[f,g]of Object.entries(u))d[f]=i(g);return d}return u},a=await Gt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],f=n(d.url),g=d.method??(d.body?"POST":"GET"),h={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";h.authorization=x.replace("{token}",a)}const b={method:g,headers:h};d.body&&(h["content-type"]="application/json",b.body=JSON.stringify(i(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const x=await fetch(f,b);if(x.ok){k=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Af(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${f} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${g} ${f} → ${y} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const E of d.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;d.capture.stripPrefix&&E.startsWith(d.capture.stripPrefix)&&(E=E.slice(d.capture.stripPrefix.length)),l[d.capture.as]=E,o[d.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Ef(s){const e=s.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Lo(e,{sessionToken:s.sessionToken,userId:s.userId,projectId:s.projectId??"",slug:s.slug??"",identity:s.identity,serviceType:s.serviceType,userType:s.userType},"on-method-select")).captured:{}}function Af(s,e){if(s===503||s===504||s===502)return!0;if(s===401||s===403)return e.trim().length===0;if(s===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function lc(s,e){const t=await fetch(s,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function cc(s,e){return s.replace("{projectId}",e).replace("{uuid}",kf().replace(/-/g,""))}function uc(s){const e=s._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Jl(r)))}async function dc(s){const e={...s.config??(s.configUrl?await lc(s.configUrl,s.configHeaders):{}),...s.overrides??{}};uc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const o=r?.projectId??"",n=s.identity.userId,i=s.conversationScope||void 0,a=s.forceNewConversation?null:ac(n,o,i),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=s.conversationId??a??cc(l,o);(s.conversationId||!a||s.forceNewConversation)&&o&&xf(n,o,c,i);const u=await s.tokenProvider(),d=s.tokenProvider,f=s.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:s.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...s.identity.departmentId?{departmentId:s.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:s.identity.senderFullname??s.identity.userName,tokenProvider:d}:void 0,h=s.uploadAdapter??(e.uploadEndpoint?ko({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=s.historyAdapter??(e.historyApiBase?Ml({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:f}):void 0),y={transport:t,baseUrl:"",userToken:s.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:s.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:s.identity.userName,departmentId:s.identity.departmentId,senderFullname:s.identity.senderFullname??s.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:h,historyAdapter:b,onError:s.onError,onMessage:s.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),s.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function If(s){if(typeof s!="string")return s;const e=document.querySelector(s);if(!e)throw new Error(`mountFromSlug: container "${s}" not found`);return e}async function hc(s){const e=(s.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(s.slug)}`;let r=null;try{r=await lc(t,s.configHeaders)}catch(I){if(!s.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${s.slug}" — using fallbackConfig.`,I)}const o={...s.fallbackConfig??{},...r??{},...s.overrides??{}};if(uc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,P]of Object.entries(o.templates)){const O=`template:${I}`;o.components[O]||!P?.scriptUrl||!P?.render||(o.components[O]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth},!o.auth)throw new Error(`mountFromSlug: widget_configs/${s.slug} descriptor must include "auth" block`);let i=null,a=s.user.id,l=s.user.name,c="",u=s.user.token,d=null;const f=await Gt(s.user.token).catch(()=>""),g=typeof f=="string"&&f.length>0;if(!g&&o.sso?.tokenSource){d=new oc({descriptor:{provider:o.sso.provider,flow:o.sso.flow,skipLogin:o.sso.skipLogin,autoRefresh:o.sso.autoRefresh,tokenSource:o.sso.tokenSource,tokenSourceConfig:o.sso.tokenSourceConfig,fallback:o.sso.fallback,map:o.sso.map},initToken:s.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,s.user.identity&&!s.user.identity.partnerToken&&(s.user.identity.partnerToken=I.token)}else if(!g&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(s.slug)}/sso_exchange`;i=await new nc({descriptor:o.sso,providers:s.user.credentialProviders,exchangeUrl:I}).get(),a=i.extUid||a,l=l??i.displayName,c=i.userToken}let h="",b="";if(o.preflight&&o.preflight.length){const I=await Lo(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:s.user.identity});if(I.captured.sessionToken){h=I.captured.sessionToken;const P=h;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new tc(o.auth,u);if(h){const I=o.tiledesk?.projectId??"",P=I?ac(a,I):null,O=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=P??(I?cc(O,I):"");y.prime(h,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Gt(s.user.token),identity:s.user.identity,slug:s.slug,configBase:e};const k=d&&o.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Gt(s.user.token)}`,E=s.hooks?.upload??(x&&x.mode==="presigned-3step"?Ol({...x,authHeader:v}):x&&x.mode==="direct"?ko({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await dc({container:If(s.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:s.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:s.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:s.conversationScope,onError:s.hooks?.onError,onMessage:s.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Gt(s.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some(j=>j.trigger==="on-method-select")?(await Lo(P,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:s.slug,identity:{...s.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Tf(s){Mo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,o]of Object.entries(t)){const n=s[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(s),document.body.appendChild(e),e}function Cf(){const s=document.querySelector("aikaara-chat-widget");s&&s.remove()}const Pf="https://checkout.razorpay.com/v1/checkout.js";let lr=null;function cr(){return window}class fc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,o)=>{const n=r.name||"Open link",i=!!this.paidIdx[o];return`<button class="link${i?" paid":""}" data-i="${o}" type="button"${i?" disabled":""}><span class="lbl">${Of(i?"Paid":n)}</span>`+(i?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const o=Number(r.dataset.i||0),n=e[o];n&&this.handleClick(o,n)})})}handleClick(e,t){const r=Mf(t),o=cr().__aikaara_descriptor__,n=o?.partnerPayment,i=o?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!i?.keyId){Bf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}Lf(i.preferredBanksUrl,r,i.preferredBanksMethod,i.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Rf().then(()=>this.openRazorpay(e,r,i,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,o){Nf(t,o).then(n=>{if(!n){Yt("Failed to generate payment link, please try again later");return}const i=(n.paymentStatus??"").toLowerCase();if(i==="paid"||i==="success"||i==="completed"){this.paidIdx[e]=!0,this.render(),Yt("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){Yt("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=jf(a);if(!u){window.open(a,"_blank"),Yt("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Uf(u,o.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{Yt(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),Yt("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,o){const n=cr(),i=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof i.mobile=="string"?a.prefill.contact=i.mobile:typeof i.phone=="string"&&(a.prefill.contact=i.phone),typeof i.email=="string"&&(a.prefill.email=i.email),typeof i.name=="string"?a.prefill.name=i.name:typeof i.userName=="string"&&(a.prefill.name=i.userName),Array.isArray(o)&&o.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Of(s){return String(s??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Mf(s){if(typeof s.orderId=="string"&&s.orderId)return s.orderId;try{const e=new URL(s.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),o=r.get("orderId")||r.get("order_id");if(o)return o}}catch{}return null}function Rf(){return typeof cr().Razorpay=="function"?Promise.resolve():lr||(lr=new Promise((s,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>s()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Pf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>s(),r.onerror=()=>{lr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),lr)}function Lf(s,e,t,r){if(!s)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=s.includes("{orderId}")?s.replace("{orderId}",encodeURIComponent(e)):s+(s.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),i=cr().__aikaara_runtime__??{};return(typeof i.getSessionToken=="function"?i.getSessionToken():typeof i.getChatJwt=="function"?i.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(f=>{if(typeof f=="string")return f;if(f&&typeof f=="object"){const g=f;return g.code||g.bankCode||g.bank_code||null}return null}).filter(f=>!!f)})}async function Nf(s,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,o=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(s)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(s),n=cr().__aikaara_runtime__??{},i=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};i&&(a.Authorization=`Bearer ${i}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:s}));const c=await fetch(o,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function jf(s){const r=window.screenX+Math.round((window.outerWidth-520)/2),o=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(s,"taxbuddy_payment",`width=520,height=680,left=${r},top=${o},scrollbars=yes,resizable=yes`)}function Uf(s,e,t){let r=!1;function o(){clearInterval(a),window.removeEventListener("message",i)}function n(l){r||(r=!0,o(),l())}function i(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{s.closed&&n(()=>t.onClose())},500);window.addEventListener("message",i)}function Yt(s){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(s);return}}catch{}console.warn("[payment_link]",s)}function Bf(s,e){if(!s)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(s,e):window.open(s,"_blank","noopener,noreferrer")}function Df(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",fc)}const $f=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:fc,registerAikaaraPaymentLink:Df},Symbol.toStringTag,{value:"Module"}));class pc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1600
1600
|
<style>
|
|
1601
1601
|
:host { display: block; margin-top: 8px; }
|
|
1602
1602
|
button {
|
|
@@ -1617,7 +1617,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1617
1617
|
button[disabled] { opacity: 0.5; cursor: not-allowed; }
|
|
1618
1618
|
</style>
|
|
1619
1619
|
<button type="button" ${e?"":"disabled"}>
|
|
1620
|
-
${
|
|
1620
|
+
${Ff(e?.name??"Open")}
|
|
1621
1621
|
<span aria-hidden="true">↗</span>
|
|
1622
1622
|
</button>
|
|
1623
|
-
`,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:o,orderId:n,extra:i,messageId:a}=this.payload,l=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:i,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)
|
|
1623
|
+
`,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:o,orderId:n,extra:i,messageId:a}=this.payload,l=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:i,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)$l(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=qf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:l,...i??{}},...a?{message_id:a}:{}}},bubbles:!0,composed:!0}))}}function Ff(s){return s.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function qf(){if(typeof document>"u")return null;let s=document.querySelector("aikaara-link-modal");if(!s){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),s=e}return s}function Hf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",pc)}const Wf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:pc,registerAikaaraLinkButton:Hf},Symbol.toStringTag,{value:"Module"}));return Pe.ActionCableClient=nn,Pe.AikaaraChatBubble=Ul,Pe.AikaaraChatClient=Cl,Pe.AikaaraChatHeader=Bl,Pe.AikaaraChatInput=Vl,Pe.AikaaraChatWidget=jl,Pe.AikaaraErrorBanner=Yl,Pe.AikaaraMessageBubble=Wl,Pe.AikaaraMessageList=Fl,Pe.AikaaraStreamingMessage=Gl,Pe.AikaaraTypingIndicator=Kl,Pe.ApiClient=Fo,Pe.ChannelSubscription=Uo,Pe.ConnectionManager=$o,Pe.ConversationManager=Ko,Pe.EventEmitter=mr,Pe.FormBridge=Gd,Pe.MessageStore=qo,Pe.SessionAuthAdapter=tc,Pe.SsoExchangeAdapter=nc,Pe.TiledeskTransport=Sl,Pe.TokenDiscoveryError=Xe,Pe.TokenDiscoveryReader=oc,Pe.clearPersistedConversationId=Sf,Pe.collectSsoCredentials=rc,Pe.createFetchUploadAdapter=ko,Pe.createPresigned3StepUploadAdapter=Ol,Pe.createTiledeskHistoryAdapter=Ml,Pe.discoverToken=ic,Pe.extractTiledeskFileEnvelope=Il,Pe.inferTiledeskRole=Al,Pe.isTiledeskSelfEcho=El,Pe.mount=Tf,Pe.mountFromSlug=hc,Pe.mountTenantWidget=dc,Pe.parseTiledeskTemplate=vo,Pe.registerComponents=Mo,Pe.runMethodSelectPreflight=Ef,Pe.unmount=Cf,Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"}),Pe})({});
|